text
stringlengths
2
1.04M
meta
dict
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_112) on Tue Jan 24 09:55:19 CST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Email (Play! API)</title> <meta name="date" content="2017-01-24"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Email (Play! API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Email.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../play/data/validation/CheckWithCheck.html" title="class in play.data.validation"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../play/data/validation/EmailCheck.html" title="class in play.data.validation"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?play/data/validation/Email.html" target="_top">Frames</a></li> <li><a href="Email.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Required&nbsp;|&nbsp;</li> <li><a href="#annotation.type.optional.element.summary">Optional</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#annotation.type.element.detail">Element</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">play.data.validation</div> <h2 title="Annotation Type Email" class="title">Annotation Type Email</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Retention.html?is-external=true" title="class or interface in java.lang.annotation">@Retention</a>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Retention.html?is-external=true#value--" title="class or interface in java.lang.annotation">value</a>=<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/RetentionPolicy.html?is-external=true#RUNTIME" title="class or interface in java.lang.annotation">RUNTIME</a>) <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Target.html?is-external=true" title="class or interface in java.lang.annotation">@Target</a>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Target.html?is-external=true#value--" title="class or interface in java.lang.annotation">value</a>={<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/ElementType.html?is-external=true#FIELD" title="class or interface in java.lang.annotation">FIELD</a>,<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/ElementType.html?is-external=true#PARAMETER" title="class or interface in java.lang.annotation">PARAMETER</a>}) @Constraint(checkWith=<a href="../../../play/data/validation/EmailCheck.html" title="class in play.data.validation">EmailCheck.class</a>) public @interface <span class="memberNameLabel">Email</span></pre> <div class="block">This field must be a valid email. Message key: validation.email $1: field name</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== ANNOTATION TYPE OPTIONAL MEMBER SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="annotation.type.optional.element.summary"> <!-- --> </a> <h3>Optional Element Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Optional Element Summary table, listing optional elements, and an explanation"> <caption><span>Optional Elements</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Optional Element and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../play/data/validation/Email.html#message--">message</a></span></code>&nbsp;</td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ ANNOTATION TYPE MEMBER DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="annotation.type.element.detail"> <!-- --> </a> <h3>Element Detail</h3> <a name="message--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>message</h4> <pre>public abstract&nbsp;<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;message</pre> <dl> <dt>Default:</dt> <dd>"validation.email"</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Email.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../play/data/validation/CheckWithCheck.html" title="class in play.data.validation"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../play/data/validation/EmailCheck.html" title="class in play.data.validation"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?play/data/validation/Email.html" target="_top">Frames</a></li> <li><a href="Email.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Required&nbsp;|&nbsp;</li> <li><a href="#annotation.type.optional.element.summary">Optional</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#annotation.type.element.detail">Element</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><a href=http://guillaume.bort.fr>Guillaume Bort</a> &amp; <a href=http://www.zenexity.fr>zenexity</a> - Distributed under <a href=http://www.apache.org/licenses/LICENSE-2.0.html>Apache 2 licence</a>, without any warrantly</small></p> </body> </html>
{ "content_hash": "2f9e9905412304fa1f5b04a994bef53a", "timestamp": "", "source": "github", "line_count": 223, "max_line_length": 691, "avg_line_length": 41.24215246636771, "alnum_prop": 0.6411873436990323, "repo_name": "chvrga/outdoor-explorer", "id": "19899aafd02000095c096aaf71b781fda6b424d7", "size": "9197", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "java/play-1.4.4/documentation/api/play/data/validation/Email.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "4720" }, { "name": "C", "bytes": "76128" }, { "name": "C++", "bytes": "31284" }, { "name": "CSS", "bytes": "107401" }, { "name": "HTML", "bytes": "1754737" }, { "name": "Java", "bytes": "2441299" }, { "name": "JavaScript", "bytes": "1405163" }, { "name": "PLpgSQL", "bytes": "1377" }, { "name": "Python", "bytes": "8991412" }, { "name": "Ruby", "bytes": "295601" }, { "name": "Shell", "bytes": "7499" }, { "name": "XQuery", "bytes": "544017" }, { "name": "XSLT", "bytes": "1099" } ], "symlink_target": "" }
require 'rails_helper' describe AgentType do # pending "add some examples to (or delete) #{__FILE__}" end # == Schema Information # # Table name: agent_types # # id :bigint not null, primary key # name :string not null # display_name :text # note :text # position :integer # created_at :datetime not null # updated_at :datetime not null #
{ "content_hash": "d2699c00528acb7308441f1e684f90b4", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 58, "avg_line_length": 22.157894736842106, "alnum_prop": 0.5700712589073634, "repo_name": "next-l/enju_leaf", "id": "0c9e714213d5b46d45b2c7bfef0226b3678c9057", "size": "421", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "spec/models/agent_type_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "42158" }, { "name": "Dockerfile", "bytes": "735" }, { "name": "HTML", "bytes": "743781" }, { "name": "JavaScript", "bytes": "386024" }, { "name": "Ruby", "bytes": "2482791" }, { "name": "Slim", "bytes": "1892" } ], "symlink_target": "" }
package com.tagmycode.plugin.gui; import java.awt.*; public class CenterLocation { private final int x; private final int y; public CenterLocation(Frame frame, Window window) { this(frame, window, CenterLocationType.CENTER_FRAME); } public CenterLocation(Frame frame, Window window, CenterLocationType centerLocationType) { int width; int height; int offsetX = 0; int offsetY = 0; if (frame == null || centerLocationType == CenterLocationType.CENTER_SCREEN) { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); width = (int) screenSize.getWidth(); height = (int) screenSize.getHeight(); } else { width = frame.getWidth(); height = frame.getHeight(); offsetX = frame.getX(); offsetY = frame.getY(); } x = offsetX + (width / 2) - (window.getWidth() / 2); y = offsetY + (height / 2) - (window.getHeight() / 2); } public int getX() { return x; } public int getY() { return y; } }
{ "content_hash": "4240ec87d6fee7470354db4ddbb2dec2", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 94, "avg_line_length": 28, "alnum_prop": 0.575, "repo_name": "massimozappino/tagmycode-java-plugin-framework", "id": "23117be97569a6c860aa28e57241ca4170af094f", "size": "1120", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/tagmycode/plugin/gui/CenterLocation.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "341328" }, { "name": "Shell", "bytes": "365" } ], "symlink_target": "" }
namespace Microsoft.ApplicationInsights.Wcf.Implementation { using System; using System.Collections.Generic; using System.ServiceModel.Description; internal class ClientContract { private IDictionary<string, ClientOperation> dictionary; public ClientContract(Type contractType) : this(ContractDescription.GetContract(contractType)) { } public ClientContract(ContractDescription description) { this.ContractType = description.ContractType; this.dictionary = new Dictionary<string, ClientOperation>(); foreach (var op in description.Operations) { var operationDesc = new ClientOperation(this.ContractType.Name, op); this.dictionary.Add(operationDesc.Action, operationDesc); } } public Type ContractType { get; private set; } public bool TryLookupByAction(string soapAction, out ClientOperation operation) { bool found = this.dictionary.TryGetValue(soapAction, out operation); if (!found) { // if we don't find it, try the catch all operation found = this.dictionary.TryGetValue("*", out operation); } return found; } } }
{ "content_hash": "0b7e65c2f44f1d4881ca2e62934e9dad", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 87, "avg_line_length": 32.53658536585366, "alnum_prop": 0.6154422788605697, "repo_name": "Microsoft/ApplicationInsights-SDK-Labs", "id": "558d07e0221a4014c2009b353b2f9fb5c29b49a3", "size": "1336", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WCF/Shared/Implementation/ClientContract.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "548" }, { "name": "C#", "bytes": "1394650" } ], "symlink_target": "" }
name: cljs.core/divide see also: --- ## Summary ## Details ## Examples
{ "content_hash": "61f3838ede447824ebdeb98059868fac", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 22, "avg_line_length": 8.222222222222221, "alnum_prop": 0.6351351351351351, "repo_name": "cljsinfo/cljs-api-docs", "id": "ed6f279f86357d938995de4382a517ddc3c048bf", "size": "78", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docfiles/cljs.core/divide.md", "mode": "33188", "license": "mit", "language": [ { "name": "Clojure", "bytes": "166023" } ], "symlink_target": "" }
from marketing_notifications_python.twilio import account_sid, auth_token, phone_number from twilio import twiml from twilio.rest import TwilioRestClient class TwilioServices: twilio_client = None def __init__(self): if TwilioServices.twilio_client is None: TwilioServices.twilio_client = TwilioRestClient(account_sid(), auth_token()) def send_message(self, to, message, image_url): TwilioServices.twilio_client.messages.create( to=to, from_=phone_number(), body=message, media_url=image_url ) def respond_message(self, message): response = twiml.Response() response.message(message) return response
{ "content_hash": "bf2ac65fd6ea6f5e76853285338ac944", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 88, "avg_line_length": 30.333333333333332, "alnum_prop": 0.6565934065934066, "repo_name": "devopsec/threatdetectionservice", "id": "bf3a2df899f0b4c7c9e94dcaa993414dce3a6e4f", "size": "728", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "api/notification/twilio/twilio_services.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "73" }, { "name": "CSS", "bytes": "60463" }, { "name": "HTML", "bytes": "73698" }, { "name": "JavaScript", "bytes": "6500" }, { "name": "Mako", "bytes": "412" }, { "name": "Python", "bytes": "166187" }, { "name": "Shell", "bytes": "24573" } ], "symlink_target": "" }
from . import * # so we don't have to type ndg.graph.graph(), etc., to get the classes from .annotate.annotate import annotate as annotate from .assess.assess import plot as plot from .assess import assess as assess from .algorithms import algorithms as algorithms from .utils import utils as utils from .algorithms import nddl version = "0.0.6"
{ "content_hash": "2cbb8334aaedf1d8af95f8497b51172e", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 70, "avg_line_length": 34.7, "alnum_prop": 0.7723342939481268, "repo_name": "neurodata/ndparse", "id": "6c167ace60fa3695d9c365eef27ab079f0be7f0c", "size": "347", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ndparse/__init__.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "77244" } ], "symlink_target": "" }
#import <WebCore/DOMObject.h> #import <WebCore/DOMNodeFilter-Protocol.h> // Not exported @interface DOMNodeFilter : DOMObject <DOMNodeFilter> { } - (short)acceptNode:(id)arg1; - (void)finalize; - (void)dealloc; @end
{ "content_hash": "8bf94db7e5c733146d4c3a742f085739", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 52, "avg_line_length": 13.117647058823529, "alnum_prop": 0.7174887892376681, "repo_name": "matthewsot/CocoaSharp", "id": "9587e9789ed67c57486046353674845a21d59364", "size": "363", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Headers/PrivateFrameworks/WebCore/DOMNodeFilter.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "259784" }, { "name": "C#", "bytes": "2789005" }, { "name": "C++", "bytes": "252504" }, { "name": "Objective-C", "bytes": "24301417" }, { "name": "Smalltalk", "bytes": "167909" } ], "symlink_target": "" }
package com.github.zion.accounts; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.Scope; import java.util.Map; /** * Base scope class */ public abstract class ScopeBase implements Scope { private static final Provider<Object> SEEDED_KEY_PROVIDER = new Provider<Object>() { public Object get() { throw new IllegalStateException("Object not seeded in this scope"); } }; /** * Returns a provider that always throws an exception complaining that the * object in question must be seeded before it can be injected. * * @return typed provider */ @SuppressWarnings({ "unchecked" }) public static <T> Provider<T> seededKeyProvider() { return (Provider<T>) SEEDED_KEY_PROVIDER; } public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) { return new Provider<T>() { public T get() { Map<Key<?>, Object> scopedObjects = getScopedObjectMap(key); @SuppressWarnings("unchecked") T current = (T) scopedObjects.get(key); if (current == null && !scopedObjects.containsKey(key)) { current = unscoped.get(); scopedObjects.put(key, current); } return current; } }; } /** * Get scoped object map * * @param key * @return map */ protected abstract <T> Map<Key<?>, Object> getScopedObjectMap(Key<T> key); }
{ "content_hash": "a9d99605c103dd3825317646c87283cd", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 88, "avg_line_length": 28.30909090909091, "alnum_prop": 0.5850995504174695, "repo_name": "DeLaSalleUniversity-Manila/ForkHub-macexcel", "id": "0c825dcd744be77f94827d20483a31b211b2a0eb", "size": "2148", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/github/zion/accounts/ScopeBase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7739" }, { "name": "HTML", "bytes": "386" }, { "name": "Java", "bytes": "1081183" }, { "name": "JavaScript", "bytes": "1212381" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Neodroid: /home/heider/Projects/Neodroid/Unity/Examples/Assets/droid/Runtime/Utilities/Misc/Procedural Directory Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="neodroidcropped124.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Neodroid &#160;<span id="projectnumber">0.2.0</span> </div> <div id="projectbrief">Machine Learning Environment Prototyping Tool</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('dir_c945ea9c9f16f9e74624ce5805c12c8c.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">Procedural Directory Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a> Files</h2></td></tr> <tr class="memitem:_game_object_cloner_8cs"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="_game_object_cloner_8cs.html">GameObjectCloner.cs</a> <a href="_game_object_cloner_8cs_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:_procedural_capsule_8cs"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="_procedural_capsule_8cs.html">ProceduralCapsule.cs</a> <a href="_procedural_capsule_8cs_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:_snake_space_filling_8cs"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="_snake_space_filling_8cs.html">SnakeSpaceFilling.cs</a> <a href="_snake_space_filling_8cs_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="dir_4f6666a8f2ab10bc970eb7559668f031.html">Runtime</a></li><li class="navelem"><a class="el" href="dir_d8da6fe6dddc6eeb0ed1e78a961648bc.html">Utilities</a></li><li class="navelem"><a class="el" href="dir_c9eadb85a3143b14eaf5fe5839688323.html">Misc</a></li><li class="navelem"><a class="el" href="dir_c945ea9c9f16f9e74624ce5805c12c8c.html">Procedural</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
{ "content_hash": "c21ce80962171e26bf966889ff44f21d", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 402, "avg_line_length": 48.648648648648646, "alnum_prop": 0.6877777777777778, "repo_name": "sintefneodroid/droid", "id": "0efb155ff2a7374efd1503a58792fd90ac4412ca", "size": "5400", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/cvs/dir_c945ea9c9f16f9e74624ce5805c12c8c.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "1475508" }, { "name": "HLSL", "bytes": "3678" }, { "name": "ShaderLab", "bytes": "157664" }, { "name": "Shell", "bytes": "204" } ], "symlink_target": "" }
#include "CPUTOSServicesWin.h" #include "tchar.h" CPUTOSServices* CPUTOSServices::mpOSServices = NULL; // Constructor //----------------------------------------------------------------------------- CPUTOSServices::CPUTOSServices():mhWnd(NULL) { //mCPUTMediaDirectory.clear(); mCPUTResourceDirectory.clear(); } // Destructor //----------------------------------------------------------------------------- CPUTOSServices::~CPUTOSServices() { //mCPUTMediaDirectory.clear(); mCPUTResourceDirectory.clear(); } // Singleton GetOSServices() //----------------------------------------------------------------------------- CPUTOSServices* CPUTOSServices::GetOSServices() { if(NULL==mpOSServices) mpOSServices = new CPUTOSServices(); return mpOSServices; } // Singleton destroyer //----------------------------------------------------------------------------- CPUTResult CPUTOSServices::DeleteOSServices() { if(mpOSServices) { delete mpOSServices; mpOSServices = NULL; } return CPUT_SUCCESS; } // Get the OS window dimensions //----------------------------------------------------------------------------- void CPUTOSServices::GetClientDimensions(int *pX, int *pY, int *pWidth, int *pHeight) { RECT windowRect; if(0==GetClientRect(mhWnd, &windowRect)) { return; } *pX = windowRect.left; *pY = windowRect.top; *pWidth = windowRect.right - windowRect.left; *pHeight = windowRect.bottom - windowRect.top; } // Get the OS window client area dimensions //----------------------------------------------------------------------------- void CPUTOSServices::GetClientDimensions(int *pWidth, int *pHeight) { RECT windowRect; if(0==GetClientRect(mhWnd, &windowRect)) { return; } *pWidth = windowRect.right - windowRect.left; *pHeight = windowRect.bottom - windowRect.top; } // Get the desktop dimensions //----------------------------------------------------------------------------- void CPUTOSServices::GetDesktopDimensions(int *pWidth, int *pHeight) { *pWidth = GetSystemMetrics(SM_CXFULLSCREEN); // alternate method: GetSystemMetrics(SM_CXSCREEN); *pHeight = GetSystemMetrics(SM_CYFULLSCREEN); // alternate method: GetSystemMetrics(SM_CYSCREEN); } // Returns true if the window is currently maximized //----------------------------------------------------------------------------- bool CPUTOSServices::IsWindowMaximized() { WINDOWPLACEMENT WindowPlacement; WindowPlacement.length = sizeof(WindowPlacement); GetWindowPlacement(mhWnd, &WindowPlacement); if(SW_SHOWMAXIMIZED == WindowPlacement.showCmd) { return true; } return false; } // Returns true if the window is currently minimized //----------------------------------------------------------------------------- bool CPUTOSServices::IsWindowMinimized() { WINDOWPLACEMENT WindowPlacement; WindowPlacement.length = sizeof(WindowPlacement); GetWindowPlacement(mhWnd, &WindowPlacement); if(SW_SHOWMAXIMIZED == WindowPlacement.showCmd) { return true; } return false; } // Returns true if the CPUT window is currently the 'focused' window on the // desktop //----------------------------------------------------------------------------- bool CPUTOSServices::DoesWindowHaveFocus() { HWND hFocusedWindow = GetActiveWindow(); if(mhWnd == hFocusedWindow) { return true; } return false; } // Retrieves the current working directory //----------------------------------------------------------------------------- CPUTResult CPUTOSServices::GetWorkingDirectory(cString *pPath) { TCHAR pPathAsTchar[CPUT_MAX_PATH]; DWORD result = GetCurrentDirectory(CPUT_MAX_PATH, pPathAsTchar); ASSERT( result, _L("GetCurrentDirectory returned 0.") ); *pPath = pPathAsTchar; return CPUT_SUCCESS; } // Sets the current working directory //----------------------------------------------------------------------------- CPUTResult CPUTOSServices::SetWorkingDirectory(const cString &path) { BOOL result = SetCurrentDirectory(path.c_str()); ASSERT( 0 != result, _L("Error setting current directory.") ); return CPUT_SUCCESS; } // Gets the location of the executable's directory //----------------------------------------------------------------------------- CPUTResult CPUTOSServices::GetExecutableDirectory(cString *pExecutableDir) { TCHAR pFilename[CPUT_MAX_PATH]; DWORD result = GetModuleFileName(NULL, pFilename, CPUT_MAX_PATH); ASSERT( 0 != result, _L("Unable to get executable's working directory.")); // strip off the executable name+ext cString ResolvedPathAndFilename; ResolveAbsolutePathAndFilename(pFilename, &ResolvedPathAndFilename); cString Drive, Dir, Filename, Ext; SplitPathAndFilename(ResolvedPathAndFilename, &Drive, &Dir, &Filename, &Ext); // store and return *pExecutableDir = Drive + Dir; return CPUT_SUCCESS; } // Split up the supplied path+fileName into its constituent parts //----------------------------------------------------------------------------- CPUTResult CPUTOSServices::SplitPathAndFilename(const cString &sourceFilename, cString *pDrive, cString *pDir, cString *pFileName, cString *pExtension) { TCHAR pSplitDrive[CPUT_MAX_PATH]; TCHAR pSplitDirs[CPUT_MAX_PATH]; TCHAR pSplitFile[CPUT_MAX_PATH]; TCHAR pSplitExt[CPUT_MAX_PATH]; #if defined (UNICODE) || defined(_UNICODE) #define SPLITPATH _wsplitpath_s #else #define SPLITPATH _splitpath_s #endif errno_t result = SPLITPATH(sourceFilename.c_str(), pSplitDrive, CPUT_MAX_PATH, pSplitDirs, CPUT_MAX_PATH, pSplitFile, CPUT_MAX_PATH, pSplitExt, CPUT_MAX_PATH); ASSERT( 0 == result, _L("Error splitting path") ); // return the items the user wants *pDrive = pSplitDrive; *pDir = pSplitDirs; *pFileName = pSplitFile; *pExtension = pSplitExt; return CPUT_SUCCESS; } // Takes a relative/full path+fileName and returns the absolute path with drive // letter, absolute path, fileName and extension of this file. // Truncates total path/file length to CPUT_MAX_PATH //----------------------------------------------------------------------------- CPUTResult CPUTOSServices::ResolveAbsolutePathAndFilename(const cString &fileName, cString *pResolvedPathAndFilename) { TCHAR pFullPathAndFilename[CPUT_MAX_PATH]; DWORD result = GetFullPathName(fileName.c_str(), CPUT_MAX_PATH, pFullPathAndFilename, NULL); ASSERT( 0 != result, _L("Error getting full path name") ); *pResolvedPathAndFilename = pFullPathAndFilename; return CPUT_SUCCESS; } // Verifies that file exists at specified path //----------------------------------------------------------------------------- CPUTResult CPUTOSServices::DoesFileExist(const cString &pathAndFilename) { // check for file existence // attempt to open it where they said it was FILE *pFile = NULL; #if defined (UNICODE) || defined(_UNICODE) errno_t err = _wfopen_s(&pFile, pathAndFilename.c_str(), _L("r")); #else errno_t err = fopen_s(&pFile, pathAndFilename.c_str(), _L("r")); #endif if(0 == err) { // yep - file exists fclose(pFile); return CPUT_SUCCESS; } // not found, translate the file error and return it return TranslateFileError(err); } // Verifies that directory exists. // Returns success if the directory exists and is readable (failure may mean // it's busy or permissions denied on win32) //----------------------------------------------------------------------------- CPUTResult CPUTOSServices::DoesDirectoryExist(const cString &path) { DWORD fileAttribs; #if defined (UNICODE) || defined(_UNICODE) fileAttribs = GetFileAttributesW(path.c_str()); #else fileAttribs = GetFileAttributesA(path.c_str()); #endif ASSERT( INVALID_FILE_ATTRIBUTES != fileAttribs, _L("Failed getting file attributes") ); return CPUT_SUCCESS; } // Open a file and return file pointer to it //----------------------------------------------------------------------------- CPUTResult CPUTOSServices::OpenFile(const cString &fileName, FILE **ppFilePointer) { #if defined (UNICODE) || defined(_UNICODE) errno_t err = _wfopen_s(ppFilePointer, fileName.c_str(), _L("r")); #else errno_t err = fopen_s(ppFilePointer, fileName.c_str(), "r"); #endif return TranslateFileError(err); } // Read the entire contents of a file and return a pointer/size to it //----------------------------------------------------------------------------- CPUTResult CPUTOSServices::ReadFileContents(const cString &fileName, UINT *pSizeInBytes, void **ppData) { FILE *pFile = NULL; #if defined (UNICODE) || defined(_UNICODE) errno_t err = _wfopen_s(&pFile, fileName.c_str(), _L("r")); #else errno_t err = fopen_s(&pFile, fileName.c_str(), "r"); #endif if(0 == err) { // get file size fseek(pFile, 0, SEEK_END); *pSizeInBytes = ftell(pFile); fseek (pFile, 0, SEEK_SET); // allocate buffer *ppData = (void*) new char[*pSizeInBytes]; ASSERT( ppData, _L("Out of memory") ); // read it all in UINT numBytesRead = (UINT) fread(*ppData, sizeof(char), *pSizeInBytes, pFile); ASSERT( numBytesRead == *pSizeInBytes, _L("File read byte count mismatch.") ); // close and return fclose(pFile); return CPUT_SUCCESS; } // some kind of file error, translate the error code and return it return TranslateFileError(err); } // Open the OS's 'open a file' dialog box //----------------------------------------------------------------------------- CPUTResult CPUTOSServices::OpenFileDialog(const cString &filter, cString *pfileName) { OPENFILENAME ofn; // common dialog box structure TCHAR szFile[260]; // buffer for file name // Initialize OPENFILENAME UNREFERENCED_PARAMETER(filter); ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = mhWnd; ofn.lpstrFilter = _L("All\0*.*\0Text\0*.TXT\0\0");//Filter.c_str(); //"All\0*.*\0Text\0*.TXT\0"; ofn.lpstrFile = szFile; // Set lpstrFile[0] to '\0' so that GetOpenFileName does not // use the contents of szFile to initialize itself. ofn.lpstrFile[0] = '\0'; ofn.nMaxFile = sizeof(szFile); ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; if(0==GetOpenFileName(&ofn)) { return CPUT_WARNING_CANCELED; } *pfileName = szFile; return CPUT_SUCCESS; } // Open a system dialog box //----------------------------------------------------------------------------- CPUTResult CPUTOSServices::OpenMessageBox(cString title, cString text) { ::MessageBox(NULL, text.c_str(), title.c_str(), MB_OK); return CPUT_SUCCESS; } // Returns whether the specified control key is pressed or not //----------------------------------------------------------------------------- bool CPUTOSServices::ControlKeyPressed(CPUTKey &key) { int nVirtKey; switch(key) { case KEY_LEFT_SHIFT: nVirtKey = VK_LSHIFT; break; case KEY_RIGHT_SHIFT: nVirtKey = VK_RSHIFT; break; case KEY_LEFT_CTRL: nVirtKey = VK_LCONTROL; break; case KEY_RIGHT_CTRL: nVirtKey = VK_RCONTROL; break; case KEY_LEFT_ALT: nVirtKey = VK_LMENU; break; case KEY_RIGHT_ALT: nVirtKey = VK_RMENU; break; default: return false; }; SHORT result = GetKeyState(nVirtKey); // return true/false if handled return (result & 0x8000)!=0; } // mouse // this function 'captures' the mouse and makes it ONLY available to this app // User cannot click on any other app until you call ReleaseMouse, so use this // carefully //----------------------------------------------------------------------------- void CPUTOSServices::CaptureMouse() { SetCapture(mhWnd); } // Releases a captured mouse //----------------------------------------------------------------------------- void CPUTOSServices::ReleaseMouse() { ReleaseCapture(); } // outputs a string to the debug out. // In Visual Studio - this is the Output pane //----------------------------------------------------------------------------- void CPUTOSServices::OutputConsoleString(cString &OutputString) { OutputDebugString(OutputString.c_str()); } // Did file open error indicate a returnable file/system problem? (or just not found) //----------------------------------------------------------------------------- bool CPUTOSServices::FileFoundButWithError(CPUTResult result) { bool IsError = false; // Is the result a file error code? switch(result) { case CPUT_ERROR_FILE_IO_ERROR: case CPUT_ERROR_FILE_NOT_ENOUGH_MEMORY: case CPUT_ERROR_FILE_PERMISSION_DENIED: case CPUT_ERROR_FILE_DEVICE_OR_RESOURCE_BUSY: case CPUT_ERROR_FILE_IS_A_DIRECTORY: case CPUT_ERROR_FILE_TOO_MANY_OPEN_FILES: case CPUT_ERROR_FILE_TOO_LARGE: case CPUT_ERROR_FILE_FILENAME_TOO_LONG: IsError = true; break; default: // nope - good to go IsError = false; } return IsError; } // Translate a file operation error code //----------------------------------------------------------------------------- CPUTResult CPUTOSServices::TranslateFileError(errno_t err) { if(0==err) { return CPUT_SUCCESS; } // see: http://msdn.microsoft.com/en-us/library/t3ayayh1.aspx // for list of all error codes CPUTResult result = CPUT_ERROR_FILE_ERROR; switch(err) { case ENOENT: result = CPUT_ERROR_FILE_NOT_FOUND; break; // file/dir not found case EIO: result = CPUT_ERROR_FILE_IO_ERROR; break; case ENXIO: result = CPUT_ERROR_FILE_NO_SUCH_DEVICE_OR_ADDRESS; break; case EBADF: result = CPUT_ERROR_FILE_BAD_FILE_NUMBER; break; case ENOMEM: result = CPUT_ERROR_FILE_NOT_ENOUGH_MEMORY; break; case EACCES: result = CPUT_ERROR_FILE_PERMISSION_DENIED; break; case EBUSY: result = CPUT_ERROR_FILE_DEVICE_OR_RESOURCE_BUSY; break; case EEXIST: result = CPUT_ERROR_FILE_EXISTS; break; case EISDIR: result = CPUT_ERROR_FILE_IS_A_DIRECTORY; break; case ENFILE: result = CPUT_ERROR_FILE_TOO_MANY_OPEN_FILES; break; case EFBIG: result = CPUT_ERROR_FILE_TOO_LARGE; break; case ENOSPC: result = CPUT_ERROR_FILE_DEVICE_FULL; break; case ENAMETOOLONG: result = CPUT_ERROR_FILE_FILENAME_TOO_LONG; break; default: // unknown file error type - assert so you can add it to the list ASSERT(0,_L("Unkown error code")); } return result; } #ifdef CPUT_GPA_INSTRUMENTATION // Allows you to get the global/domain-wide instrumentation markers needed // to mark events in GPA //----------------------------------------------------------------------------- void CPUTOSServices::GetInstrumentationPointers(__itt_domain **ppGPADomain, CPUT_GPA_INSTRUMENTATION_STRINGS eString, __itt_string_handle **ppGPAStringHandle) { *ppGPADomain = mpGPADomain; *ppGPAStringHandle = mppGPAStringHandles[eString]; } // Set the global/domain-wide instrumtation markers needed to mark events // in GPA //----------------------------------------------------------------------------- void CPUTOSServices::SetInstrumentationPointers(__itt_domain *pGPADomain, CPUT_GPA_INSTRUMENTATION_STRINGS eString, __itt_string_handle *pGPAStringHandle) { mpGPADomain = pGPADomain; mppGPAStringHandles[eString] = pGPAStringHandle; } #endif
{ "content_hash": "a1b396aed530ab5e2290f2358a2d1cdc", "timestamp": "", "source": "github", "line_count": 475, "max_line_length": 163, "avg_line_length": 34.24842105263158, "alnum_prop": 0.5659577083845586, "repo_name": "GameTechDev/CloudsGPUPro6", "id": "7136804617bd3f4f4a16ba59bfcf065bb6fcef52", "size": "17060", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CPUT/CPUT/CPUTOSServicesWin.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "292517" }, { "name": "C++", "bytes": "1086108" }, { "name": "FLUX", "bytes": "276226" }, { "name": "Rust", "bytes": "1079" }, { "name": "Shell", "bytes": "103" } ], "symlink_target": "" }
This is a my first Android application. For testing purposes... Content of this file will be updated periodically...
{ "content_hash": "6f81d980d3e903b66740afaa7317929e", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 63, "avg_line_length": 39, "alnum_prop": 0.7863247863247863, "repo_name": "dimkas71/CommercialAgent", "id": "0a1869476e0a0f0b56d62c7d14551f035e2a1d45", "size": "117", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Readme.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "955" } ], "symlink_target": "" }
var window = Ti.UI.createWindow({ backgroundColor:'white' }); var label = Ti.UI.createLabel(); window.add(label); window.open(); // TODO: write your module tests here var tieventkit = require('ti.eventkit'); Ti.API.info("module is => " + tieventkit); label.text = tieventkit.example(); Ti.API.info("module exampleProp is => " + tieventkit.exampleProp); tieventkit.exampleProp = "This is a test value"; if (Ti.Platform.name == "android") { var proxy = tieventkit.createExample({message: "Creating an example Proxy"}); proxy.printMessage("Hello world!"); }
{ "content_hash": "3e29f52090b76f3353bf78b0df29b503", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 78, "avg_line_length": 28.05, "alnum_prop": 0.7112299465240641, "repo_name": "okpala/IowaAlumni--iPhone-", "id": "3f175ebc2847cf0750e0a63192e232b1f042c8a4", "size": "781", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/iphone/ti.eventkit/0.1/example/app.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "152494" }, { "name": "C++", "bytes": "51991" }, { "name": "D", "bytes": "665535" }, { "name": "JavaScript", "bytes": "284330" }, { "name": "Objective-C", "bytes": "3583616" }, { "name": "Objective-C++", "bytes": "18015" }, { "name": "Shell", "bytes": "1282" } ], "symlink_target": "" }
<?php namespace ConnectHolland\PiccoloContentBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; /** * Piccolo content bundle * * @author Arthur Hoek <arthur@connectholland.nl> */ class ConnectHollandPiccoloContentBundle extends Bundle { }
{ "content_hash": "51edb0985a3de44d427d73e6105dc733", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 55, "avg_line_length": 16.933333333333334, "alnum_prop": 0.7755905511811023, "repo_name": "TimGroenenberg/PiccoloContentBundle", "id": "ac1df79958ecb8c6ca7b8a1c7f409b43617c77cc", "size": "254", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ConnectHollandPiccoloContentBundle.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "19629" }, { "name": "PHP", "bytes": "54688" } ], "symlink_target": "" }
package com.facebook.buck.cxx; import com.facebook.buck.android.packageable.AndroidPackageable; import com.facebook.buck.android.packageable.AndroidPackageableCollector; import com.facebook.buck.android.toolchain.ndk.NdkCxxPlatform; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.TargetConfiguration; import com.facebook.buck.core.rules.ActionGraphBuilder; import com.facebook.buck.core.rules.BuildRule; import com.facebook.buck.core.rules.BuildRuleParams; import com.facebook.buck.core.rules.BuildRuleResolver; import com.facebook.buck.core.rules.impl.NoopBuildRuleWithDeclaredAndExtraDeps; import com.facebook.buck.core.sourcepath.DefaultBuildTargetSourcePath; import com.facebook.buck.core.sourcepath.PathSourcePath; import com.facebook.buck.core.sourcepath.SourcePath; import com.facebook.buck.cxx.toolchain.CxxPlatform; import com.facebook.buck.cxx.toolchain.HeaderSymlinkTree; import com.facebook.buck.cxx.toolchain.linker.Linker; import com.facebook.buck.cxx.toolchain.nativelink.LegacyNativeLinkableGroup; import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableGroup; import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableInput; import com.facebook.buck.cxx.toolchain.nativelink.PlatformLockedNativeLinkableGroup; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.rules.args.SourcePathArg; import com.facebook.buck.util.types.Either; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedSet; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import java.util.function.Supplier; /** Fake implementation of {@link CxxLibraryGroup} for testing. */ public final class FakeCxxLibrary extends NoopBuildRuleWithDeclaredAndExtraDeps implements AbstractCxxLibraryGroup, NativeTestable, LegacyNativeLinkableGroup { private final BuildTarget publicHeaderTarget; private final BuildTarget publicHeaderSymlinkTreeTarget; private final BuildTarget privateHeaderTarget; private final BuildTarget privateHeaderSymlinkTreeTarget; private final BuildRule archive; private final BuildRule sharedLibrary; private final Path sharedLibraryOutput; private final String sharedLibrarySoname; private final ImmutableSortedSet<BuildTarget> tests; private final TransitiveCxxPreprocessorInputCache transitiveCxxPreprocessorInputCache = new TransitiveCxxPreprocessorInputCache(this); private final PlatformLockedNativeLinkableGroup.Cache linkableCache = LegacyNativeLinkableGroup.getNativeLinkableCache(this); public FakeCxxLibrary( BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams params, BuildTarget publicHeaderTarget, BuildTarget publicHeaderSymlinkTreeTarget, BuildTarget privateHeaderTarget, BuildTarget privateHeaderSymlinkTreeTarget, BuildRule archive, BuildRule sharedLibrary, Path sharedLibraryOutput, String sharedLibrarySoname, ImmutableSortedSet<BuildTarget> tests) { super(buildTarget, projectFilesystem, params); this.publicHeaderTarget = publicHeaderTarget; this.publicHeaderSymlinkTreeTarget = publicHeaderSymlinkTreeTarget; this.privateHeaderTarget = privateHeaderTarget; this.privateHeaderSymlinkTreeTarget = privateHeaderSymlinkTreeTarget; this.archive = archive; this.sharedLibrary = sharedLibrary; this.sharedLibraryOutput = sharedLibraryOutput; this.sharedLibrarySoname = sharedLibrarySoname; this.tests = tests; } @Override public PlatformLockedNativeLinkableGroup.Cache getNativeLinkableCompatibilityCache() { return linkableCache; } @Override public Iterable<CxxPreprocessorDep> getCxxPreprocessorDeps( CxxPlatform cxxPlatform, BuildRuleResolver ruleResolver) { return FluentIterable.from(getBuildDeps()).filter(CxxPreprocessorDep.class); } @Override public CxxPreprocessorInput getCxxPreprocessorInput( CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder) { return CxxPreprocessorInput.builder() .addIncludes( ImmutableCxxSymlinkTreeHeaders.of( CxxPreprocessables.IncludeType.LOCAL, DefaultBuildTargetSourcePath.of(publicHeaderSymlinkTreeTarget), Either.ofRight(DefaultBuildTargetSourcePath.of(publicHeaderSymlinkTreeTarget)), Optional.empty(), ImmutableSortedMap.of( Paths.get("header.h"), DefaultBuildTargetSourcePath.of(publicHeaderTarget)), HeaderSymlinkTree.class.getName())) .build(); } @Override public CxxPreprocessorInput getPrivateCxxPreprocessorInput( CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder) { return CxxPreprocessorInput.builder() .addIncludes( ImmutableCxxSymlinkTreeHeaders.of( CxxPreprocessables.IncludeType.LOCAL, DefaultBuildTargetSourcePath.of(privateHeaderSymlinkTreeTarget), Either.ofRight(DefaultBuildTargetSourcePath.of(privateHeaderSymlinkTreeTarget)), Optional.empty(), ImmutableSortedMap.of( Paths.get("header.h"), DefaultBuildTargetSourcePath.of(privateHeaderTarget)), HeaderSymlinkTree.class.getName())) .build(); } @Override public ImmutableMap<BuildTarget, CxxPreprocessorInput> getTransitiveCxxPreprocessorInput( CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder) { return transitiveCxxPreprocessorInputCache.getUnchecked(cxxPlatform, graphBuilder); } @Override public Iterable<NativeLinkableGroup> getNativeLinkableDeps(BuildRuleResolver ruleResolver) { return FluentIterable.from(getDeclaredDeps()).filter(NativeLinkableGroup.class); } @Override public Iterable<NativeLinkableGroup> getNativeLinkableExportedDeps( BuildRuleResolver ruleResolver) { return FluentIterable.from(getDeclaredDeps()).filter(NativeLinkableGroup.class); } @Override public NativeLinkableInput getNativeLinkableInput( CxxPlatform cxxPlatform, Linker.LinkableDepType type, boolean forceLinkWhole, ActionGraphBuilder graphBuilder, TargetConfiguration targetConfiguration, boolean preferStripped) { return type == Linker.LinkableDepType.STATIC ? NativeLinkableInput.of( ImmutableList.of(SourcePathArg.of(archive.getSourcePathToOutput())), ImmutableSet.of(), ImmutableSet.of()) : NativeLinkableInput.of( ImmutableList.of(SourcePathArg.of(sharedLibrary.getSourcePathToOutput())), ImmutableSet.of(), ImmutableSet.of()); } @Override public NativeLinkableGroup.Linkage getPreferredLinkage(CxxPlatform cxxPlatform) { return Linkage.ANY; } @Override public Iterable<AndroidPackageable> getRequiredPackageables( BuildRuleResolver ruleResolver, Supplier<Iterable<NdkCxxPlatform>> ndkCxxPlatforms) { return ImmutableList.of(); } @Override public void addToCollector( ActionGraphBuilder graphBuilder, AndroidPackageableCollector collector) {} @Override public ImmutableMap<String, SourcePath> getSharedLibraries( CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder) { return ImmutableMap.of( sharedLibrarySoname, PathSourcePath.of(getProjectFilesystem(), sharedLibraryOutput)); } @Override public boolean isTestedBy(BuildTarget testTarget) { return tests.contains(testTarget); } }
{ "content_hash": "ebbf3d24fb2e18903047abdc01bee9fc", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 97, "avg_line_length": 41.329787234042556, "alnum_prop": 0.777992277992278, "repo_name": "JoelMarcey/buck", "id": "69134498351821c5a4271ee829c3c9bb615a734a", "size": "8386", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "test/com/facebook/buck/cxx/FakeCxxLibrary.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "579" }, { "name": "Batchfile", "bytes": "2093" }, { "name": "C", "bytes": "255521" }, { "name": "C#", "bytes": "237" }, { "name": "C++", "bytes": "10992" }, { "name": "CSS", "bytes": "54863" }, { "name": "D", "bytes": "1017" }, { "name": "Go", "bytes": "16819" }, { "name": "Groovy", "bytes": "3362" }, { "name": "HTML", "bytes": "6115" }, { "name": "Haskell", "bytes": "895" }, { "name": "IDL", "bytes": "385" }, { "name": "Java", "bytes": "19430296" }, { "name": "JavaScript", "bytes": "932672" }, { "name": "Kotlin", "bytes": "2079" }, { "name": "Lex", "bytes": "2731" }, { "name": "Makefile", "bytes": "1816" }, { "name": "Matlab", "bytes": "47" }, { "name": "OCaml", "bytes": "4384" }, { "name": "Objective-C", "bytes": "138150" }, { "name": "Objective-C++", "bytes": "34" }, { "name": "PowerShell", "bytes": "244" }, { "name": "Prolog", "bytes": "858" }, { "name": "Python", "bytes": "1786899" }, { "name": "Roff", "bytes": "1109" }, { "name": "Rust", "bytes": "3618" }, { "name": "Scala", "bytes": "4906" }, { "name": "Shell", "bytes": "49876" }, { "name": "Smalltalk", "bytes": "3355" }, { "name": "Standard ML", "bytes": "15" }, { "name": "Swift", "bytes": "6897" }, { "name": "Thrift", "bytes": "26256" }, { "name": "Yacc", "bytes": "323" } ], "symlink_target": "" }
The `jaxrs` library adds tooling to implement JAX-RS web services. It combines the powers of the Spring framework, the Apache CXF framework, the Jackson JSON mapper and the Eclipse Jetty web server. To include it add the maven dependency to your POM file. It will then automatically configure a Jetty web server running on a given port and start a CXF JAX-RS handler into the running Jetty server. By default all beans annotated with `@JaxRsComponent` will be registered as provider or endpoint respectively. Additionally several extra features are implemented. You can inject the `DvalinRSContext` to get easier access to some of the features. ### Monitoring For every request an instance of `de.taimos.dvalin.jaxrs.monitoring.InvocationInstance` will be registered into the MessageContext. It will contain a unique request id and will measure the runtime of the request for monitoring purpose. It also populates the request id field of the context. ### Providers You can activate preconfigured JacksonProvider or WebExceptionMapper by subclassing the respective type and annotate it with `@JaxRsComponent`. ### Remote service By annotating a private field of a JAX-RS client interface with `@RemoteService` dvalin will automatically create a JAX-RS client proxy and then inject it like any other autowired bean into the desired location. You can provide the base URL of the service or use defined system properties to resolve the URL of the service. ### Swagger The JAX-RS web service it automatically documented using the Swagger specification and published as `swagger.{json|yaml}` and `openapi.{json|yaml}` on the root of your API URL. Also a graphical Swagger ui is served under `/swagger-ui`. By providing a bean of type `OpenApiModification` you can alter the API definition manually. ### WebSocket support You can publish a WebSocket just by annotating any class with `@WebSocket`. If you like you can use the abstract `ServerJSONWebSocketAdapter` as a base class. For the client side (e.g. in tests) you can use the `ClientSocketAdapter` to connect the the published socket. ### Security There are several helper classes and beans to provide identity and access management functionality. #### Authentication You can subclass the abstract `AuthorizationProvider` and return SecurityContexts in the methods to implement or you can provide implementations of predefined bean interfaces to activate ready-to-use authentication filters for BasicAuth or token based authentication. These interfaces are the `IBasicAuthUserDAO` or the `ITokenAuthUserDAO`. If you put an implementation in your Spring context the JAX-RS filter will be deployed using the `@BeanAvailable` annotation of the core library. #### Authorization To limit access to sensitive resources you can use the injectable `DvalinRSContext` that provides methods to retrieve information about the logged in user or to assert given roles. Additionally dvalin registers filters that support the following annotations to limit access to resources. * `@RolesAllowed` - only users having at least one of the provided roles are granted access * `@LoggedIn` - only request that contain a valid logged in user are processed To help in protecting user credentials the class `HashedPassword` implements everything needed to store password hashes secured by the SHA-512 function using a 512 bit salt and a dynamic number of iterations. ### Configuration Several settings of the dvalin framework can be customized using system properties which are described in `de.taimos.dvalin.jaxrs.SpringCXFProperties`. ### Testing moved to `test` sub-project.
{ "content_hash": "33cc23328ce20fe95adc90445463bd3e", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 154, "avg_line_length": 52.84057971014493, "alnum_prop": 0.8008776741634668, "repo_name": "taimos/dvalin", "id": "06b041168157ee981d9f943ffcd30bd3547097ca", "size": "3657", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jaxrs/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "533" }, { "name": "HTML", "bytes": "3736" }, { "name": "Java", "bytes": "1249209" }, { "name": "Shell", "bytes": "1497" } ], "symlink_target": "" }
package us.kbase.typedobj.core; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.math.BigInteger; import com.fasterxml.jackson.core.Base64Variant; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonStreamContext; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.core.SerializableString; import com.fasterxml.jackson.core.TreeNode; import com.fasterxml.jackson.core.Version; public class NullJsonGenerator extends JsonGenerator { public NullJsonGenerator() { } @Override public JsonGenerator setCodec(ObjectCodec oc) { return null; } @Override public ObjectCodec getCodec() { return null; } @Override public Version version() { return null; } @Override public JsonGenerator enable(Feature f) { return null; } @Override public JsonGenerator disable(Feature f) { return null; } @Override public boolean isEnabled(Feature f) { return false; } @Override public JsonGenerator useDefaultPrettyPrinter() { return null; } @Override public void writeStartArray() throws IOException, JsonGenerationException { } @Override public void writeEndArray() throws IOException, JsonGenerationException { } @Override public void writeStartObject() throws IOException, JsonGenerationException { } @Override public void writeEndObject() throws IOException, JsonGenerationException { } @Override public void writeFieldName(String name) throws IOException, JsonGenerationException { } @Override public void writeFieldName(SerializableString name) throws IOException, JsonGenerationException { } @Override public void writeString(String text) throws IOException, JsonGenerationException { } @Override public void writeString(char[] text, int offset, int len) throws IOException, JsonGenerationException { } @Override public void writeString(SerializableString text) throws IOException, JsonGenerationException { } @Override public void writeRawUTF8String(byte[] text, int offset, int length) throws IOException, JsonGenerationException { } @Override public void writeUTF8String(byte[] text, int offset, int length) throws IOException, JsonGenerationException { } @Override public void writeRaw(String text) throws IOException, JsonGenerationException { } @Override public void writeRaw(String text, int offset, int len) throws IOException, JsonGenerationException { } @Override public void writeRaw(char[] text, int offset, int len) throws IOException, JsonGenerationException { } @Override public void writeRaw(char c) throws IOException, JsonGenerationException { } @Override public void writeRawValue(String text) throws IOException, JsonGenerationException { } @Override public void writeRawValue(String text, int offset, int len) throws IOException, JsonGenerationException { } @Override public void writeRawValue(char[] text, int offset, int len) throws IOException, JsonGenerationException { } @Override public void writeBinary(Base64Variant b64variant, byte[] data, int offset, int len) throws IOException, JsonGenerationException { } @Override public int writeBinary(Base64Variant b64variant, InputStream data, int dataLength) throws IOException, JsonGenerationException { return 0; } @Override public void writeNumber(int v) throws IOException, JsonGenerationException { } @Override public void writeNumber(long v) throws IOException, JsonGenerationException { } @Override public void writeNumber(BigInteger v) throws IOException, JsonGenerationException { } @Override public void writeNumber(double d) throws IOException, JsonGenerationException { } @Override public void writeNumber(float f) throws IOException, JsonGenerationException { } @Override public void writeNumber(BigDecimal dec) throws IOException, JsonGenerationException { } @Override public void writeNumber(String encodedValue) throws IOException, JsonGenerationException, UnsupportedOperationException { } @Override public void writeBoolean(boolean state) throws IOException, JsonGenerationException { } @Override public void writeNull() throws IOException, JsonGenerationException { } @Override public void writeObject(Object pojo) throws IOException, JsonProcessingException { } @Override public void writeTree(TreeNode rootNode) throws IOException, JsonProcessingException { } @Override public void copyCurrentEvent(JsonParser jp) throws IOException, JsonProcessingException { } @Override public void copyCurrentStructure(JsonParser jp) throws IOException, JsonProcessingException { } @Override public JsonStreamContext getOutputContext() { return null; } @Override public void flush() throws IOException { } @Override public boolean isClosed() { return false; } @Override public void close() throws IOException { } @Override public int getFeatureMask() { return 0; } @Override public JsonGenerator setFeatureMask(int values) { return null; } }
{ "content_hash": "276999e6ea53ed04616090a75f2f9b31", "timestamp": "", "source": "github", "line_count": 246, "max_line_length": 78, "avg_line_length": 21.410569105691057, "alnum_prop": 0.7748243782039111, "repo_name": "kbase/workspace_deluxe", "id": "37c45470a18ccfbe012873d53de8919350d1040e", "size": "5267", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "src/us/kbase/typedobj/core/NullJsonGenerator.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "962" }, { "name": "Dockerfile", "bytes": "2301" }, { "name": "HTML", "bytes": "596672" }, { "name": "Java", "bytes": "4368308" }, { "name": "JavaScript", "bytes": "49595" }, { "name": "Makefile", "bytes": "4102" }, { "name": "Perl", "bytes": "511276" }, { "name": "Python", "bytes": "429991" }, { "name": "Roff", "bytes": "119891" }, { "name": "Ruby", "bytes": "87119" }, { "name": "Shell", "bytes": "5186" } ], "symlink_target": "" }
using System; using System.Threading; using System.Threading.Tasks; namespace NStore.Core.Persistence { public class WriteJob : IChunk { public enum WriteResult { None, Committed, DuplicatedIndex, DuplicatedOperation, DuplicatedPosition } // in public string PartitionId { get; private set; } public long Index { get; private set; } public object Payload { get; private set; } public string OperationId { get; private set; } // out public long Position { get; private set; } public WriteResult Result { get; private set; } public IChunk Chunk { get; private set; } public WriteJob(string partitionId, long index, object payload, string operationId) { PartitionId = partitionId; Index = index; Payload = payload; OperationId = operationId; } public virtual void Succeeded(IChunk chunk) { this.Result = WriteResult.Committed; this.Chunk = chunk; this.Position = chunk.Position; } public virtual void Failed(WriteResult result ) { this.Result = result; } } public interface IEnhancedPersistence { Task AppendBatchAsync( WriteJob[] queue, CancellationToken cancellationToken ); } }
{ "content_hash": "0256330d682b4d7b422fa3bb60a0229d", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 91, "avg_line_length": 24.65, "alnum_prop": 0.5632183908045977, "repo_name": "ProximoSrl/NStore", "id": "f8117c729be1c11883e99f2f92f1904c9ce95b8a", "size": "1479", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "src/NStore.Core/Persistence/IEnhancedPersistence.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "497014" }, { "name": "HTML", "bytes": "3755" }, { "name": "PowerShell", "bytes": "6317" }, { "name": "Shell", "bytes": "2935" } ], "symlink_target": "" }
package cmd import ( "github.com/cilium/cilium/pkg/kvstore" "github.com/spf13/cobra" ) var kvstoreDeleteCmd = &cobra.Command{ Use: "delete [options] <key>", Short: "Delete a key", Example: "cilium kvstore delete --recursive foo", Run: func(cmd *cobra.Command, args []string) { setupKvstore() if len(args) < 1 { Fatalf("Please specify a key or key prefix to delete") } if recursive { if err := kvstore.DeletePrefix(args[0]); err != nil { Fatalf("Unable to delete keys: %s", err) } } else { if err := kvstore.Delete(args[0]); err != nil { Fatalf("Unable to delete key: %s", err) } } }, } func init() { kvstoreCmd.AddCommand(kvstoreDeleteCmd) kvstoreDeleteCmd.Flags().BoolVar(&recursive, "recursive", false, "Recursive lookup") }
{ "content_hash": "6933fcd631c1834beae41a5b777e7c55", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 85, "avg_line_length": 22.37142857142857, "alnum_prop": 0.6500638569604087, "repo_name": "eloycoto/cilium", "id": "ffed7c636d9dbc04d784e4e458230f4852df3f5f", "size": "1378", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "cilium/cmd/kvstore_delete.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "574376" }, { "name": "C++", "bytes": "107097" }, { "name": "Dockerfile", "bytes": "5608" }, { "name": "Go", "bytes": "3263034" }, { "name": "Makefile", "bytes": "27993" }, { "name": "Perl 6", "bytes": "4948" }, { "name": "Python", "bytes": "19920" }, { "name": "Ruby", "bytes": "10295" }, { "name": "Shell", "bytes": "219547" }, { "name": "TeX", "bytes": "347" }, { "name": "sed", "bytes": "4191" } ], "symlink_target": "" }
::: tip Vue.js reactivity system is based on [ES5 getter/setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get) which have limitations. In the future, Vue will use [ES6 proxies](https://caniuse.com/#feat=proxy) for it's reactivity system, and the limitations below will disappear :tada:. We will however leave the option to keep the old reactivity system on a given project for IE 11 compatibility. ::: ## Objects Observation When you assign an Object to a `@Data` of a Component, all it's properties **must** already be set in the JS world to be observed. This means that they must have a value set, even if null. In this case the `text` property **WON'T** be observed: ```java public class Todo { private String text; public Todo() {} public void setText(String text) { this.text = text; } } @Component public class MyComponent implements IsVueComponent, HasCreated { @Data Todo todo; @Override public void created() { todo = new Todo(); todo.setText("Bob"); // Won't update the Vue :( } } ``` But in these cases it will **WILL**: ```java // Any of those public class Todo { private String text = null; ... } public class Todo { private String text; public Todo() { this.text = null; } ... } public class Todo { private String text = "Default Value"; ... } public class Todo { private String text; public Todo() { this.text = "Default Value"; } ... } public class Todo { private String text; public Todo(String defaultText) { this.text = defaultText; } ... } // The text property will be observable in your Component @Component public class MyComponent implements IsVueComponent, HasCreated { @Data Todo todo; @Override public void created() { todo = new Todo(); todo.setText("Bob"); // Will update the Vue! } } ``` If you don't have the control over the Java class, you can also set a value before attaching your object to your Component data model. ```java // This class comes from some library, I can't change it! How do I make text reactive? public class Todo { private String text; public Todo() {} public void setText(String text) { this.text = text; } } @Component public class MyComponent implements IsVueComponent, HasCreated { @Data todo; @Override public void created() { Todo myTodo = new Todo(); // We store in a local variable myTodo.setText("Bob"); // We set the value, this define the property this.todo = myTodo; // We attach myTodo, it starts being observed, Bob displays in the Vue! todo.setText("Mickael"); // Will update the Vue to Mickael! } } ``` ## Java Collections Observation Due to JavaScript getter/setter limitations [Vue.js cannot observe some changes on JavaScript Arrays](https://vuejs.org/v2/guide/list.html#Array-Change-Detection). All Java Collections have a JavaScript implementation provided by GWT. In some cases, these implementations use JavaScript Arrays to store their data. This mean that some Java Collection cannot be automatically observed by Vue.js. Luckily, Vue GWT goes around this limitation for you by wrapping java Collections mutation methods. When calling any of these methods, Vue GWT will warn Vue.js observer to trigger a view update. The wrapped methods are: - For `List`: `add`, `addAll`, `clear`, `remove`, `removeAll`, `retainAll`, `set` - For `Set`: `add`, `addAll`, `clear`, `remove`, `removeAll`, `retainAll` - For `Map`: `put`, `putAll`, `putIfAbsent`, `replace`, `clear`, `remove` For this to work the name of these methods must not change when your code is optimized by GWT. To tell GWT that you want this, you must always: - Use either `List`, `Set` or `Map` for your property type, never the concrete type. - Always use the `@JsProperty` annotation on top of your collection fields, on Class that will be in a `@Data`. Here is a valid example of a `UsersRepository` containing a collection of Users: ```java class UsersRepository { @JsProperty List<User> myUsers; } ``` ::: tip Vue GWT will check for you all your `@Data` fields (recursively) and all your `@Prop` fields (non-recursively) at compile time to make sure they respect the rules on collection fields. If they don't Vue GWT will throw an explicit compile time exception. If you wish to disable this error on a specific field you can add the annotation `@SuppressWarnings("vue-gwt-collections")` to it. :::
{ "content_hash": "f65cdbfbf4479b4b6f110cbec2417ada", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 184, "avg_line_length": 30.83783783783784, "alnum_prop": 0.6923751095530236, "repo_name": "Axellience/vue-gwt", "id": "e6579c3006ae0f109e65d0e70928082452258902", "size": "4585", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/guide/essentials/reactivity-system.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "340" }, { "name": "HTML", "bytes": "12558" }, { "name": "Java", "bytes": "916116" }, { "name": "JavaScript", "bytes": "88043" }, { "name": "Shell", "bytes": "297" } ], "symlink_target": "" }
 namespace _07.CakeIngridients { using System; public class Program { public static void Main() { string ingridient = ""; int countOfIngridients = 0; while (true) { ingridient = Console.ReadLine(); if (ingridient == "Bake!") { break; } Console.WriteLine($"Adding ingredient {ingridient}."); countOfIngridients++; } Console.WriteLine($"Preparing cake with {countOfIngridients} ingredients."); } } }
{ "content_hash": "99df6a4a134af447f53a8df1299c5811", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 88, "avg_line_length": 22.535714285714285, "alnum_prop": 0.4595879556259905, "repo_name": "DannyBerova/Exercises-Programming-Fundamentals-Extended-May-2017", "id": "e3f0a69acd65a45c865d74a9cf17ecceba137859", "size": "633", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ConditionalStatementsAndLoopsExercises/07.CakeIngridients/07.CakeIngridients.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "810676" } ], "symlink_target": "" }
namespace Spore3D { ObjectManager *ObjectManager::getInstance() { static ObjectManager _instance; return &_instance; } ObjectManager::_ObjectCreate ObjectManager::_objectCreate; ObjectManager::_ObjectCreate::_ObjectCreate() { ObjectManager::getInstance(); } bool ObjectManager::init(void) { if (nullptr != m_DB) { delete m_DB; } m_DB = new ObjectManagerDB(); if (nullptr == m_DB) return false; registerAllComponentTypes(); return true; } bool ObjectManager::addComponentWithComponent(const CObjectId objectId, Component *component) { if (nullptr == component) return false; if (m_DB->mObjectMap.find(objectId) == m_DB->mObjectMap.end()) return nullptr; if (m_DB->mComponentTypeInfoMap.find(component->getTypeId()) == m_DB->mComponentTypeInfoMap.end()) return false; component->gameObject = m_DB->mObjectMap[objectId]; component->transform = component->gameObject->transform; m_DB->mComponentTypeToComponentMap[component->getTypeId()][objectId].push_back(component); return true; } Component *ObjectManager::addComponentWithComponentTypeId(const CObjectId objectId, const ComponentTypeId typeId) { if (m_DB->mObjectMap.find(objectId) == m_DB->mObjectMap.end()) return nullptr; auto it = m_DB->mComponentTypeInfoMap.find(typeId); if (it == m_DB->mComponentTypeInfoMap.end()) return nullptr; Component *cmp = static_cast<Component*>((*(it->second->creationMethod))(it->second->typeName)); if (nullptr == cmp) return nullptr; cmp->gameObject = m_DB->mObjectMap[objectId]; cmp->transform = cmp->gameObject->transform; m_DB->mComponentTypeToComponentMap[typeId][objectId].push_back(cmp); return cmp; } Component *ObjectManager::addComponentWithComponentTypeName(const CObjectId objectId, const std::string &typeName) { Hash typeId(typeName); return addComponentWithComponentTypeId(objectId, typeId.get()); } void ObjectManager::getComponentByComponentTypeId(const CObjectId objectId, const ComponentTypeId typeId, std::vector<Component *> &componentList) const { if (m_DB->mObjectMap.find(objectId) == m_DB->mObjectMap.end()) return; if (m_DB->mComponentTypeToComponentMap.find(typeId) == m_DB->mComponentTypeToComponentMap.end()) return; componentList = m_DB->mComponentTypeToComponentMap[typeId][objectId]; } void ObjectManager::getComponentByComponentTypeName(const CObjectId objectId, const std::string &typeName, std::vector<Component *> &componentList) const { return getComponentByComponentTypeId(objectId, Component::genTypeId(typeName), componentList); } void ObjectManager::getComponents(const CObjectId objectId, std::vector<Component*> &componentList) const { if (m_DB->mObjectMap.find(objectId) == m_DB->mObjectMap.end()) return; for (const auto &it : m_DB->mComponentTypeToComponentMap) { if (it.second.find(objectId) != it.second.end()) { componentList.insert(componentList.end(), it.second.at(objectId).begin(), it.second.at(objectId).end()); } } } void ObjectManager::getGameObjects(const ComponentTypeId typeId, std::vector<GameObject*> &gameObjectList) const { if (m_DB->mComponentTypeToComponentMap.find(typeId) == m_DB->mComponentTypeToComponentMap.end()) return; for (const auto &it : m_DB->mComponentTypeToComponentMap.at(typeId)) { gameObjectList.push_back(m_DB->mObjectMap.at(it.first)); } } void ObjectManager::removeComponentByComponentTypeId(const CObjectId objectId, const ComponentTypeId typeId) { m_DB->mComponentTypeToComponentMap[typeId].erase(objectId); } void ObjectManager::removeComponentByComponentTypeName(const CObjectId objectId, const std::string& typeName) { Hash typeId(typeName); return removeComponentByComponentTypeId(objectId, typeId.get()); } void ObjectManager::removeComponentByObjectId(const CObjectId objectId) { if (m_DB->mObjectMap.find(objectId) == m_DB->mObjectMap.end()) return; for (auto &it : m_DB->mComponentTypeToComponentMap) { if (it.second.find(objectId) != it.second.end()) { for (const auto &c : it.second.at(objectId)) { CoreObject::Destory(c); } it.second.erase(objectId); } } } void ObjectManager::addGameObject(GameObject *gameObject) { if (nullptr != gameObject) { m_DB->mObjectMap[gameObject->getInstanceId()] = gameObject; } } void ObjectManager::removeGameObject(const CObjectId objectId) { removeComponentByObjectId(objectId); m_DB->mObjectMap.erase(objectId); } void ObjectManager::registerComponentType(const ComponentTypeId typeId, const CreationMethod creationMethod, const DestructionMethod destructionMethod, const std::string &typeName) { ComponentTypeInfo *newComponentTypeInfo =new ComponentTypeInfo(); newComponentTypeInfo->creationMethod = creationMethod; newComponentTypeInfo->destructionMethod = destructionMethod; newComponentTypeInfo->typeId = typeId; newComponentTypeInfo->typeName = typeName; m_DB->mComponentTypeInfoMap[typeId] = newComponentTypeInfo; } void ObjectManager::registerAllComponentTypes(void) { Component::registerComponentTypes(); Transform::registerComponentTypes(); MeshFilter::registerComponentTypes(); Camera::registerComponentTypes(); Renderer::registerComponentTypes(); } Component *ObjectManager::createComponent(const ComponentTypeId typeId) { auto it = m_DB->mComponentTypeInfoMap.find(typeId); if (it == m_DB->mComponentTypeInfoMap.end()) return nullptr; return static_cast<Component*>((*(it->second->creationMethod))(it->second->typeName)); } }
{ "content_hash": "1478ef3a4ff191fc379756675533f4d7", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 186, "avg_line_length": 46.45112781954887, "alnum_prop": 0.6691485917772741, "repo_name": "pgdnxu/Spore3D", "id": "1b62ed4af4f7c3b9b118aa167a71bf32f0140f46", "size": "7187", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spore3d/src/cObjectManager.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1245" }, { "name": "C++", "bytes": "602528" }, { "name": "GLSL", "bytes": "557" } ], "symlink_target": "" }
require 'test_helper' class RemoteBraintreeBlueTest < Test::Unit::TestCase def setup @gateway = BraintreeGateway.new(fixtures(:braintree_blue)) @braintree_backend = @gateway.instance_eval{@braintree_gateway} @amount = 100 @declined_amount = 2000_00 @credit_card = credit_card('5105105105105100') @declined_card = credit_card('4000300011112220') @options = { :order_id => '1', :billing_address => address(:country_name => "United States of America"), :description => 'Store Purchase' } end def test_credit_card_details_on_store assert response = @gateway.store(@credit_card) assert_success response assert_equal '5100', response.params["braintree_customer"]["credit_cards"].first["last_4"] assert_equal('510510******5100', response.params["braintree_customer"]["credit_cards"].first["masked_number"]) assert_equal('5100', response.params["braintree_customer"]["credit_cards"].first["last_4"]) assert_equal('MasterCard', response.params["braintree_customer"]["credit_cards"].first["card_type"]) assert_equal('510510', response.params["braintree_customer"]["credit_cards"].first["bin"]) assert_match %r{^\d+$}, response.params["customer_vault_id"] assert_equal response.params["customer_vault_id"], response.authorization end def test_successful_authorize assert response = @gateway.authorize(@amount, @credit_card, @options) assert_success response assert_equal '1000 Approved', response.message assert_equal 'authorized', response.params["braintree_transaction"]["status"] end def test_masked_card_number assert response = @gateway.authorize(@amount, @credit_card, @options) assert_equal('510510******5100', response.params["braintree_transaction"]["credit_card_details"]["masked_number"]) assert_equal('5100', response.params["braintree_transaction"]["credit_card_details"]["last_4"]) assert_equal('MasterCard', response.params["braintree_transaction"]["credit_card_details"]["card_type"]) assert_equal('510510', response.params["braintree_transaction"]["credit_card_details"]["bin"]) end def test_successful_authorize_with_order_id assert response = @gateway.authorize(@amount, @credit_card, :order_id => '123') assert_success response assert_equal '1000 Approved', response.message assert_equal '123', response.params["braintree_transaction"]["order_id"] end def test_successful_purchase_with_hold_in_escrow @options.merge({:merchant_account_id => fixtures(:braintree_blue)[:merchant_account_id], :hold_in_escrow => true}) assert response = @gateway.authorize(@amount, @credit_card, @options) assert_success response assert_equal '1000 Approved', response.message end def test_successful_purchase_using_vault_id assert response = @gateway.store(@credit_card) assert_success response assert_equal 'OK', response.message customer_vault_id = response.params["customer_vault_id"] assert_match(/\A\d+\z/, customer_vault_id) assert response = @gateway.purchase(@amount, customer_vault_id) assert_success response assert_equal '1000 Approved', response.message assert_equal 'submitted_for_settlement', response.params["braintree_transaction"]["status"] assert_equal customer_vault_id, response.params["braintree_transaction"]["customer_details"]["id"] end def test_successful_purchase_using_vault_id_as_integer assert response = @gateway.store(@credit_card) assert_success response assert_equal 'OK', response.message customer_vault_id = response.params["customer_vault_id"] assert_match %r{\A\d+\z}, customer_vault_id assert response = @gateway.purchase(@amount, customer_vault_id.to_i) assert_success response assert_equal '1000 Approved', response.message assert_equal 'submitted_for_settlement', response.params["braintree_transaction"]["status"] assert_equal customer_vault_id, response.params["braintree_transaction"]["customer_details"]["id"] end def test_successful_verify assert response = @gateway.verify(@credit_card, @options) assert_success response assert_equal "1000 Approved", response.message end def test_failed_verify assert response = @gateway.verify(@declined_card, @options) assert_failure response assert_match %r{number is not an accepted test number}, response.message end def test_successful_validate_on_store card = credit_card('4111111111111111', :verification_value => '101') assert response = @gateway.store(card, :verify_card => true) assert_success response assert_equal 'OK', response.message end def test_failed_validate_on_store card = credit_card('4000111111111115', :verification_value => '200') assert response = @gateway.store(card, :verify_card => true) assert_failure response assert_equal 'Processor declined: Do Not Honor (2000)', response.message end def test_successful_store_with_no_validate card = credit_card('4000111111111115', :verification_value => '200') assert response = @gateway.store(card, :verify_card => false) assert_success response assert_equal 'OK', response.message end def test_successful_store_with_valid_card assert response = @gateway.store(@credit_card) assert_success response assert_equal 'OK', response.message end def test_successful_store_with_valid_card_and_empty_payment_method_nonce assert response = @gateway.store(@credit_card, payment_method_nonce: "") assert_success response assert_equal 'OK', response.message end def test_successful_store_with_billing_address billing_address = { :address1 => "1 E Main St", :address2 => "Suite 403", :city => "Chicago", :state => "Illinois", :zip => "60622", :country_name => "United States of America" } credit_card = credit_card('5105105105105100') assert response = @gateway.store(credit_card, :billing_address => billing_address) assert_success response assert_equal 'OK', response.message vault_id = response.params['customer_vault_id'] purchase_response = @gateway.purchase(@amount, vault_id) response_billing_details = { "country_name"=>"United States of America", "region"=>"Illinois", "company"=>nil, "postal_code"=>"60622", "extended_address"=>"Suite 403", "street_address"=>"1 E Main St", "locality"=>"Chicago" } assert_equal purchase_response.params['braintree_transaction']['billing_details'], response_billing_details end def test_successful_store_with_credit_card_token credit_card = credit_card('5105105105105100') credit_card_token = generate_unique_id assert response = @gateway.store(credit_card, credit_card_token: credit_card_token) assert_success response assert_equal 'OK', response.message assert_equal credit_card_token, response.params["braintree_customer"]["credit_cards"][0]["token"] end def test_successful_store_with_new_customer_id credit_card = credit_card('5105105105105100') customer_id = generate_unique_id assert response = @gateway.store(credit_card, customer: customer_id) assert_success response assert_equal 'OK', response.message assert_equal customer_id, response.authorization assert_equal customer_id, response.params["braintree_customer"]["id"] end def test_successful_store_with_existing_customer_id credit_card = credit_card('5105105105105100') customer_id = generate_unique_id assert response = @gateway.store(credit_card, customer: customer_id) assert_success response assert_equal 1, @braintree_backend.customer.find(customer_id).credit_cards.size assert response = @gateway.store(credit_card, customer: customer_id) assert_success response assert_equal 2, @braintree_backend.customer.find(customer_id).credit_cards.size assert_equal customer_id, response.params["customer_vault_id"] assert_equal customer_id, response.authorization assert_not_nil response.params["credit_card_token"] end def test_successful_purchase assert response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert_equal '1000 Approved', response.message assert_equal 'submitted_for_settlement', response.params["braintree_transaction"]["status"] end def test_successful_purchase_with_solution_id ActiveMerchant::Billing::BraintreeBlueGateway.application_id = 'ABC123' assert response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert_equal '1000 Approved', response.message assert_equal 'submitted_for_settlement', response.params["braintree_transaction"]["status"] ensure ActiveMerchant::Billing::BraintreeBlueGateway.application_id = nil end def test_avs assert_avs("1 Elm", "60622", "M") assert_avs("1 Elm", "20000", "A") assert_avs("1 Elm", "20001", "B") assert_avs("1 Elm", "", "B") assert_avs("200 Elm", "60622", "Z") assert_avs("200 Elm", "20000", "C") assert_avs("200 Elm", "20001", "C") assert_avs("200 Elm", "", "C") assert_avs("201 Elm", "60622", "P") assert_avs("201 Elm", "20000", "N") assert_avs("201 Elm", "20001", "I") assert_avs("201 Elm", "", "I") assert_avs("", "60622", "P") assert_avs("", "20000", "C") assert_avs("", "20001", "I") assert_avs("", "", "I") assert_avs("1 Elm", "30000", "E") assert_avs("1 Elm", "30001", "S") end def test_cvv_match assert response = @gateway.purchase(@amount, credit_card('5105105105105100', :verification_value => '400')) assert_success response assert_equal({'code' => 'M', 'message' => ''}, response.cvv_result) end def test_cvv_no_match assert response = @gateway.purchase(@amount, credit_card('5105105105105100', :verification_value => '200')) assert_success response assert_equal({'code' => 'N', 'message' => ''}, response.cvv_result) end def test_successful_purchase_with_email assert response = @gateway.purchase(@amount, @credit_card, :email => "customer@example.com" ) assert_success response transaction = response.params["braintree_transaction"] assert_equal 'customer@example.com', transaction["customer_details"]["email"] end def test_purchase_with_store_using_random_customer_id assert response = @gateway.purchase( @amount, credit_card('5105105105105100'), @options.merge(:store => true) ) assert_success response assert_equal '1000 Approved', response.message assert_match(/\A\d+\z/, response.params["customer_vault_id"]) assert_equal '510510', response.params["braintree_transaction"]["vault_customer"]["credit_cards"][0]["bin"] assert_equal '510510', @braintree_backend.customer.find(response.params["customer_vault_id"]).credit_cards[0].bin end def test_purchase_with_store_using_specified_customer_id customer_id = rand(1_000_000_000).to_s assert response = @gateway.purchase( @amount, credit_card('5105105105105100'), @options.merge(:store => customer_id) ) assert_success response assert_equal '1000 Approved', response.message assert_equal customer_id, response.params["customer_vault_id"] assert_equal '510510', response.params["braintree_transaction"]["vault_customer"]["credit_cards"][0]["bin"] assert_equal '510510', @braintree_backend.customer.find(response.params["customer_vault_id"]).credit_cards[0].bin end def test_purchase_with_transaction_source assert response = @gateway.store(@credit_card) assert_success response customer_vault_id = response.params['customer_vault_id'] assert response = @gateway.purchase(@amount, customer_vault_id, @options.merge(:transaction_source => 'unscheduled')) assert_success response assert_equal '1000 Approved', response.message end def test_purchase_using_specified_payment_method_token assert response = @gateway.store( credit_card('4111111111111111', :first_name => 'Old First', :last_name => 'Old Last', :month => 9, :year => 2012 ), :email => "old@example.com" ) payment_method_token = response.params["braintree_customer"]["credit_cards"][0]["token"] assert response = @gateway.purchase( @amount, payment_method_token, @options.merge(payment_method_token: true) ) assert_success response assert_equal '1000 Approved', response.message assert_equal payment_method_token, response.params["braintree_transaction"]["credit_card_details"]["token"] end def test_successful_purchase_with_addresses billing_address = { :address1 => '1 E Main St', :address2 => 'Suite 101', :company => 'Widgets Co', :city => 'Chicago', :state => 'IL', :zip => '60622', :country_name => 'United States of America' } shipping_address = { :address1 => '1 W Main St', :address2 => 'Suite 102', :company => 'Widgets Company', :city => 'Bartlett', :state => 'Illinois', :zip => '60103', :country_name => 'Mexico' } assert response = @gateway.purchase(@amount, @credit_card, :billing_address => billing_address, :shipping_address => shipping_address ) assert_success response transaction = response.params["braintree_transaction"] assert_equal '1 E Main St', transaction["billing_details"]["street_address"] assert_equal 'Suite 101', transaction["billing_details"]["extended_address"] assert_equal 'Widgets Co', transaction["billing_details"]["company"] assert_equal 'Chicago', transaction["billing_details"]["locality"] assert_equal 'IL', transaction["billing_details"]["region"] assert_equal '60622', transaction["billing_details"]["postal_code"] assert_equal 'United States of America', transaction["billing_details"]["country_name"] assert_equal '1 W Main St', transaction["shipping_details"]["street_address"] assert_equal 'Suite 102', transaction["shipping_details"]["extended_address"] assert_equal 'Widgets Company', transaction["shipping_details"]["company"] assert_equal 'Bartlett', transaction["shipping_details"]["locality"] assert_equal 'Illinois', transaction["shipping_details"]["region"] assert_equal '60103', transaction["shipping_details"]["postal_code"] assert_equal 'Mexico', transaction["shipping_details"]["country_name"] end def test_successful_purchase_with_three_d_secure_pass_thru three_d_secure_params = { eci: "05", cavv: "cavv", xid: "xid" } assert response = @gateway.purchase(@amount, @credit_card, three_d_secure: three_d_secure_params ) assert_success response end def test_unsuccessful_purchase_declined assert response = @gateway.purchase(@declined_amount, @credit_card, @options) assert_failure response assert response.authorization.present? assert_equal '2000 Do Not Honor', response.message end def test_unsuccessful_purchase_validation_error assert response = @gateway.purchase(@amount, credit_card('51051051051051000')) assert_failure response assert_match %r{Credit card number is invalid\. \(81715\)}, response.message assert_equal({"processor_response_code"=>"91577"}, response.params["braintree_transaction"]) end def test_authorize_and_capture assert auth = @gateway.authorize(@amount, @credit_card, @options) assert_success auth assert_equal '1000 Approved', auth.message assert auth.authorization assert capture = @gateway.capture(@amount, auth.authorization) assert_success capture end def test_authorize_and_capture_with_apple_pay_card credit_card = network_tokenization_credit_card('4111111111111111', :brand => 'visa', :eci => "05", :payment_cryptogram => "EHuWW9PiBkWvqE5juRwDzAUFBAk=" ) assert auth = @gateway.authorize(@amount, credit_card, @options) assert_success auth assert_equal '1000 Approved', auth.message assert auth.authorization assert capture = @gateway.capture(@amount, auth.authorization) assert_success capture end def test_authorize_and_void assert auth = @gateway.authorize(@amount, @credit_card, @options) assert_success auth assert_equal '1000 Approved', auth.message assert auth.authorization assert void = @gateway.void(auth.authorization) assert_success void assert_equal 'voided', void.params["braintree_transaction"]["status"] end def test_purchase_and_void assert purchase = @gateway.purchase(@amount, @credit_card, @options) assert_success purchase assert void = @gateway.void(purchase.authorization) assert_success void assert_equal 'voided', void.params["braintree_transaction"]["status"] end def test_capture_and_void assert auth = @gateway.authorize(@amount, @credit_card, @options) assert_success auth assert capture = @gateway.capture(@amount, auth.authorization) assert_success capture assert void = @gateway.void(capture.authorization) assert_success void assert_equal 'voided', void.params["braintree_transaction"]["status"] end def test_failed_void assert auth = @gateway.authorize(@amount, @credit_card, @options) assert_success auth assert_equal '1000 Approved', auth.message assert auth.authorization assert void = @gateway.void(auth.authorization) assert_success void assert_equal 'voided', void.params["braintree_transaction"]["status"] assert failed_void = @gateway.void(auth.authorization) assert_failure failed_void assert_equal 'Transaction can only be voided if status is authorized, submitted_for_settlement, or - for PayPal - settlement_pending. (91504)', failed_void.message assert_equal({"processor_response_code"=>"91504"}, failed_void.params["braintree_transaction"]) end def test_failed_capture_with_invalid_transaction_id assert response = @gateway.capture(@amount, 'invalidtransactionid') assert_failure response assert_equal 'Braintree::NotFoundError', response.message end def test_invalid_login gateway = BraintreeBlueGateway.new(:merchant_id => "invalid", :public_key => "invalid", :private_key => "invalid") assert response = gateway.purchase(@amount, @credit_card, @options) assert_failure response assert_equal 'Braintree::AuthenticationError', response.message end def test_successful_add_to_vault_with_store_method assert response = @gateway.store(@credit_card) assert_success response assert_equal 'OK', response.message assert_match(/\A\d+\z/, response.params["customer_vault_id"]) end def test_failed_add_to_vault assert response = @gateway.store(credit_card('5105105105105101')) assert_failure response assert_equal 'Credit card number is invalid. (81715)', response.message assert_equal nil, response.params["braintree_customer"] assert_equal nil, response.params["customer_vault_id"] end def test_unstore_customer assert response = @gateway.store(@credit_card) assert_success response assert_equal 'OK', response.message assert customer_vault_id = response.params["customer_vault_id"] assert delete_response = @gateway.unstore(customer_vault_id) assert_success delete_response end def test_unstore_credit_card assert response = @gateway.store(@credit_card) assert_success response assert_equal 'OK', response.message assert credit_card_token = response.params["credit_card_token"] assert delete_response = @gateway.unstore(nil, credit_card_token: credit_card_token) assert_success delete_response end def test_unstore_with_delete_method assert response = @gateway.store(@credit_card) assert_success response assert_equal 'OK', response.message assert customer_vault_id = response.params["customer_vault_id"] assert delete_response = @gateway.delete(customer_vault_id) assert_success delete_response end def test_successful_update assert response = @gateway.store( credit_card('4111111111111111', :first_name => 'Old First', :last_name => 'Old Last', :month => 9, :year => 2012 ), :email => "old@example.com" ) assert_success response assert_equal 'OK', response.message customer_vault_id = response.params["customer_vault_id"] assert_match(/\A\d+\z/, customer_vault_id) assert_equal "old@example.com", response.params["braintree_customer"]["email"] assert_equal "Old First", response.params["braintree_customer"]["first_name"] assert_equal "Old Last", response.params["braintree_customer"]["last_name"] assert_equal "411111", response.params["braintree_customer"]["credit_cards"][0]["bin"] assert_equal "09/2012", response.params["braintree_customer"]["credit_cards"][0]["expiration_date"] assert_not_nil response.params["braintree_customer"]["credit_cards"][0]["token"] assert_equal customer_vault_id, response.params["braintree_customer"]["id"] assert response = @gateway.update( customer_vault_id, credit_card('5105105105105100', :first_name => 'New First', :last_name => 'New Last', :month => 10, :year => 2014 ), :email => "new@example.com" ) assert_success response assert_equal "new@example.com", response.params["braintree_customer"]["email"] assert_equal "New First", response.params["braintree_customer"]["first_name"] assert_equal "New Last", response.params["braintree_customer"]["last_name"] assert_equal "510510", response.params["braintree_customer"]["credit_cards"][0]["bin"] assert_equal "10/2014", response.params["braintree_customer"]["credit_cards"][0]["expiration_date"] assert_not_nil response.params["braintree_customer"]["credit_cards"][0]["token"] assert_equal customer_vault_id, response.params["braintree_customer"]["id"] end def test_successful_credit_card_partial_update assert response = @gateway.store( credit_card('4111111111111111', :first_name => 'Old First', :last_name => 'Old Last', :month => 9, :year => 2012 ), :email => "old@example.com" ) assert_success response assert_equal 'OK', response.message customer_vault_id = response.params["customer_vault_id"] assert_match(/\A\d+\z/, customer_vault_id) assert_equal "old@example.com", response.params["braintree_customer"]["email"] assert_equal "Old First", response.params["braintree_customer"]["first_name"] assert_equal "Old Last", response.params["braintree_customer"]["last_name"] assert_equal "411111", response.params["braintree_customer"]["credit_cards"][0]["bin"] assert_equal "09/2012", response.params["braintree_customer"]["credit_cards"][0]["expiration_date"] assert_not_nil response.params["braintree_customer"]["credit_cards"][0]["token"] assert_equal customer_vault_id, response.params["braintree_customer"]["id"] assert response = @gateway.update(customer_vault_id, credit_card('1111', first_name: "New First", last_name: "New Last"), email: "new@example.com") assert_success response assert_equal "new@example.com", response.params["braintree_customer"]["email"] assert_equal "New First", response.params["braintree_customer"]["first_name"] assert_equal "New Last", response.params["braintree_customer"]["last_name"] assert_equal customer_vault_id, response.params["braintree_customer"]["id"] end def test_successful_partial_paypal_update assert response = @gateway.store(paypal_account, email: "jd@example.com") assert_success response assert_equal 'OK', response.message customer_vault_id = response.params["customer_vault_id"] assert_match(/\A\d+\z/, customer_vault_id) assert_equal "jd@example.com", response.params["braintree_customer"]["email"] assert_equal "John", response.params["braintree_customer"]["first_name"] assert_equal "Doe", response.params["braintree_customer"]["last_name"] assert_equal customer_vault_id, response.params["braintree_customer"]["id"] assert response = @gateway.update(customer_vault_id, paypal_account("New First", "New Last"), email: "new@example.com") assert_success response assert_equal "new@example.com", response.params["braintree_customer"]["email"] assert_equal "New First", response.params["braintree_customer"]["first_name"] assert_equal "New Last", response.params["braintree_customer"]["last_name"] assert_equal customer_vault_id, response.params["braintree_customer"]["id"] end def test_failed_customer_update assert response = @gateway.store(credit_card('4111111111111111'), :email => "email@example.com") assert_success response assert_equal 'OK', response.message assert customer_vault_id = response.params["customer_vault_id"] assert response = @gateway.update( customer_vault_id, credit_card('51051051051051001') ) assert_failure response assert_equal 'Credit card number is invalid. (81715)', response.message assert_equal nil, response.params["braintree_customer"] assert_equal nil, response.params["customer_vault_id"] end def test_failed_customer_update_invalid_vault_id assert response = @gateway.update('invalid-customer-id', credit_card('5105105105105100')) assert_failure response assert_equal 'Braintree::NotFoundError', response.message end def test_failed_credit_card_update assert response = @gateway.store(credit_card('4111111111111111')) assert_success response assert_equal 'OK', response.message assert customer_vault_id = response.params["customer_vault_id"] assert response = @gateway.update( customer_vault_id, credit_card('5105105105105101') ) assert_failure response assert_equal 'Credit card number is invalid. (81715)', response.message end def test_failed_credit_card_update_on_verify assert response = @gateway.store(credit_card('4111111111111111')) assert_success response assert_equal 'OK', response.message assert customer_vault_id = response.params["customer_vault_id"] assert response = @gateway.update( customer_vault_id, credit_card('4000111111111115'), {:verify_card => true} ) assert_failure response assert_equal 'Processor declined: Do Not Honor (2000)', response.message end def test_customer_does_not_have_credit_card_failed_update customer_without_credit_card = @braintree_backend.customer.create assert response = @gateway.update(customer_without_credit_card.customer.id, credit_card('5105105105105100')) assert_failure response assert_equal 'Braintree::NotFoundError', response.message end def test_successful_credit assert response = @gateway.credit(@amount, @credit_card, @options) assert_success response, "You must get credits enabled in your Sandbox account for this to pass." assert_equal '1002 Processed', response.message assert_equal 'submitted_for_settlement', response.params["braintree_transaction"]["status"] end def test_failed_credit assert response = @gateway.credit(@amount, credit_card('5105105105105101'), @options) assert_failure response assert_equal 'Credit card number is invalid. (81715)', response.message, "You must get credits enabled in your Sandbox account for this to pass" end def test_successful_credit_with_merchant_account_id assert response = @gateway.credit(@amount, @credit_card, :merchant_account_id => fixtures(:braintree_blue)[:merchant_account_id]) assert_success response, "You must specify a valid :merchant_account_id key in your fixtures.yml AND get credits enabled in your Sandbox account for this to pass." assert_equal '1002 Processed', response.message assert_equal 'submitted_for_settlement', response.params["braintree_transaction"]["status"] end def test_successful_authorize_with_merchant_account_id assert response = @gateway.authorize(@amount, @credit_card, :merchant_account_id => fixtures(:braintree_blue)[:merchant_account_id]) assert_success response, "You must specify a valid :merchant_account_id key in your fixtures.yml for this to pass." assert_equal '1000 Approved', response.message assert_equal fixtures(:braintree_blue)[:merchant_account_id], response.params["braintree_transaction"]["merchant_account_id"] end def test_authorize_with_descriptor assert auth = @gateway.authorize(@amount, @credit_card, descriptor_name: "company*theproduct", descriptor_phone: "1331131131", descriptor_url: "company.com") assert_success auth end def test_successful_validate_on_store_with_verification_merchant_account card = credit_card('4111111111111111', :verification_value => '101') assert response = @gateway.store(card, :verify_card => true, :verification_merchant_account_id => fixtures(:braintree_blue)[:merchant_account_id]) assert_success response, "You must specify a valid :merchant_account_id key in your fixtures.yml for this to pass." assert_equal 'OK', response.message end def test_transcript_scrubbing transcript = capture_transcript(@gateway) do @gateway.purchase(@amount, @credit_card, @options) end clean_transcript = @gateway.scrub(transcript) assert_scrubbed(@credit_card.number, clean_transcript) assert_scrubbed(@credit_card.verification_value.to_s, clean_transcript) end def test_verify_credentials assert @gateway.verify_credentials gateway = BraintreeGateway.new(merchant_id: "UNKNOWN", public_key: "UNKONWN", private_key: "UNKONWN") assert !gateway.verify_credentials end def test_check_payment_method_nonce_with_valid_nonce assert response = @gateway.check_payment_method_nonce("fake-three-d-secure-visa-full-authentication-nonce") assert_success response assert_equal 'OK', response.message end def test_check_payment_method_nonce_with_invalid_nonce assert response = @gateway.check_payment_method_nonce("invalid-nonce") assert_failure response assert_equal 'Braintree::NotFoundError', response.message end private def assert_avs(address1, zip, expected_avs_code) response = @gateway.purchase(@amount, @credit_card, billing_address: {address1: address1, zip: zip}) assert_success response assert_equal expected_avs_code, response.avs_result['code'] end end
{ "content_hash": "b61232fb7ee53463cb303635e3b25f85", "timestamp": "", "source": "github", "line_count": 715, "max_line_length": 167, "avg_line_length": 42.723076923076924, "alnum_prop": 0.702851343830818, "repo_name": "chargify/active_merchant", "id": "e78bce9c7b0ef3e1032603ac446e66d3c3533fa1", "size": "30547", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/remote/gateways/remote_braintree_blue_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "6561802" } ], "symlink_target": "" }
/** * Created by aleckim on 2016. 2. 19.. * controllerTown에서 short의 time table을 0~21 에서 3~24시로 변경한 클래스임. */ 'use strict'; var async = require('async'); var request = require('request'); var ControllerTown = require('../controllers/controllerTown'); var kmaTimeLib = require('../lib/kmaTimeLib'); var UnitConverter = require('../lib/unitConverter'); var AqiConverter = require('../lib/aqi.converter'); var KecoController = require('../controllers/kecoController'); var AirkoreaHourlyForecastCtrl = require('../controllers/airkorea.hourly.forecast.controller'); var KaqHourlyForecastCtrl = require('../controllers/kaq.hourly.forecast.controller'); var KmaSpecialWeatherController = require('../controllers/kma.specialweather.controller'); var config = require('../config/config'); /** * * @constructor */ function ControllerTown24h() { var self = this; ControllerTown.call(this); this.checkQueryValidation = function(req, res, next) { var meta = {}; meta.sID = req.sessionID; /** * * temperatureUnit(C,F), windSpeedUnit(mph,km/h,m/s,bft,kr), pressureUnit(mmHg,inHg,hPa,mb), * distanceUnit(km,mi), precipitationUnit(mm,in), airUnit(airkorea,airkorea_who,airnow,aqicn), * airForecastSource(kaq, airkorea) */ if(!req.hasOwnProperty('query')) { req.query = {}; } try { if (req.baseUrl) { req.version = req.baseUrl.split('/')[1]; if (req.version.indexOf('v') !== 0) { log.warn("Fail to find version base url=",req.baseUrl); delete req.version; } } /** * #1978 * client에서 airUnit이 없으면 (null)로 전달됨 */ UnitConverter.getUnitList().forEach(function (value) { if (!req.query.hasOwnProperty(value) || req.query[value] == '(null)') { req.query[value] = UnitConverter.getDefaultValue(value); } }); if (!req.query.hasOwnProperty('airForecastSource') || req.query.airForecastSource == '(null)') { req.query.airForecastSource = 'airkorea'; } log.info({sId:req.sessionID, reqQuery: req.query}); } catch(err) { err.message += ' ' + JSON.stringify(meta); log.error(err); } next(); return this; }; /** * adjust tmn, tmx and reorganize position of tmn and tmx * @param req * @param res * @param next */ this.adjustShort = function(req, res, next) { var regionName = req.params.region; var cityName = req.params.city; var townName = req.params.town; var meta = {}; meta.sID = req.sessionID; meta.method = 'adjustShort'; meta.region = regionName; meta.city = cityName; meta.town = townName; log.info(meta); if (!req.hasOwnProperty('short')) { log.error("Short forecast data hasn't attached on req", meta); next(); return this; } //t3h, tmx, tmn로부터 일별 taMax, taMin을 만들고 tmx, tmn을 초기화 한다. var daySummaryList = []; req.short.forEach(function (short, index) { //과거 short가 없는 경우 -1로 client로 넘어가는 것을 방지함. 이것은 short에 대한 merge가 완료된 후에 해야 함. if (short.pop == undefined || short.pop == -1) { short.pop = 0; } var daySummary = self._createOrGetDaySummaryList(daySummaryList, short.date); daySummary.taMax = daySummary.taMax === undefined ? -50:daySummary.taMax; daySummary.taMin = daySummary.taMin === undefined ? -50:daySummary.taMin; if (daySummary.taMax < short.t3h) { daySummary.taMax = short.t3h; } if (daySummary.taMax < short.tmx) { daySummary.taMax = short.tmx; log.verbose(index+" tmx clear"); //clear tmx } short.tmx = -50; if (daySummary.taMin === -50 && short.t3h !== -50) { daySummary.taMin = short.t3h; } else if (daySummary.taMin > short.t3h && short.t3h !== -50) { daySummary.taMin = short.t3h; } if (daySummary.taMin === -50 && short.tmn !== -50) { daySummary.taMin = short.tmn; } else if (daySummary.taMin > short.tmn && short.tmn !== -50) { daySummary.taMin = short.tmn; short.tmn = -50; log.verbose(index+" tmn clear"); } short.tmn = -50; }); //r06, s06을 3시간단위로 나눔. //앞시간 뒤시간 모두 pty가 1이상이면 반반으로 나누고, 아니라면 몰아줌. //todo: merge 순서 변경 필요. 1) short 2) short rss 3) r06, s06분리 4) past if (req.short[0].s06 < 0) { req.short[0].s06 = 0; } if (req.short[0].r06 < 0) { req.short[0].r06 = 0; } var i; for (i=2; i<req.short.length; i+=2) { var short = req.short[i]; if (short.r06 > 0) { if (req.short[i-1].pty > 0 && req.short[i].pty > 0) { req.short[i-1].r06 = +(short.r06/2).toFixed(1); req.short[i].r06 = +(short.r06/2).toFixed(1); } else if (req.short[i-1].pty > 0 ) { req.short[i-1].r06 = short.r06; req.short[i].r06 = 0; } else if (req.short[i].pty > 0 ) { req.short[i-1].r06 = 0; req.short[i].r06 = short.r06; } else { if (req.short[i-1].rn1 != undefined || req.short[i].rn1 != undefined) { //과거의 경우 예보상으로 온다고 했지만, 오지 않은 경우에 발생할 수 있음. } else { //17.01.12 05시 단기 예보에서, pty가 0이지만, R06,S06은 1이었음. 충청남도 아산시 온양4동 mx 60, my 110 //kma에서는 이경우 r06,s06을 표시하지 않고, 눈,비 안옴으로 표기 log.warn("It has r06 but pty is zero short date="+req.short[i].date+" time="+req.short[i].time); } req.short[i-1].r06 = 0; req.short[i].r06 = 0; } } else { req.short[i-1].r06 = 0; req.short[i].r06 = 0; } if (short.s06 > 0) { if (req.short[i-1].pty > 0 && req.short[i].pty > 0) { req.short[i-1].s06 = +(short.s06/2).toFixed(1); req.short[i].s06 = +(short.s06/2).toFixed(1); } else if (req.short[i-1].pty > 0 ) { req.short[i-1].s06 = short.s06; req.short[i].s06 = 0; } else if (req.short[i].pty > 0 ) { req.short[i-1].s06 = 0; req.short[i].s06 = short.s06; } else { if (req.short[i-1].rn1 != undefined || req.short[i].rn1 != undefined) { //과거의 경우 예보상으로 온다고 했지만, 오지 않은 경우에 발생할 수 있음. } else { //17.01.12 05시 단기 예보에서, pty가 0이지만, R06,S06은 1이었음. 충청남도 아산시 온양4동 mx 60, my 110 //kma에서는 이경우 r06,s06을 표시하지 않고, 눈,비 안옴으로 표기 log.warn("It has s06 but pty is zero short date="+req.short[i].date+" time="+req.short[i].time); } req.short[i-1].s06 = 0; req.short[i].s06 = 0; } } else { req.short[i-1].s06 = 0; req.short[i].s06 = 0; } } req.short.forEach(function (short) { if (short.hasOwnProperty('shortestRn1')) { if (short.hasOwnProperty('pty')) { if (short.pty === 3) { short.s06 = short.shortestRn1; } else if (short.pty === 2 || short.pty === 1) { short.r06 = short.shortestRn1; } } } }); //client 하위 버전 지원 못함. req.short.forEach(function (short, index) { var daySum = self._createOrGetDaySummaryList(daySummaryList, short.date); daySum.taMax = daySum.taMax === undefined ? -50:daySum.taMax; daySum.taMin = daySum.taMin === undefined ? -50:daySum.taMin; if (daySum.taMax === -50 || daySum.taMin === -50) { log.warn("short date:"+short.date+" fail to get daySummary"); return; } var tmxDiff = Math.abs(daySum.taMax - short.t3h); var tmnDiff = Math.abs(daySum.taMin - short.t3h); if (!daySum.hasOwnProperty("tmxDiff")) { daySum.tmxDiff = tmxDiff; short.tmx = daySum.taMax; daySum.tmxIndex = index; } else { if (daySum.tmxDiff === tmxDiff) { if(short.time === "1500") { req.short[daySum.tmxIndex].tmx = -50; daySum.tmxDiff = tmxDiff; short.tmx = daySum.taMax; daySum.tmxIndex = index; log.verbose("put index:"+index+" tmx:"+short.tmx); } else if (req.short[daySum.tmxIndex].time === "1500") { //skip } else { //날짜와 무관하게 비교값들의 앞과 뒤 값 중에 큰쪽을 최대온도로 표기 var prvTmx; var nextTmx; if (daySum.tmnIndex > 0 && req.short[daySum.tmnIndex-1].t3h > req.short[daySum.tmnIndex].t3h) { prvTmx = req.short[daySum.tmnIndex-1].t3h; } else { prvTmx = req.short[daySum.tmnIndex].t3h; } if (index < req.short.length-1 && req.short[index+1].t3h > short.t3h) { nextTmx = req.short[index+1].t3h; } else { nextTmx = short.t3h; } if (prvTmx > nextTmx) { //skip } else { //nearest from 1500 //late time req.short[daySum.tmxIndex].tmx = -50; daySum.tmxDiff = tmxDiff; short.tmx = daySum.taMax; daySum.tmxIndex = index; log.verbose("put index:"+index+" tmx:"+short.tmx); } } } else if (daySum.tmxDiff > tmxDiff) { req.short[daySum.tmxIndex].tmx = -50; daySum.tmxDiff = tmxDiff; short.tmx = daySum.taMax; daySum.tmxIndex = index; log.verbose("put index:"+index+" tmx:"+short.tmx); } } if (!daySum.hasOwnProperty("tmnDiff")) { daySum.tmnDiff = tmnDiff; short.tmn = daySum.taMin; daySum.tmnIndex = index; } else { if (daySum.tmnDiff === tmnDiff) { if(short.time === "0600") { req.short[daySum.tmnIndex].tmn = -50; daySum.tmnDiff = tmnDiff; short.tmn = daySum.taMin; daySum.tmnIndex = index; log.verbose("put index:"+index+" tmn:"+short.tmn); } else if (req.short[daySum.tmnIndex].time === "0600") { //skip } else { //날짜와 무관하게 비교값들의 앞과 뒤 값 중에 작은 쪽을 최저온도로 표기 var prvTmn; var nextTmn; if (daySum.tmnIndex > 0 && req.short[daySum.tmnIndex-1].t3h < req.short[daySum.tmnIndex].t3h) { prvTmn = req.short[daySum.tmnIndex-1].t3h; } else { prvTmn = req.short[daySum.tmnIndex].t3h; } if (index < req.short.length-1 && req.short[index+1].t3h < short.t3h) { nextTmn = req.short[index+1].t3h; } else { nextTmn = short.t3h; } if (prvTmn > nextTmn) { req.short[daySum.tmnIndex].tmn = -50; daySum.tmnDiff = tmnDiff; short.tmn = daySum.taMin; daySum.tmnIndex = index; log.verbose("put index:"+index+" tmn:"+short.tmn); } else { //nearest from 0600 //early time } } } else if (daySum.tmnDiff > tmnDiff) { req.short[daySum.tmnIndex].tmn = -50; daySum.tmnDiff = tmnDiff; short.tmn = daySum.taMin; daySum.tmnIndex = index; log.verbose("put index:"+index+" tmn:"+short.tmn); } } }); //앞의 invalid한 날씨정보를 제거 i = req.short.length - 1; for(;i>=0;i--) { if(req.short[i].t3h !== -50) { break; } } req.short.splice(i+1, (req.short.length-(i+1))); next(); return this; }; this._makeDailyPmStr = function (dustFcst) { var pmStr; var pmGrade; if (dustFcst == undefined) { return; } if (dustFcst.PM10Grade && dustFcst.PM25Grade) { pmStr = dustFcst.PM10Grade>=dustFcst.PM25Grade?dustFcst.PM10Str:dustFcst.PM25Str; pmGrade = dustFcst.PM10Grade>=dustFcst.PM25Grade?dustFcst.PM10Grade:dustFcst.PM25Grade; } else if (dustFcst.PM10Grade) { pmStr = dustFcst.PM10Str; pmGrade = dustFcst.PM10Grade; } else if (dustFcst.PM25Grade) { pmStr = dustFcst.PM25Str; pmGrade = dustFcst.PM25Grade; } return {"pmGrade": pmGrade, "pmStr": pmStr}; }; this.makeDailySummary = function (req, res, next) { var regionName = req.params.region; var cityName = req.params.city; var townName = req.params.town; var meta = {}; meta.method = "makeDailySummary"; meta.region = regionName; meta.city = cityName; meta.town = townName; log.info('>sID=',req.sessionID, meta); var todayDate = req.current.date; var yD = kmaTimeLib.convertStringToDate(todayDate); yD.setDate(yD.getDate()-1); var yesterdayDate = kmaTimeLib.convertDateToYYYYMMDD(yD); var tD = kmaTimeLib.convertStringToDate(todayDate); tD.setDate(tD.getDate()+1); var tomorrowDate = kmaTimeLib.convertDateToYYYYMMDD(tD); var time = parseInt(req.current.time.substr(0, 2)); req.current.skyIcon = self._parseSkyState(req.current.sky, req.current.pty, req.current.lgt, time < 7 || time > 18); var current = req.current; var today; var yesterday; var tomorrow; var dailyDataLen = req.midData.dailyData.length; var pmObject; for (var i=0; i<dailyDataLen; i++) { var dailyData = req.midData.dailyData[i]; if (dailyData.date === yesterdayDate) { yesterday = req.midData.dailyData[i]; } else if (dailyData.date === todayDate) { today = req.midData.dailyData[i]; today.skyIcon = self._parseSkyState(today.sky, today.pty, 0, false); today.skyIconAm = self._parseSkyState(today.skyAm, today.ptyAm, 0, false); today.skyIconPm = self._parseSkyState(today.skyPm, today.ptyPm, 0, false); pmObject = self._makeDailyPmStr(today.dustForecast); if (pmObject) { today.pmStr = pmObject.pmStr; today.pmGrade = pmObject.pmGrade; } } else if (dailyData.date === tomorrowDate) { tomorrow = req.midData.dailyData[i]; tomorrow.skyIcon = self._parseSkyState(tomorrow.sky, tomorrow.pty, 0, false); tomorrow.skyIconAm = self._parseSkyState(tomorrow.skyAm, tomorrow.ptyAm, 0, false); tomorrow.skyIconPm = self._parseSkyState(tomorrow.skyPm, tomorrow.ptyPm, 0, false); pmObject = self._makeDailyPmStr(tomorrow.dustForecast); if (pmObject) { tomorrow.pmStr = pmObject.pmStr; tomorrow.pmGrade = pmObject.pmGrade; } } } //update pop if (req.short) { today.pop = 0; var len = req.short.length; for (i=0; i<len; i++) { var w3h = req.short[i]; if (w3h.date === today.date && w3h.time > req.current.time) { if (w3h.pop > today.pop) { today.pop = w3h.pop; } } } } var dailyArray = []; var dailySummary = ""; var location = ""; if (townName && townName != "") { location += townName+" "; } else if (cityName && cityName != "") { location += cityName+" "; } else if (regionName && regionName != "") { location += regionName+" "; } var theDay; if (time < 18) { theDay = today; dailySummary += "오늘: "; } else { theDay = tomorrow; dailySummary += "내일: "; } if (theDay.skyIconAm && theDay.skyIconPm) { dailyArray.push(self._getWeatherEmoji(theDay.skyIconAm)+self._getEmoji("RightwardsArrow")+self._getWeatherEmoji(theDay.skyIconPm)); } else if (theDay.skyIcon) { dailyArray.push(self._getWeatherEmoji(theDay.skyIcon)); } if (theDay.taMin != undefined && theDay.taMax != undefined) { dailyArray.push(theDay.taMin+"˚/"+theDay.taMax+"˚"); } if (theDay.pty && theDay.pty > 0) { if (theDay.pop && current.pty <= 0) { dailyArray.push("강수확률"+" "+theDay.pop+"%"); } } if (theDay.pmGrade && theDay.pmGrade > 1) { if (theDay.pmStr) { dailyArray.push("미세먼지" + " " + theDay.pmStr); } } if (theDay.ultrvGrade && theDay.ultrvGrade >= 2) { dailyArray.push("자외선"+" "+theDay.ultrvStr); } if (theDay.dustForecast && theDay.dustForecast.O3Grade && theDay.dustForecast.O3Grade >= 2) { dailyArray.push("오존"+" "+theDay.dustForecast.O3Str); } //불쾌지수 dailySummary += dailyArray.toString(); var hourlyArray = []; var hourlySummary = ""; hourlySummary += time+"시: "; if (current.skyIcon) { var weather = self._getWeatherEmoji(current.skyIcon); //if (current.weather) { // weather += " "+current.weather; //} hourlyArray.push(weather); } if (current.t1h) { var str = current.t1h+"˚"; //if (current.yesterday && current.yesterday.t1h !== undefined) { // str += " "; // var diffTemp = Math.round(current.t1h - current.yesterday.t1h); // // str += "어제"; // if (diffTemp == 0) { // str += "와 동일"; // } // else { // str += "보다 " + Math.abs(diffTemp); // if (diffTemp < 0) { // str += "˚낮음"; // } // else if (diffTemp > 0) { // str += "˚높음"; // } // } //} hourlyArray.push(str); } if (current.arpltn && current.arpltn.khaiGrade) { hourlyArray.push("대기"+" "+ current.arpltn.khaiStr); } if (current.pty && current.pty > 0 && current.rn1 != undefined) { hourlyArray.push(current.ptyStr+" "+ current.rn1Str); } hourlySummary += hourlyArray.toString(); //불쾌지수 var date = current.stnDateTime?current.stnDateTime:req.currentPubDate; req.dailySummary = {title: location+hourlySummary, text: dailySummary, date: date, icon: current.skyIcon, current: current, yesterday: yesterday, today: today, tomorrow: tomorrow}; return next(); }; /** * * @param dailyList * @param date YYYYMMDD * @param time HHMM * @returns {boolean} * @private */ function _isNight(dailyList, date, time) { var dayInfo = dailyList.find(function (data) { return data.date === date; }); var sunrise = 700; var sunset = 1800; if (dayInfo == undefined) { log.error({func:"isnight", msg:"Fail to find date="+date}); } else { if (dayInfo.hasOwnProperty('sunrise')) { sunrise = kmaTimeLib.convertYYYYoMMoDDoHHoMMtoHHMM(dayInfo.sunrise); } if (dayInfo.hasOwnProperty('sunset')) { sunset = kmaTimeLib.convertYYYYoMMoDDoHHoMMtoHHMM(dayInfo.sunset); } } var isNight = false; if (sunrise <= time && time <= sunset) { isNight = false; } else { isNight = true; } //log.verbose({date:date, time:time, sunrise:sunrise, sunset:sunset, night:isNight}); return isNight; } this.insertSkyIcon = function (req, res, next) { var isNight = false; try { if(req.short){ req.short.forEach(function (data) { isNight = _isNight(req.midData.dailyData, data.date, data.time); data.night = isNight; data.skyIcon = self._parseSkyState(data.sky, data.pty, data.lgt, isNight); }); } if(req.shortest){ req.shortest.forEach(function (data) { isNight = _isNight(req.midData.dailyData, data.date, data.time); data.night = isNight; data.skyIcon = self._parseSkyState(data.sky, data.pty, data.lgt, isNight); }); } if(req.current){ var data = req.current; var time; if (data.liveTime) { time = data.liveTime; } else { time = data.time; } isNight = _isNight(req.midData.dailyData, data.date, time); data.night = isNight; data.skyIcon = self._parseSkyState(data.sky, data.pty, data.lgt, isNight); } if(req.midData){ req.midData.dailyData.forEach(function (data) { if (data.sky) { data.skyIcon = self._parseSkyState(data.sky, data.pty, data.lgt, false); } if (data.skyAm) { data.skyAmIcon = self._parseSkyState(data.skyAm, data.ptyAm, data.lgtAm, false); } if (data.skyPm) { data.skyPmIcon = self._parseSkyState(data.skyPm, data.ptyPm, data.lgtPm, false); } }); } } catch(err) { return next(err); } next(); return this; }; this.insertSkyIconLowCase = function (req, res, next) { var isNight = false; try { if(req.short){ req.short.forEach(function (data) { isNight = _isNight(req.midData.dailyData, data.date, data.time); data.night = isNight; data.skyIcon = self._parseSkyStateLowCase(data.sky, data.pty, data.lgt, isNight); }); } if(req.shortest){ req.shortest.forEach(function (data) { isNight = _isNight(req.midData.dailyData, data.date, data.time); data.night = isNight; data.skyIcon = self._parseSkyStateLowCase(data.sky, data.pty, data.lgt, isNight); }); } if(req.current){ var data = req.current; var time; if (data.liveTime) { time = data.liveTime; } else { time = data.time; } isNight = _isNight(req.midData.dailyData, data.date, time); data.night = isNight; data.skyIcon = self._parseSkyStateLowCase(data.sky, data.pty, data.lgt, isNight); } if(req.midData){ req.midData.dailyData.forEach(function (data) { if (data.sky) { data.skyIcon = self._parseSkyStateLowCase(data.sky, data.pty, data.lgt, false); } if (data.skyAm) { data.skyAmIcon = self._parseSkyStateLowCase(data.skyAm, data.ptyAm, data.lgtAm, false); } if (data.skyPm) { data.skyPmIcon = self._parseSkyStateLowCase(data.skyPm, data.ptyPm, data.lgtPm, false); } }); } } catch(err) { return next(err); } next(); return this; }; function _getHourlyAqiData(airInfo, date) { var obj; var pollutants = airInfo.pollutants; if (!pollutants.hasOwnProperty('aqi')) { pollutants.aqi = {}; } if (!pollutants.aqi.hasOwnProperty('hourly')) { pollutants.aqi.hourly = []; } var hourly = pollutants.aqi.hourly; obj = hourly.find(function (aqiHourlyObj) { return aqiHourlyObj.date === date; }); if (obj == undefined) { obj = {date: date}; hourly.push(obj); } return obj; } function _insertHourlyAqiData(airInfo, newData) { var obj = _getHourlyAqiData(airInfo, newData.date); if (obj.hasOwnProperty('val')) { if (obj.val >= newData.val) { return false; } } for (var key in newData) { obj[key] = newData[key]; } return true; } this._insertForecastPollutants = function (airInfo, hourlyForecasts, source, airUnit) { var latestPastDate = '1970-01-01'; if (airInfo.last && airInfo.last.dataTime) { latestPastDate = airInfo.last.dataTime; } else if (airInfo.pollutants) { for (var key in airInfo.pollutants) { var pollutant = airInfo.pollutants[key]; if (pollutant.hourly && pollutant.hourly.length) { var newDate = pollutant.hourly[pollutant.hourly.length-1].date; if (latestPastDate < newDate) { latestPastDate = newDate; } } } } airInfo.forecastSource = source; airInfo.forecastPubDate = hourlyForecasts[hourlyForecasts.length-1].pubDate; var endForecastDate = new Date(latestPastDate); endForecastDate.setDate(endForecastDate.getDate()+1); endForecastDate = kmaTimeLib.convertDateToYYYY_MM_DD_HHoMM(endForecastDate); hourlyForecasts.forEach(function (forecast) { if (forecast == null) { return; } if (forecast.dataTime <= latestPastDate || forecast.dataTime > endForecastDate) { return; } var code = forecast.code; var pollutant = airInfo.pollutants[code]; if (pollutant == undefined) { pollutant = airInfo.pollutants[code] = {}; } //과거 데이터가 없으므로 빈껍데기 추가하고, 예보정보 추가함. if (pollutant.hourly == undefined) { var hourlyObj = {date: latestPastDate}; pollutant.hourly = []; pollutant.hourly.push(hourlyObj); return; } var hourlyData = pollutant.hourly.find(function (hourlyObj) { return hourlyObj.date === forecast.dataTime; }); if (hourlyData) { //skip past data return; } forecast.grade = AqiConverter.value2grade(airUnit, code, forecast.val); hourlyData = {date: forecast.dataTime, val: forecast.val, grade: forecast.grade, pubDate: forecast.pubDate}; pollutant.hourly.push(hourlyData); var aqiVal = AqiConverter.value2index(airUnit, code, forecast.val); var aqiData = {date: forecast.dataTime, code: code, val: aqiVal, grade: AqiConverter.value2grade(airUnit, 'aqi', aqiVal)}; _insertHourlyAqiData(airInfo, aqiData); }); if (source === 'kaq') { //make daily forecast var dailyArray = []; hourlyForecasts.forEach(function (forecast) { var day = forecast.dataTime.slice(0, 10); var dayForecast = self._createOrGetDaySummaryList(dailyArray, day); if (dayForecast[forecast.code] == undefined) { dayForecast[forecast.code] = {}; } if (dayForecast[forecast.code].hourly == undefined) { dayForecast[forecast.code].hourly = []; } dayForecast[forecast.code].hourly.push(forecast.val); }); //remove old data and last it does not have full time let strToday = latestPastDate.slice(0, 10); dailyArray = dailyArray.filter(obj => { return obj.date >= strToday; }); dailyArray.pop(); dailyArray.forEach(function (dayForecast) { var date = dayForecast.date; ['pm10', 'pm25', 'o3', 'no2', 'co', 'so2'].forEach(function (code) { var forecast = dayForecast[code]; if (forecast == undefined) { return; } var pollutant = airInfo.pollutants[code]; if (pollutant == undefined) { pollutant = airInfo.pollutants[code] = {}; } if (pollutant.daily == undefined) { pollutant.daily = []; } var dayData = pollutant.daily.find(function (hourlyObj) { return hourlyObj.date === date; }); if (dayData == undefined) { dayData = {}; pollutant.daily.push(dayData); } /** * 평균이 중요한게 아니라, 각 grade를 넘어서는 경우가 몇번인가로 구분해야 한다. * 최악을 12번이상 넘긴다면 최악, 최악이 1~12번이다 한때 최악 * 매우나쁨을 12번이상 넘긴다면 매우나쁨, 매우나쁨이 1~12번이다 한때 매우나쁨 */ dayData.date = date; dayData.maxVal = self._max(forecast.hourly, -1); dayData.minVal = self._min(forecast.hourly, -1); dayData.val = self._average(forecast.hourly, -1, 0); dayData.grade = AqiConverter.value2grade(airUnit, code, dayData.val); dayData.maxGrade = AqiConverter.value2grade(airUnit, code, dayData.maxVal); dayData.minGrade = AqiConverter.value2grade(airUnit, code, dayData.minVal); //forecast.overUnhealthyCount = self._countOverLimit() var aqiVal = AqiConverter.value2index(airUnit, code, dayData.val); var aqiMinVal = AqiConverter.value2index(airUnit, code, dayData.minVal); var aqiMaxVal = AqiConverter.value2index(airUnit, code, dayData.maxVal); var aqiData = {date: dayData.date, code: code, val: aqiVal, minVal: aqiMinVal, maxVal: aqiMaxVal, grade: AqiConverter.value2grade(airUnit, 'aqi', aqiVal), minGrade: AqiConverter.value2grade(airUnit, 'aqi', aqiMinVal), maxGrade: AqiConverter.value2grade(airUnit, 'aqi', aqiMaxVal)}; _insertDailyAqiData(airInfo, aqiData); }); }); log.debug('_insertForecastPollutants', JSON.stringify(airInfo)); //_insertDailyAqiData(airInfo, aqiData); } }; this._insertEmptyPollutantHourlyObj = function (lastDataTime) { var list = []; try { var date = new Date(lastDataTime); date.setHours(date.getHours()-24); for (var i=0; i<=24; i++) { var hourlyObj = {date: kmaTimeLib.convertDateToYYYY_MM_DD_HHoMM(date)}; list.push(hourlyObj); date.setHours(date.getHours()+1); } } catch (err) { log.error(err); } return list; }; /** * * @param pollutants * @param arpltnList * @param airUnit * @private */ this._insertHourlyPollutants = function (pollutants, arpltnList, airUnit, lastDataTime) { arpltnList.forEach(function (arpltn) { arpltn = KecoController.recalculateValue(arpltn, airUnit); if (arpltn.dataTime.indexOf("24:00") > 0) { arpltn.dataTime = kmaTimeLib.convertDateToYYYY_MM_DD_HHoMM(new Date(arpltn.dataTime)); } ['pm25', 'pm10', 'o3', 'no2', 'co', 'so2', 'aqi'].forEach(function (propertyName) { if (arpltn[propertyName+"Value"] == undefined) { log.debug("Fail to find "+propertyName+"Value"); return; } var pollutant = pollutants[propertyName]; if (pollutant == undefined) { pollutant = pollutants[propertyName] = {}; } if (!Array.isArray(pollutant.hourly)) { pollutant.hourly = self._insertEmptyPollutantHourlyObj(lastDataTime); //insert empty object } var hourlyData = pollutant.hourly.find(function (hourlyObj) { return hourlyObj.date === arpltn.dataTime; }); if (hourlyData == undefined) { log.debug("Fail to find arpltn dataTime: "+arpltn.dataTime+", code: "+propertyName); return; } hourlyData.val = arpltn[propertyName+"Value"]; hourlyData.grade = arpltn[propertyName+"Grade"]; }); }); }; function _getDailyAqiData(airInfo, date) { var obj; if (!airInfo.pollutants.hasOwnProperty('aqi')) { airInfo.pollutants.aqi = {}; } if (!airInfo.pollutants.aqi.hasOwnProperty('daily')) { airInfo.pollutants.aqi.daily = []; } obj = airInfo.pollutants.aqi.daily.find(function (aqiHourlyObj) { return aqiHourlyObj.date === date; }); if (obj == undefined) { obj = {date: date}; airInfo.pollutants.aqi.daily.push(obj); } return obj; } /** * val(평균)우선하고, 없는 경우 maxVal사용함. * @param airInfo * @param newData * @returns {boolean} * @private */ function _insertDailyAqiData(airInfo, newData) { var obj = _getDailyAqiData(airInfo, newData.date); if (obj.hasOwnProperty('val')) { if (obj.val >= newData.val) { return false; } } else if (obj.hasOwnProperty('maxVal')) { if (obj.maxVal >= newData.maxVal) { return false; } } for (var key in newData) { obj[key] = newData[key]; } return true; } this._insertDailyPollutants = function (airInfo, dailyList, airUnit) { var pollutants = airInfo.pollutants; dailyList.forEach(function (dayObj) { if ( !dayObj.hasOwnProperty('dustForecast') ) { return; } ['pm25', 'pm10', 'o3'].forEach(function (propertyName) { if (dayObj.dustForecast[propertyName.toUpperCase()+"Grade"] == undefined) { return; } var pollutant = pollutants[propertyName]; if (pollutant == undefined) { pollutant = pollutants[propertyName] = {}; } if (!Array.isArray(pollutant.daily)) { pollutant.daily = []; } var dailyData = pollutant.daily.find(function (obj) { var date = kmaTimeLib.convertYYYYMMDDtoYYYY_MM_DD(dayObj.date); return obj.date === date; }); if (dailyData == undefined) { dailyData = {date: kmaTimeLib.convertYYYYMMDDtoYYYY_MM_DD(dayObj.date)}; } var grade = dayObj.dustForecast[propertyName.toUpperCase()+"Grade"]+1; dailyData.minVal = AqiConverter.grade2minMaxValue('airkorea', propertyName, grade).min; dailyData.maxVal = AqiConverter.grade2minMaxValue('airkorea', propertyName, grade).max; dailyData.val = Math.round((dailyData.maxVal+dailyData.minVal)/2); dailyData.minGrade = AqiConverter.value2grade(airUnit, propertyName, dailyData.minVal); dailyData.maxGrade = AqiConverter.value2grade(airUnit, propertyName, dailyData.maxVal); dailyData.grade = AqiConverter.value2grade(airUnit, propertyName, dailyData.val); pollutant.daily.push(dailyData); var aqiMinVal = AqiConverter.value2index(airUnit, propertyName, dailyData.minVal); var aqiMaxVal = AqiConverter.value2index(airUnit, propertyName, dailyData.maxVal); var aqiVal = Math.round((aqiMinVal+aqiMaxVal)/2); var aqiData = {date: dailyData.date, code: propertyName, val: aqiVal, minVal: aqiMinVal, maxVal: aqiMaxVal, grade: AqiConverter.value2grade(airUnit, 'aqi', aqiVal), minGrade: AqiConverter.value2grade(airUnit, 'aqi', aqiMinVal), maxGrade: AqiConverter.value2grade(airUnit, 'aqi', aqiMaxVal)}; _insertDailyAqiData(airInfo, aqiData); }); }); }; this._getAirInfo = function (req) { if (req.airInfo == undefined) { req.airInfo = {source: "airkorea"}; } return req.airInfo; }; this.makeAirInfo = function (req, res, next) { var meta = {}; meta.sID = req.sessionID; meta.method = 'makeAirInfo'; meta.region = req.params.region; meta.city = req.params.city; meta.town = req.params.town; log.info(meta); try { var airInfo; var airUnit = req.query.airUnit || 'airkorea'; if(req.arpltnList) { if (airInfo == undefined) { airInfo = self._getAirInfo(req); } airInfo.last = req.arpltnList[0]; airInfo.pollutants = {}; self._insertHourlyPollutants(airInfo.pollutants, req.arpltnList, airUnit, airInfo.last.dataTime); } if ( req.midData && Array.isArray(req.midData.dailyData) ) { var dailyList = req.midData.dailyData.filter(function (value) { return value.hasOwnProperty('dustForecast'); }); if (dailyList && dailyList.length > 0) { if (airInfo == undefined) { airInfo = self._getAirInfo(req); } airInfo.pollutants = airInfo.pollutants || {}; self._insertDailyPollutants(airInfo, dailyList, airUnit); } } } catch (err) { err.message += ' ' + JSON.stringify(meta); log.error(err); } next(); return this; }; /** * make 3 objects * @param req * @param res * @param next * @returns {ControllerTown24h} */ this.makeAirInfoList = function (req, res, next) { var meta = {}; meta.sID = req.sessionID; meta.method = 'makeAirInfoList'; meta.region = req.params.region; meta.city = req.params.city; meta.town = req.params.town; log.info(meta); try { var airUnit = req.query.airUnit || 'airkorea'; if(req.arpltnStnList) { var airInfoList = []; for (var i=0; i<req.arpltnStnList.length; i++) { var arpltnList = req.arpltnStnList[i]; var airInfo = {source: "airkorea"}; airInfo.last = arpltnList[0]; airInfo.pollutants = {}; self._insertHourlyPollutants(airInfo.pollutants, arpltnList, airUnit, airInfo.last.dataTime); /** * airkorea의 경우 예보가 측정소별이 아니라 시/도 단위이므로, * 첫번째 측정소를 제외하고는 거리가 너무 멀 경우 예보가 측정소 위치랑 맞지 않을 수 있음 */ if ( req.midData && Array.isArray(req.midData.dailyData) ) { var dailyList = req.midData.dailyData.filter(function (value) { return value.hasOwnProperty('dustForecast'); }); if (dailyList && dailyList.length > 0) { airInfo.pollutants = airInfo.pollutants || {}; self._insertDailyPollutants(airInfo, dailyList, airUnit); } } airInfoList.push(airInfo); } if (airInfoList.length > 0) { req.airInfoList = airInfoList; } else { log.error('fail to make air info list', meta); } } else { log.error('arpltnList is undefined', meta); } } catch (err) { err.message += ' ' + JSON.stringify(meta); log.error(err); } next(); return this; }; this._getAirForecast = function(airInfo, forecastSource, airUnit, callback) { var ctrl; var stnName; try { stnName = airInfo.last.stationName; if (forecastSource === 'kaq') { ctrl = new KaqHourlyForecastCtrl(); } else if (forecastSource === 'airkorea') { ctrl = new AirkoreaHourlyForecastCtrl(); } else { throw new Error('Unknown air forecast source=' + forecastSource); } } catch (err) { return callback(err); } ctrl.getForecast(stnName, function (err, results) { if (err) { err.message += ' stnName:'+stnName; return callback(err); } try { if (results == undefined || results.length <= 0) { //울릉도 태하리는 아직 예보를 제공하지 않음. if (stnName === '태하리') { log.warn("Fail to get forecast stnName="+stnName); return callback(null, airInfo); } throw new Error("Fail to get forecast"); } self._insertForecastPollutants(airInfo, results, forecastSource, airUnit); } catch(err) { err.message += ' stnName:'+stnName; return callback(err); } callback(null, airInfo); }); }; this.AirForecast = function (req, res, next) { var meta = {}; meta.sID = req.sessionID; meta.method = 'AirForecast'; meta.region = req.params.region; meta.city = req.params.city; meta.town = req.params.town; log.info(meta); var forecastSource = req.query.airForecastSource; var airInfo = self._getAirInfo(req); self._getAirForecast(airInfo, forecastSource, req.query.airUnit, function (err) { if (err) { err.message += ' ' + JSON.stringify(meta); log.error(err); } next(); }); }; this.AirForecastList = function (req, res, next) { var meta = {}; meta.sID = req.sessionID; meta.method = 'AirForecastList'; meta.region = req.params.region; meta.city = req.params.city; meta.town = req.params.town; log.info(meta); var forecastSource = req.query.airForecastSource; var airUnit = req.query.airUnit; async.map(req.airInfoList, function (airInfo, callback) { self._getAirForecast(airInfo, forecastSource, airUnit, callback) }, function (err) { if (err) { err.message += ' ' + JSON.stringify(meta); log.error(err); } next(); }); }; this.sendDailySummaryResult = function (req, res) { var meta = {}; var result = {}; var regionName = req.params.region; var cityName = req.params.city; var townName = req.params.town; meta.method = '/:region/:city/:town'; meta.region = regionName; meta.city = cityName; meta.town = townName; log.info('## - ' + decodeURI(req.originalUrl) + ' sID=' + req.sessionID); result.regionName = regionName; result.cityName = cityName; result.townName = townName; result.dailySummary = req.dailySummary; res.json(result); return this; }; this.setYesterday = function (req, res, next) { var meta = {}; meta.sID = req.sessionID; meta.method = 'setYesterday'; meta.region = req.params.region; meta.city = req.params.city; meta.town = req.params.town; log.info(meta); try { if (!req.current || !req.currentList) { log.warn("Fail to find current weather or current list", meta); next(); return this; } var yesterdayDate = self._getCurrentTimeValue(+9-24); var yesterdayItem; if (yesterdayDate.time == '0000') { kmaTimeLib.convert0Hto24H(yesterdayDate); } /** * short 만들때, 당시간에 데이터가 없는 경우에 그 이전 데이터를 사용하지만, * 새로 데이터를 수집하면 23시간전부터 있음. * 그래서 해당 시간 데이터가 없는 경우 그 이후 데이터를 사용. */ for (var i=0; i<req.currentList.length-1; i++) { if (req.currentList[i].date == yesterdayDate.date && parseInt(req.currentList[i].time) >= parseInt(req.current.time)) { yesterdayItem = req.currentList[i]; break; } } if (yesterdayItem) { req.current.yesterday = yesterdayItem; } else { log.error('Fail to gt yesterday weather info', meta); } } catch (err) { err.message += ' ' + JSON.stringify(meta); log.error(err); } next(); return this; }; /** * WHO 경계 기준 PM2.5 25㎍/㎥, PM10 50㎍/㎥, O₃ 100㎍/㎥, SO₂ 20㎍/㎥, CO 25ppm, NO₂ 0.10 * @param current * @param units * @param res */ this.makeSummaryAir = function(current, units, res) { var str = ""; var item; var itemList = []; var ts = res || global; var airInfo = current.arpltn || current; airInfo.aqiValue = airInfo.khaiValue || airInfo.aqiValue; airInfo.aqiGrade = airInfo.khaiGrade || airInfo.aqiGrade; airInfo.aqiStr = airInfo.khaiStr || airInfo.aqiStr; //find over moderate pollutants var maxGrade = 0; for (var key in airInfo) { if (key.indexOf('Grade') >= 0) { if (key.indexOf('Grade24') >= 0) { continue; } if (airInfo[key] > maxGrade) { maxGrade = airInfo[key]; } } } if (maxGrade <= 0) { log.warn("airInfo is invalid! ", {airInfo: airInfo}); return ""; } else if (maxGrade === 1) { //대기상태가 좋아요 return ts.__('LOC_AIR_QUALITY_IS_GOOD'); } else if (maxGrade === 2) { //대기상태는 보통입니다 return ts.__('LOC_AIR_QUALITY_IS_MODERATE'); } //grade가 3(민감군주의or나쁨)이상인 경우 오염물질 표시 var locStr; if (airInfo.pm25Value) { locStr = ts.__('LOC_PM25'); str = locStr + " " + airInfo.pm25Value + " " + airInfo.pm25Str; item = {str: str, grade: airInfo.pm25Index}; itemList.push(item); } if (airInfo.pm10Value) { locStr = ts.__('LOC_PM10'); str = locStr + " " + airInfo.pm10Value + " " + airInfo.pm10Str; item = {str: str, grade: airInfo.pm10Index}; itemList.push(item); } if (airInfo.o3Value) { locStr = ts.__('LOC_O3'); str = locStr + " " + airInfo.o3Value + " " + airInfo.o3Str; item = {str: str, grade: airInfo.o3Index}; itemList.push(item); } if (airInfo.no2Grade) { locStr = ts.__('LOC_NO2'); str = locStr + " " + airInfo.no2Value + " " + airInfo.no2Str; item = {str: str, grade: airInfo.no2Index}; itemList.push(item); } if (airInfo.so2Grade) { locStr = ts.__('LOC_SO2'); str = locStr + " " + airInfo.so2Value + " " + airInfo.so2Str; item = {str: str, grade: airInfo.so2Index}; itemList.push(item); } if (airInfo.coGrade) { locStr = ts.__('LOC_CO'); str = locStr + " " + airInfo.coValue + " " + airInfo.coStr; item = {str: str, grade: airInfo.coIndex}; itemList.push(item); } itemList.sort(function (a, b) { if(a.grade > b.grade){ return -1; } if(a.grade < b.grade){ return 1; } return 0; }); log.info(JSON.stringify(itemList)); if (itemList.length === 0) { log.warn("Fail to make air summary"); return ""; } else { return itemList[0].str; } }; this.makeSummaryWeather = function(current, yesterday, units, res) { var str = ""; var item; var itemList = []; var diffTemp; var tmpGrade; var ts = res; /** * diff temp와 weather가 2.5로 특별한 날씨가 정보가 없으면 온도차와 날씨를 표시 */ if (current.hasOwnProperty('t1h') && yesterday && yesterday.hasOwnProperty('t1h')) { var obj = self._diffTodayYesterday(current, yesterday, ts); if (obj.grade <= 2) { obj.grade = 2.5; } item = {str: obj.str, grade: obj.grade}; itemList.push(item); } if (current.hasOwnProperty('weatherType')) { tmpGrade = 2.5; if (current.weatherType > 3) { tmpGrade = 3; } item = {str: current.weather, grade: tmpGrade}; itemList.push(item); } if (current.hasOwnProperty('specialInfo')) { var obj = current.specialInfo[0]; item = {str: obj.weatherStr+obj.levelStr, grade: obj.weather+5}; itemList.push(item); } if (current.rn1 && current.pty) { switch (current.pty) { case 1: current.ptyStr = ts.__('LOC_RAINFALL'); break; case 2: current.ptyStr = ts.__('LOC_PRECIPITATION'); break; case 3: current.ptyStr = ts.__('LOC_SNOWFALL'); break; default : current.ptyStr = ""; } current.rn1Str = current.rn1 + units.precipitationUnit; item = {str: current.ptyStr + " " + current.rn1Str, grade: current.rn1+3}; itemList.push(item); } if (current.dsplsGrade && current.dsplsGrade && current.t1h >= 20) { tmpGrade = current.dsplsGrade; str = ts.__('LOC_DISCOMFORT_INDEX') + " " + current.dsplsStr; item = {str:str, grade: tmpGrade}; itemList.push(item); } if (current.sensorytem && current.sensorytem !== current.t1h) { diffTemp = Math.round(current.sensorytem - current.t1h); str = ts.__('LOC_FEELS_LIKE') + ' ' + current.sensorytem +"˚"; item = {str : str, grade: Math.abs(diffTemp)}; itemList.push(item); } if (current.ultrv && current.time <= 15) { tmpGrade = current.ultrvGrade; if (current.time >= 11) { tmpGrade++; } str = ts.__('LOC_UV') +' '+current.ultrvStr; item = {str:str, grade: tmpGrade}; itemList.push(item); } if (current.wsdGrade && current.wsdStr) { //약함(1)을 보통으로 보고 보정 1함. item = {str: current.wsdStr, grade: current.wsdGrade+1}; itemList.push(item); } // if (current.fsnGrade && current.fsnStr) { // //주의(1)를 보통으로 보고 보정 1함. // str = ts.__('LOC_FOOD_POISONING') + ' ' + current.fsnStr; // item = {str: str, grade: current.fsnGrade+1}; // itemList.push(item); // } //감기 itemList.sort(function (a, b) { if(a.grade > b.grade){ return -1; } if(a.grade < b.grade){ return 1; } return 0; }); log.info(JSON.stringify(itemList)); if (itemList.length === 0) { log.error("Fail to make weather summary"); return ""; } else if(itemList.length > 1) { return itemList[0].str+", "+itemList[1].str; } else { return itemList[0].str; } }; /** * getSummary -> setYesterday + getSummaryAfterUnitConverter * @param req * @param res * @param next * @returns {ControllerTown24h} */ this.getSummaryAfterUnitConverter = function(req, res, next){ var meta = {}; meta.sID = req.sessionID; meta.method = 'getSummaryAfterUnitConverter'; meta.region = req.params.region; meta.city = req.params.city; meta.town = req.params.town; log.info(meta); try { if (!req.current || !req.currentList) { log.warn("Fail to find current weather or current list", meta); next(); return this; } var current = req.current; current.summaryWeather = self.makeSummaryWeather(current, current.yesterday, req.query, res); current.summaryAir = self.makeSummaryAir(current, req.query, res); current.summary = self.makeSummary(current, current.yesterday, req.query, res); } catch (err) { err.message += ' ' + JSON.stringify(meta); log.error(err); req.current.summary = ''; } next(); return this; }; this.makeResult = function (req, res, next) { var meta = {}; var result; var regionName = req.params.region; var cityName = req.params.city; var townName = req.params.town; meta.sID = req.sessionID; meta.method = 'makeResult'; meta.region = regionName; meta.city = cityName; meta.town = townName; try { if (req.result == undefined) { req.result = {}; } result = req.result; result.regionName = regionName; result.cityName = cityName; result.townName = townName; if(req.shortPubDate) { result.shortPubDate = req.shortPubDate; } if(req.shortRssPubDate) { result.shortRssPubDate = req.shortRssPubDate; } if(req.short) { if (req.short == undefined || req.short.length == undefined || req.short.length < 33) { log.error("short is invalid", meta); } result.short = req.short; } if (req.shortestPubDate) { result.shortestPubDate = req.shortestPubDate; } if(req.shortest) { result.shortest = req.shortest.filter(function (shortest) { return shortest.pubDate === result.shortestPubDate; }); } if(req.currentPubDate) { result.currentPubDate = req.currentPubDate; } if(req.current) { if (req.current == undefined || req.current.t1h == undefined || req.current.yesterday == undefined) { log.error("current is invalid", meta); } result.current = req.current; } if(req.midData) { if (req.midData.dailyData == undefined || req.midData.dailyData.length == undefined || req.midData.dailyData.length < 17) { log.error("daily data is invalid", meta); } //#2013 check date var daily = req.midData.dailyData; for (var i=0; i<daily.length-1; i++) { if (daily[i].date === daily[i+1].date) { var resInfo = {index: i, date: daily[i].date, regionName: regionName, cityName: cityName, townName: townName}; log.error('Same date in dailyData', JSON.stringify(resInfo), meta); } if (daily[i].dayOfWeek != undefined && daily[i].dayOfWeek === daily[i+1].dayOfWeek) { resInfo = {index: i, date: daily[i].date, regionName: regionName, cityName: cityName, townName: townName}; log.error('Same day of week in dailyData', JSON.stringify(resInfo), meta); } } result.midData = req.midData; } if (req.dailySummary) { result.dailySummary = req.dailySummary; } if (req.airInfoList) { result.airInfoList = req.airInfoList; } else if (req.airInfo) { result.airInfo = req.airInfo; } result.source = "KMA"; var units ={}; UnitConverter.getUnitList().forEach(function (value) { units[value] = req.query[value] || UnitConverter.getDefaultValue(value); }); result.units = units; if (req.gCoord && req.version >= 'v000901') { result.location = {lat: parseFloat(req.gCoord.lat.toFixed(3)), long: parseFloat(req.gCoord.lon.toFixed(3))}; } } catch(err) { err.message += ' ' + JSON.stringify(meta); log.error(err); next(err); return this; } next(); return this; }; this.sendResult = function (req, res) { log.info('## - ' + decodeURI(req.originalUrl) + ' sID=' + req.sessionID); res.json(req.result); }; this._convertAirInfo = function (airInfo, airUnit, currentDate) { if (airInfo.hasOwnProperty('last')) { KecoController.recalculateValue(airInfo.last, airUnit); } if (airInfo.hasOwnProperty('pollutants')) { var pollutants = airInfo.pollutants; for (var pollutantName in pollutants) { if (pollutants[pollutantName].hasOwnProperty('daily')) { pollutants[pollutantName].daily.forEach(function (value) { value.fromToday = kmaTimeLib.getDiffDays(value.date, currentDate); value.dayOfWeek = (new Date(value.date)).getDay(); }); } } } }; this.convertUnits = function (req, res, next) { var meta = {}; meta.sID = req.sessionID; meta.method = 'convertUnits'; meta.region = req.params.region; meta.city = req.params.city; meta.town = req.params.town; log.info(meta); try { var current = req.current; var currentDate; if (current.hasOwnProperty('stnDateTime')) { current.dateObj = kmaTimeLib.convertYYYYoMMoDDoHHoMMtoYYYYoMMoDD_HHoMM(current.stnDateTime); } else { current.dateObj = kmaTimeLib.convertYYYYMMDDHHMMtoYYYYoMMoDD_HHoMM(current.date+current.time); } currentDate = current.dateObj; current.time = parseInt(current.time.slice(0, -2)); self._convertWeatherData(current, req.query); self._convertWeatherData(current.yesterday, req.query); current.yesterday.time = parseInt(current.yesterday.time.slice(0, -2)); req.shortest.forEach(function (value) { value.dateObj = kmaTimeLib.convertYYYYMMDDHHMMtoYYYYoMMoDD_HHoMM(value.date+value.time); self._convertWeatherData(value, req.query); }); var short = req.short; var foundCurrentIndex = false; short.forEach(function (value, index) { value.dateObj = kmaTimeLib.convertYYYYMMDDHHMMtoYYYYoMMoDD_HHoMM(value.date+value.time); value.time = parseInt(value.time.slice(0, -2)); value.fromToday = kmaTimeLib.getDiffDays(value.dateObj, currentDate); if (foundCurrentIndex === false && value.dateObj <= currentDate) { if (index === short.length-1) { value.currentIndex = true; } else { var nextObj = short[index+1]; var nextIndexDate = kmaTimeLib.convertYYYYMMDDHHMMtoYYYYoMMoDD_HHoMM(nextObj.date+nextObj.time); if(currentDate <= nextIndexDate) { value.currentIndex = true; } } } self._convertWeatherData(value, req.query); }); req.midData.dailyData.forEach(function (value, index) { value.dateObj = kmaTimeLib.convertYYYYMMDDHHMMtoYYYYoMMoDD_HHoMM(value.date+"0000"); value.skyAm = value.skyAmIcon; value.skyPm = value.skyPmIcon; value.tmx = value.taMax; value.tmn = value.taMin; value.fromToday = kmaTimeLib.getDiffDays(value.dateObj, currentDate); value.dayOfWeek = (new Date(value.dateObj)).getDay(); if (value.date === current.date) { current.todayIndex = index; } if (!(value.dustForecast == undefined)) { var dustForecast = value.dustForecast; if (!(dustForecast.PM10Grade == undefined)) { dustForecast.pm10Grade = dustForecast.PM10Grade+1; dustForecast.pm10Str = dustForecast.PM10Str; delete dustForecast.PM10Grade; delete dustForecast.PM10Str; } if (!(dustForecast.PM25Grade == undefined)) { dustForecast.pm25Grade = dustForecast.PM25Grade+1; dustForecast.pm25Str = dustForecast.PM25Str; delete dustForecast.PM25Grade; delete dustForecast.PM25Str; } if (!(dustForecast.O3Grade == undefined)) { dustForecast.o3Grade = dustForecast.O3Grade+1; dustForecast.o3Str = dustForecast.O3Str; delete dustForecast.O3Grade; delete dustForecast.O3Str; } } delete value.skyAmIcon; delete value.skyPmIcon; delete value.taMax; delete value.taMin; self._convertWeatherData(value, req.query); }); if (req.current.hasOwnProperty('arpltn')) { KecoController.recalculateValue(req.current.arpltn, req.query.airUnit); } if (req.hasOwnProperty('airInfoList')) { req.airInfoList.forEach(function (airInfo) { self._convertAirInfo(airInfo, req.query.airUnit, currentDate); }); } else if (req.hasOwnProperty('airInfo')) { self._convertAirInfo(req.airInfo, req.query.airUnit, currentDate); } } catch (err) { err.message += ' ' + JSON.stringify(meta); log.error(err); } return next(); }; function _request(url, lang, callback) { log.info({_request:{url:url}}); let options = {json: true, timeout: 3000}; if (lang) { options.headers = {'Accept-Language' : lang}; } request(url, options, (err, response, body) => { if (err) { return callback(err); } if (response.statusCode >= 400) { err = new Error("url=" + url + " statusCode=" + response.statusCode); return callback(err); } callback(err, body); }); } function _retryRequest(url, lang, callback) { async.retry(3, (cb) => { _request(url, lang, (err, result) => { if (err) { return cb(err); } cb(null, result); }); }, (err, result) => { if (err) { return callback(err); } callback(null, result); }); } this.coord2addr = function (req, res, next) { var loc = req.params.loc; if (loc == undefined) { throw new Error("Invalid loc"); } var lang; if (req.headers['accept-language']) { lang = req.headers['accept-language']; } var url = config.apiServer.url + '/geocode/coord/'+loc; _retryRequest(url, lang, (err, geoInfo)=> { if (err) { return next(err); } if (!geoInfo.kmaAddress) { return next(new Error('Fail to get kma address loc:'+loc)); } var kmaAddress = geoInfo.kmaAddress; req.params.region = kmaAddress.name1; if (kmaAddress.name2) { req.params.city = kmaAddress.name2; } if (kmaAddress.name3) { req.params.town = kmaAddress.name3; } next(); }); }; this.getSpecialInfo = function (req, res, next) { var kmaSpecial = new KmaSpecialWeatherController(); var town; var stnName; try { town = {first:req.params.region, second:req.params.city, third:req.params.town}; stnName = req.current.nearStnName; } catch (e) { log.error(e); return next(); } kmaSpecial.getSpecialInfo(town, stnName, function(err, list) { if (err) { log.error(err); return next(); } req.current = req.current || {}; if (list && list.length > 0) { req.current.specialInfo = list; } return next(); }); }; } // subclass extends superclass ControllerTown24h.prototype = Object.create(ControllerTown.prototype); ControllerTown24h.prototype.constructor = ControllerTown24h; ControllerTown24h.prototype._parseSkyState = function (sky, pty, lgt, isNight) { var skyIconName = ""; if (isNight) { skyIconName = "Moon"; } else { skyIconName = "Sun"; } switch (sky) { case 1: skyIconName; break; case 2: skyIconName += "SmallCloud"; break; case 3: skyIconName += "BigCloud"; //Todo need new icon break; case 4: skyIconName = "Cloud"; //overwrite Moon/Sun break; default: log.error('Fail to parse sky='+sky); break; } switch (pty) { case 0: //nothing break; case 1: skyIconName += "Rain"; break; case 2: skyIconName += "RainSnow"; //Todo need RainWithSnow icon"; break; case 3: skyIconName += "Snow"; break; default: log.error('Fail to parse pty='+pty); break; } if (lgt === 1) { skyIconName += "Lightning"; } return skyIconName; }; ControllerTown24h.prototype._parseSkyStateLowCase = function (sky, pty, lgt, isNight) { var skyIconName = ""; if (isNight) { skyIconName = "moon"; } else { skyIconName = "sun"; } switch (sky) { case 1: skyIconName; break; case 2: skyIconName += "_smallcloud"; break; case 3: skyIconName += "_bigcloud"; //Todo need new icon break; case 4: skyIconName = "cloud"; //overwrite Moon/Sun break; default: log.error('Fail to parse sky='+sky); break; } switch (pty) { case 0: //nothing break; case 1: skyIconName += "_rain"; break; case 2: skyIconName += "_rainsnow"; //Todo need RainWithSnow icon"; break; case 3: skyIconName += "_snow"; break; default: log.error('Fail to parse pty='+pty); break; } if (lgt === 1) { skyIconName += "_lightning"; } return skyIconName; }; ControllerTown24h.prototype._getEmoji = function (name) { switch (name) { case 'UpwardsArrow': return '\u2191'; case 'RightwardsArrow': return '\u2192'; case 'DownwardsArrow': return '\u2193'; case 'UpwardsArrowToBar': return '\u2912'; case 'DownwardsArrowToBar': return '\u2913'; default: log.error('Fail to find emoji name='+name); } return ''; }; ControllerTown24h.prototype._getWeatherEmoji = function (skyIcon) { var icon = skyIcon.toLowerCase(); if (icon.indexOf('lightning') != -1) { return '\u26c8'; } else if (icon.indexOf('rainsnow') != -1) { return '\u2614\u2603'; } else if (icon.indexOf('rain') != -1) { return '\u2614'; } else if (icon.indexOf('snow') != -1) { return '\u2603'; } else if (icon.indexOf('cloud') != -1) { if (icon.indexOf('sun') != -1 || icon.indexOf('moon') != -1) { return '\u26c5'; } else { return '\u2601'; } } else if (icon.indexOf('sun') != -1 || icon.indexOf('moon') != -1) { return '\ud83c\udf1e'; } log.error('Fail to find emoji icon='+icon); return ''; }; /** * temperatureUnit(C,F), windSpeedUnit(mph,km/h,m/s,bft,kr), pressureUnit(mmHg,inHg,hPa,mb), * distanceUnit(km,mi), precipitationUnit(mm,in), airUnit(airkorea,airkorea_who,airnow,aqicn) * @param wData * @param query * @returns {ControllerTown24h} * @private */ ControllerTown24h.prototype._convertWeatherData = function(wData, query) { var unitConverter = new UnitConverter(); var toTempUnit; var toWindUnit; var toPressUnit; var toDistUnit; var toPrecipUnit; var defaultValueList; if (wData == undefined) { log.error('Invalid weather data for converting'); return this; } if (query == undefined) { log.error('Invalid query for converting'); return this; } toTempUnit = query.temperatureUnit; toPrecipUnit = query.precipitationUnit; toWindUnit = query.windSpeedUnit; toPressUnit = query.pressureUnit; toDistUnit = query.distanceUnit; defaultValueList = UnitConverter.getDefaultValueList(); //convert cm to mm s06, sn1, s1d ['s06', 'sn1', 's1d'].forEach(function (name) { if (wData.hasOwnProperty(name)) { wData[name] *= 10; } }); if (toTempUnit && toTempUnit !== defaultValueList['temperatureUnit']) { //client에서는 taMax,taMin은 tmx, tmn으로 변환해서 사용하고 있음. ['t1h', 'sensorytem', 'dpt', 'heatIndex', 't3h', 'tmx', 'tmn', 't1d'].forEach(function (name) { if (wData.hasOwnProperty(name) && wData[name] !== -50) { wData[name] = unitConverter.convertUnits(defaultValueList['temperatureUnit'], toTempUnit, wData[name]); if (toTempUnit === 'F') { wData[name] = Math.floor(wData[name]); } } }); } //will remove rs1h, rs1d if (toPrecipUnit && toPrecipUnit !== defaultValueList['precipitationUnit']) { ['rn1', 'rs1h', 'rs1d', 'r06', 's06', 'sn1', 's1d'].forEach(function (name) { if (wData.hasOwnProperty(name)) { wData[name] = unitConverter.convertUnits(defaultValueList['precipitationUnit'], toWindUnit, wData[name]); } }); } if (wData.hasOwnProperty('wsd')) { wData.wsd = unitConverter.convertUnits(defaultValueList['windSpeedUnit'], toWindUnit, wData.wsd); } if (wData.hasOwnProperty('hPa')) { wData.hPa = unitConverter.convertUnits(defaultValueList['pressureUnit'], toPressUnit, wData.hPa); } if (wData.hasOwnProperty('visibility')) { wData.visibility = unitConverter.convertUnits(defaultValueList['distanceUnit'], toDistUnit, wData.visibility); } }; module.exports = ControllerTown24h;
{ "content_hash": "c22c7b0aab738adc8c81b1ca8cbf54d7", "timestamp": "", "source": "github", "line_count": 2158, "max_line_length": 143, "avg_line_length": 35.549582947173306, "alnum_prop": 0.4838886281870796, "repo_name": "skywlrl/TodayWeather", "id": "c007665a821dab42b306da07ab5d7258ca67d3be", "size": "78252", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/controllers/controllerTown24h.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "15215" }, { "name": "C", "bytes": "651896" }, { "name": "C++", "bytes": "14966" }, { "name": "CSS", "bytes": "2492341" }, { "name": "HTML", "bytes": "246926" }, { "name": "JavaScript", "bytes": "13220783" }, { "name": "Objective-C", "bytes": "1292046" }, { "name": "Shell", "bytes": "7764" } ], "symlink_target": "" }
using System; namespace Alachisoft.NGroups { [Serializable] public class TimeoutException:System.Exception { public System.Collections.IList failed_mbrs = null; // members that failed responding public TimeoutException():base("TimeoutExeption") { } public TimeoutException(string msg):base(msg) { } public TimeoutException(System.Collections.IList failed_mbrs):base("TimeoutExeption") { this.failed_mbrs = failed_mbrs; } public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(base.ToString()); if (failed_mbrs != null && failed_mbrs.Count > 0) sb.Append(" (failed members: ").Append(failed_mbrs); return sb.ToString(); } } }
{ "content_hash": "26626beedf7aba835bb04e430d565d47", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 87, "avg_line_length": 21.485714285714284, "alnum_prop": 0.6914893617021277, "repo_name": "Alachisoft/NCache", "id": "1120b9a0489520372a5a1e7524fc5f6062b84eaf", "size": "826", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Src/NCCluster/TimeoutException.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "12283536" }, { "name": "CSS", "bytes": "707" }, { "name": "HTML", "bytes": "16825" }, { "name": "JavaScript", "bytes": "377" } ], "symlink_target": "" }
@implementation UADDBUpdateItemResponse @synthesize attributes=_attributes, consumedCapacity=_consumedCapacity, itemCollectionMetrics=_itemCollectionMetrics; - (id)init { if (self = [super init]) { [self UA_addDDBKeyValueAdditionalAccessorForSelector:@selector(attributeValueForAttributeName:) propertyName:@"attributes"]; } return self; } + (NSDictionary *)JSONKeyPathsByPropertyKey { // Start with super's key paths (if there are any) NSMutableDictionary *keyPaths = [[UADDBResponse JSONKeyPathsByPropertyKey] mutableCopy]; [keyPaths addEntriesFromDictionary: @{ @"attributes": @"Attributes", @"consumedCapacity": @"ConsumedCapacity", @"itemCollectionMetrics": @"ItemCollectionMetrics" }]; return [keyPaths copy]; } + (NSValueTransformer *)attributesJSONTransformer { return [NSValueTransformer UA_JSONDynamoDBDictionaryTransformer]; } + (NSValueTransformer *)consumedCapacityJSONTransformer { return [NSValueTransformer UAMTL_JSONDictionaryTransformerWithModelClass:[UADDBConsumedCapacity class]]; } + (NSValueTransformer *)itemCollectionMetricsJSONTransformer { return [NSValueTransformer UAMTL_JSONDictionaryTransformerWithModelClass:[UADDBItemCollectionMetrics class]]; } @end #pragma clang diagnostic pop
{ "content_hash": "b1623d2eed033d387e0a077585b1aecd", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 126, "avg_line_length": 27.404255319148938, "alnum_prop": 0.7756211180124224, "repo_name": "unsignedapps/ua-aws-sdk-ios", "id": "8ae1eddff66b617543f92db0c0dc6f86b6e8f6bf", "size": "1668", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AWS iOS SDK/DDB/Responses/UADDBUpdateItemResponse.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "42359" }, { "name": "Objective-C", "bytes": "4812683" }, { "name": "Ruby", "bytes": "1520" } ], "symlink_target": "" }
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="SinglePlayerGames.html" type="JavascriptDebugType" factoryName="JavaScript Debug" nameIsGenerated="true" uri="http://localhost:63342/WE-Bowler-html5/src/SinglePlayerGames.html"> <method /> </configuration> </component>
{ "content_hash": "3917d9586f247cd70d5513c41ee9347b", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 216, "avg_line_length": 62.6, "alnum_prop": 0.7891373801916933, "repo_name": "WhiteWolf1776/WE-Bowler-html5", "id": "df06340119f843ab40fd00200f86a64c211883df", "size": "313", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/runConfigurations/SinglePlayerGames_html.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12432" }, { "name": "HTML", "bytes": "13694" }, { "name": "JavaScript", "bytes": "30132" } ], "symlink_target": "" }
package edu.harvard.iq.dataverse.confirmemail; /** * * @author bsilverstein */ public class ConfirmEmailException extends Exception { public ConfirmEmailException(String message) { super(message); } public ConfirmEmailException(String message, Throwable cause) { super(message, cause); } }
{ "content_hash": "2b345a71ae69458405fcfbf06eb902e7", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 67, "avg_line_length": 19.352941176470587, "alnum_prop": 0.6960486322188449, "repo_name": "JayanthyChengan/dataverse", "id": "add7cd922fbde2cb7c6104ee3035a8f05f2a4312", "size": "329", "binary": false, "copies": "13", "ref": "refs/heads/dataverse-contactform-afflist", "path": "src/main/java/edu/harvard/iq/dataverse/confirmemail/ConfirmEmailException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "48137" }, { "name": "HTML", "bytes": "781240" }, { "name": "Java", "bytes": "4153477" }, { "name": "JavaScript", "bytes": "390936" }, { "name": "Makefile", "bytes": "3299" }, { "name": "Perl", "bytes": "58151" }, { "name": "Python", "bytes": "58198" }, { "name": "R", "bytes": "36411" }, { "name": "Ruby", "bytes": "1670" }, { "name": "Shell", "bytes": "96276" }, { "name": "XSLT", "bytes": "455" } ], "symlink_target": "" }
/* */ 'use strict'; Object.defineProperty(exports, "__esModule", {value: true}); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin); var _svgIcon = require('../../svg-icon'); var _svgIcon2 = _interopRequireDefault(_svgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj}; } var AvFiberSmartRecord = _react2.default.createClass({ displayName: 'AvFiberSmartRecord', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('g', null, _react2.default.createElement('circle', { cx: '9', cy: '12', r: '8' }), _react2.default.createElement('path', {d: 'M17 4.26v2.09c2.33.82 4 3.04 4 5.65s-1.67 4.83-4 5.65v2.09c3.45-.89 6-4.01 6-7.74s-2.55-6.85-6-7.74z'}))); } }); exports.default = AvFiberSmartRecord; module.exports = exports['default'];
{ "content_hash": "bb7cd34b5db6cd95da7421df13e25693", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 157, "avg_line_length": 44.96, "alnum_prop": 0.7046263345195729, "repo_name": "nayashooter/ES6_React-Bootstrap", "id": "9372c4ff10c98870cbefc79ac1f3bdb4db4056c3", "size": "1124", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/jspm_packages/npm/material-ui@0.14.4/lib/svg-icons/av/fiber-smart-record.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2994" }, { "name": "HTML", "bytes": "2057" }, { "name": "JavaScript", "bytes": "13972689" }, { "name": "LiveScript", "bytes": "7961" }, { "name": "Makefile", "bytes": "451" }, { "name": "Shell", "bytes": "73" } ], "symlink_target": "" }
<?xml version="1.0" standalone="yes"?> <CalibrationProject> <xs:schema id="CalibrationProject" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="CalibrationProject" msdata:IsDataSet="true" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="data"> <xs:complexType> <xs:sequence> <xs:element name="ObjWidth" type="xs:int" minOccurs="0" /> <xs:element name="ObjHeight" type="xs:int" minOccurs="0" /> <xs:element name="FieldSize" type="xs:double" minOccurs="0" /> <xs:element name="DetectionMethod" type="xs:int" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="images"> <xs:complexType> <xs:sequence> <xs:element name="ImagePath" type="xs:string" minOccurs="0" /> <xs:element name="SourceType" type="xs:int" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="results"> <xs:complexType> <xs:sequence> <xs:element name="ImageCount" type="xs:int" minOccurs="0" /> <xs:element name="focus_lenX" type="xs:double" minOccurs="0" /> <xs:element name="focus_lenY" type="xs:double" minOccurs="0" /> <xs:element name="PrincipalX" type="xs:double" minOccurs="0" /> <xs:element name="PrincipalY" type="xs:double" minOccurs="0" /> <xs:element name="Dist1" type="xs:double" minOccurs="0" /> <xs:element name="Dist2" type="xs:double" minOccurs="0" /> <xs:element name="Dist3" type="xs:double" minOccurs="0" /> <xs:element name="Dist4" type="xs:double" minOccurs="0" /> <xs:element name="focus_lenX_er" type="xs:double" minOccurs="0" /> <xs:element name="focus_lenY_er" type="xs:double" minOccurs="0" /> <xs:element name="PrincipalX_er" type="xs:double" minOccurs="0" /> <xs:element name="PrincipalY_er" type="xs:double" minOccurs="0" /> <xs:element name="Dist1_er" type="xs:double" minOccurs="0" /> <xs:element name="Dist2_er" type="xs:double" minOccurs="0" /> <xs:element name="Dist3_er" type="xs:double" minOccurs="0" /> <xs:element name="Dist4_er" type="xs:double" minOccurs="0" /> <xs:element name="dc_AllImage_errX" type="xs:double" minOccurs="0" /> <xs:element name="dc_AllImage_errY" type="xs:double" minOccurs="0" /> <xs:element name="Calib_Date" type="xs:string" minOccurs="0" /> <xs:element name="Calib_Type" type="xs:int" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> <data> <ObjWidth>5</ObjWidth> <ObjHeight>6</ObjHeight> <FieldSize>29</FieldSize> <DetectionMethod>3</DetectionMethod> </data> <data> <ObjWidth>7</ObjWidth> <ObjHeight>10</ObjHeight> <FieldSize>21.5</FieldSize> <DetectionMethod>3</DetectionMethod> </data> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6954.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6955.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6956.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6957.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6958.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6959.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6960.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6961.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6962.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6963.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6964.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6965.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6966.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6967.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6968.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6969.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6970.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6973.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6974.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6975.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6976.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6977.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6978.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6979.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6980.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6981.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6982.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6983.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6984.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6985.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6987.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6988.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6989.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6990.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6993.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6994.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6995.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6996.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6997.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6998.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR6999.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR7000.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR7001.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR7002.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR7003.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR7004.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR7005.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR7006.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR7007.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR7008.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR7009.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR7010.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR7011.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR7012.JPG</ImagePath> <SourceType>0</SourceType> </images> <images> <ImagePath>H:\Projects\Flights\Camera Calibration\GoPro Hero Black Camera cal\GoPro camera cal\GOPR7013.JPG</ImagePath> <SourceType>0</SourceType> </images> <results> <ImageCount>55</ImageCount> <focus_lenX>1789.987745777602</focus_lenX> <focus_lenY>1811.2655616766015</focus_lenY> <PrincipalX>2012.7835966962634</PrincipalX> <PrincipalY>1509.81618794889</PrincipalY> <Dist1>-0.18548026513384971</Dist1> <Dist2>0.02452750534577456</Dist2> <Dist3>-0.00043497000682752928</Dist3> <Dist4>0.00020446158823213652</Dist4> <focus_lenX_er>3.3676886558532715</focus_lenX_er> <focus_lenY_er>3.4943766593933105</focus_lenY_er> <PrincipalX_er>2.3686425685882568</PrincipalX_er> <PrincipalY_er>2.5695276260375977</PrincipalY_er> <Dist1_er>0.0011719877365976572</Dist1_er> <Dist2_er>0.0007742646848782897</Dist2_er> <Dist3_er>0.00013010365364607424</Dist3_er> <Dist4_er>0.00011762924987124279</Dist4_er> <dc_AllImage_errX>9.0577202702547677</dc_AllImage_errX> <dc_AllImage_errY>6.8625246834168463</dc_AllImage_errY> <Calib_Date>10/05/2014 3:54:43 p.m.</Calib_Date> <Calib_Type>2</Calib_Type> </results> </CalibrationProject>
{ "content_hash": "8db210f3f94eeacd37d5a1e59f5b4926", "timestamp": "", "source": "github", "line_count": 311, "max_line_length": 142, "avg_line_length": 45.82636655948553, "alnum_prop": 0.6956216671344373, "repo_name": "amarburg/camera_undistort", "id": "78e67d30d42220bb4cafd19f1df9ed87f899dd1b", "size": "14252", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sample/better_coverage.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "149756" } ], "symlink_target": "" }
#define SQUID_UNIT_TEST 1 #include "squid.h" #include "testStoreSupport.h" #include "event.h" #include "EventLoop.h" #include "SquidTime.h" /* construct a stock loop with event dispatching, a time service that advances * 1 second a tick */ StockEventLoop::StockEventLoop() : default_time_engine(TimeEngine()) { registerEngine(EventScheduler::GetInstance()); setTimeService(&default_time_engine); }
{ "content_hash": "1c6785b6f6b5e68dda720b9afe46cf1f", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 78, "avg_line_length": 22.88888888888889, "alnum_prop": 0.7378640776699029, "repo_name": "spaceify/spaceify", "id": "89664c54936b771dd28cd65e32c1b900246df12d", "size": "1817", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "squid/squid3-3.3.8.spaceify/src/tests/testStoreSupport.cc", "mode": "33188", "license": "mit", "language": [ { "name": "Awk", "bytes": "5027" }, { "name": "C", "bytes": "6727964" }, { "name": "C++", "bytes": "7435855" }, { "name": "CSS", "bytes": "9138" }, { "name": "CoffeeScript", "bytes": "10353" }, { "name": "Groff", "bytes": "253204" }, { "name": "HTML", "bytes": "67045" }, { "name": "JavaScript", "bytes": "559321" }, { "name": "M4", "bytes": "241674" }, { "name": "Makefile", "bytes": "5753890" }, { "name": "Objective-C", "bytes": "1898" }, { "name": "Perl", "bytes": "152532" }, { "name": "Python", "bytes": "60106" }, { "name": "Shell", "bytes": "3088278" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; namespace RimTrans.Lite.Converters { class EnumerationToBoolean : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value.Equals(parameter); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value.Equals(true) ? parameter : Binding.DoNothing; } } }
{ "content_hash": "f9e429f362a78d5ee7c5e9d35bc08e9e", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 103, "avg_line_length": 27.291666666666668, "alnum_prop": 0.7022900763358778, "repo_name": "duduluu/RimTrans", "id": "b85340b55f833b07a424493feead08785e55d391", "size": "657", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RimTrans.Lite/Converters/EnumerationToBoolean.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "453236" } ], "symlink_target": "" }
package org.apache.camel.component.netty4.http; import java.util.ArrayList; import java.util.List; import io.netty.channel.ChannelHandler; import org.apache.camel.RuntimeCamelException; import org.apache.camel.component.netty4.NettyConfiguration; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriParams; /** * Extended configuration for using HTTP with Netty. */ @UriParams public class NettyHttpConfiguration extends NettyConfiguration { @UriParam private boolean urlDecodeHeaders; @UriParam(defaultValue = "true") private boolean mapHeaders = true; @UriParam(defaultValue = "false") private boolean compression; @UriParam(defaultValue = "true") private boolean throwExceptionOnFailure = true; @UriParam(defaultValue = "false") private boolean transferException; @UriParam(defaultValue = "false") private boolean matchOnUriPrefix; @UriParam(defaultValue = "false") private boolean bridgeEndpoint; @UriParam private String path; @UriParam(defaultValue = "false") private boolean disableStreamCache; @UriParam(defaultValue = "true") private boolean send503whenSuspended = true; @UriParam(defaultValue = "" + 1024 * 1024) private int chunkedMaxContentLength = 1024 * 1024; @UriParam(defaultValue = "true") private boolean chunked = true; public NettyHttpConfiguration() { // we need sync=true as http is request/reply by nature setSync(true); setReuseAddress(true); setServerInitializerFactory(new HttpServerInitializerFactory()); setClientInitializerFactory(new HttpClientInitializerFactory()); } @Override public NettyHttpConfiguration copy() { try { // clone as NettyHttpConfiguration NettyHttpConfiguration answer = (NettyHttpConfiguration) clone(); // make sure the lists is copied in its own instance List<ChannelHandler> encodersCopy = new ArrayList<ChannelHandler>(getEncoders()); answer.setEncoders(encodersCopy); List<ChannelHandler> decodersCopy = new ArrayList<ChannelHandler>(getDecoders()); answer.setDecoders(decodersCopy); return answer; } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public boolean isCompression() { return compression; } public void setCompression(boolean compression) { this.compression = compression; } public boolean isThrowExceptionOnFailure() { return throwExceptionOnFailure; } public void setThrowExceptionOnFailure(boolean throwExceptionOnFailure) { this.throwExceptionOnFailure = throwExceptionOnFailure; } public boolean isTransferException() { return transferException; } public void setTransferException(boolean transferException) { this.transferException = transferException; } public boolean isUrlDecodeHeaders() { return urlDecodeHeaders; } public void setUrlDecodeHeaders(boolean urlDecodeHeaders) { this.urlDecodeHeaders = urlDecodeHeaders; } public boolean isMapHeaders() { return mapHeaders; } public void setMapHeaders(boolean mapHeaders) { this.mapHeaders = mapHeaders; } public boolean isMatchOnUriPrefix() { return matchOnUriPrefix; } public void setMatchOnUriPrefix(boolean matchOnUriPrefix) { this.matchOnUriPrefix = matchOnUriPrefix; } public boolean isBridgeEndpoint() { return bridgeEndpoint; } public void setBridgeEndpoint(boolean bridgeEndpoint) { this.bridgeEndpoint = bridgeEndpoint; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public boolean isDisableStreamCache() { return disableStreamCache; } public void setDisableStreamCache(boolean disableStreamCache) { this.disableStreamCache = disableStreamCache; } public boolean isSend503whenSuspended() { return send503whenSuspended; } public void setSend503whenSuspended(boolean send503whenSuspended) { this.send503whenSuspended = send503whenSuspended; } public boolean isChunked() { return chunked; } public void setChunked(boolean chunked) { this.chunked = chunked; } public int getChunkedMaxContentLength() { return chunkedMaxContentLength; } public void setChunkedMaxContentLength(int chunkedMaxContentLength) { this.chunkedMaxContentLength = chunkedMaxContentLength; } // Don't support allowDefaultCodec public boolean isAllowDefaultCodec() { return false; } public void setAllowDefaultCodec(boolean allowDefaultCodec) { throw new UnsupportedOperationException("You cannot setAllowDefaultCodec here."); } }
{ "content_hash": "8e2445fc824e6ce081dff3fd5337d338", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 93, "avg_line_length": 28.815028901734102, "alnum_prop": 0.6944834503510532, "repo_name": "logzio/camel", "id": "39fe13517b86db2ade47c7d3bf74c24397841d80", "size": "5788", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/camel-netty4-http/src/main/java/org/apache/camel/component/netty4/http/NettyHttpConfiguration.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "20202" }, { "name": "Batchfile", "bytes": "106" }, { "name": "CSS", "bytes": "221391" }, { "name": "Eagle", "bytes": "2898" }, { "name": "Elm", "bytes": "5970" }, { "name": "FreeMarker", "bytes": "12394" }, { "name": "Groovy", "bytes": "23444" }, { "name": "HTML", "bytes": "406194" }, { "name": "Java", "bytes": "42719701" }, { "name": "JavaScript", "bytes": "3695475" }, { "name": "PHP", "bytes": "88860" }, { "name": "Protocol Buffer", "bytes": "578" }, { "name": "Python", "bytes": "36" }, { "name": "Ruby", "bytes": "4802" }, { "name": "Scala", "bytes": "299988" }, { "name": "Shell", "bytes": "9057" }, { "name": "Tcl", "bytes": "4974" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "284036" } ], "symlink_target": "" }
FROM ubuntu:bionic # setup timezone RUN echo 'Etc/UTC' > /etc/timezone && \ ln -s /usr/share/zoneinfo/Etc/UTC /etc/localtime && \ apt-get update && \ apt-get install -q -y --no-install-recommends tzdata && \ rm -rf /var/lib/apt/lists/* # install packages RUN apt-get update && apt-get install -q -y --no-install-recommends \ dirmngr \ gnupg2 \ lsb-release \ && rm -rf /var/lib/apt/lists/* # setup keys RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys D2486D2DD83DB69272AFE98867170598AF249743 # setup sources.list RUN . /etc/os-release \ && echo "deb http://packages.osrfoundation.org/gazebo/$ID-stable `lsb_release -sc` main" > /etc/apt/sources.list.d/gazebo-latest.list # install gazebo packages RUN apt-get update && apt-get install -y --no-install-recommends \ gazebo11=11.11.0-1* \ && rm -rf /var/lib/apt/lists/* # setup environment EXPOSE 11345 # setup entrypoint COPY ./gzserver_entrypoint.sh / ENTRYPOINT ["/gzserver_entrypoint.sh"] CMD ["gzserver"]
{ "content_hash": "402e715c92164789d9b027adcbb63698", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 137, "avg_line_length": 28.61111111111111, "alnum_prop": 0.683495145631068, "repo_name": "ruffsl/docker_images", "id": "f24cca3dfd459fa396078ee908e8cc8e7744652c", "size": "1158", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gazebo/11/ubuntu/bionic/gzserver11/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "110024" }, { "name": "EmberScript", "bytes": "81720" }, { "name": "Makefile", "bytes": "41343" }, { "name": "Python", "bytes": "21962" }, { "name": "Shell", "bytes": "7389" } ], "symlink_target": "" }
<?php error_reporting(E_STRICT | E_ALL); require_once 'Google/Api/Ads/Common/Util/DeprecationUtils.php'; /** * Unit tests for {@link DeprecationUtils}. * @group small */ class DeprecationUtilsTest extends PHPUnit_Framework_TestCase { public function testIsUsingOAuth2_UsingOAuth2() { $credentials = array('refresh_token' => 'REFRESH_TOKEN'); $mockUser = $this->getMockBuilder('AdsUser') ->disableOriginalConstructor() ->getMockForAbstractClass(); $mockUser->SetOAuth2Info($credentials); $this->assertTrue( DeprecationUtils::IsUsingOAuth2($mockUser)); } public function testIsUsingOAuth2_UsingClientLogin() { // Because AdsUser doesn't have ClientLogin information on it, we consider // the absence of OAuth 2 as using ClientLogin. $mockUser = $this->getMockBuilder('AdsUser') ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->assertFalse( DeprecationUtils::IsUsingOAuth2($mockUser)); } public function testCheckUsingClientLoginWithUnsupportedVersion_UsingClientLoginSupportedVersion() { // Because AdsUser doesn't have ClientLogin information on it, we consider // the absence of OAuth 2 as using ClientLogin. $mockUser = $this->getMockBuilder('AdsUser') ->disableOriginalConstructor() ->getMockForAbstractClass(); DeprecationUtils::CheckUsingClientLoginWithUnsupportedVersion($mockUser, "v201311", "v201208"); DeprecationUtils::CheckUsingClientLoginWithUnsupportedVersion($mockUser, "v201311", "v201311"); } /** * @expectedException ServiceException */ public function testCheckUsingClientLoginWithUnsupportedVersion_UsingClientLoginUnsupportedVersion() { // Because AdsUser doesn't have ClientLogin information on it, we consider // the absence of OAuth 2 as using ClientLogin. $mockUser = $this->getMockBuilder('AdsUser') ->disableOriginalConstructor() ->getMockForAbstractClass(); DeprecationUtils::CheckUsingClientLoginWithUnsupportedVersion($mockUser, "v201311", "v201403"); } public function testCheckUsingClientLoginWithUnsupportedVersion_UsingOAuth2WithAnyVersion() { $credentials = array('refresh_token' => 'REFRESH_TOKEN'); $mockUser = $this->getMockBuilder('AdsUser') ->disableOriginalConstructor() ->getMockForAbstractClass(); $mockUser->SetOAuth2Info($credentials); DeprecationUtils::CheckUsingClientLoginWithUnsupportedVersion($mockUser, "v201311", "v201208"); DeprecationUtils::CheckUsingClientLoginWithUnsupportedVersion($mockUser, "v201311", "v201311"); DeprecationUtils::CheckUsingClientLoginWithUnsupportedVersion($mockUser, "v201311", "v201403"); } }
{ "content_hash": "976acac0a78af9722c347832646f63fb", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 92, "avg_line_length": 34.85, "alnum_prop": 0.7191535150645624, "repo_name": "cornernote/googleads-php-lib", "id": "0e415af5e8af4ceb406c285902d83e0d6a0d1c7d", "size": "3701", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Google/Api/Ads/Common/Util/DeprecationUtilsTest.php", "mode": "33261", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace FishDiary\Model\Table; use Cake\ORM\Query; use Cake\ORM\RulesChecker; use Cake\ORM\Table; use Cake\Validation\Validator; /** * FishingPlaces Model * * @property \Cake\ORM\Association\HasMany $CaughtFishes * * @method \FishDiary\Model\Entity\FishingPlace get($primaryKey, $options = []) * @method \FishDiary\Model\Entity\FishingPlace newEntity($data = null, array $options = []) * @method \FishDiary\Model\Entity\FishingPlace[] newEntities(array $data, array $options = []) * @method \FishDiary\Model\Entity\FishingPlace|bool save(\Cake\Datasource\EntityInterface $entity, $options = []) * @method \FishDiary\Model\Entity\FishingPlace patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = []) * @method \FishDiary\Model\Entity\FishingPlace[] patchEntities($entities, array $data, array $options = []) * @method \FishDiary\Model\Entity\FishingPlace findOrCreate($search, callable $callback = null, $options = []) * * @mixin \Cake\ORM\Behavior\TimestampBehavior */ class FishingPlacesTable extends Table { /** * Initialize method * * @param array $config The configuration for the Table. * @return void */ public function initialize(array $config) { parent::initialize($config); $this->setTable('fishing_places'); $this->setDisplayField('name'); $this->setPrimaryKey('id'); $this->addBehavior('Timestamp'); $this->hasMany('CaughtFishes', [ 'foreignKey' => 'fishing_place_id' ]); } /** * Default validation rules. * * @param \Cake\Validation\Validator $validator Validator instance. * @return \Cake\Validation\Validator */ public function validationDefault(Validator $validator) { $validator ->integer('id') ->allowEmpty('id', 'create'); $validator ->requirePresence('name', 'create') ->notEmpty('name'); return $validator; } }
{ "content_hash": "4f70961231a8250614f7cdd5578e3f19", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 135, "avg_line_length": 30.53030303030303, "alnum_prop": 0.6501240694789082, "repo_name": "makallio85/fish-diary", "id": "39fd6b6f7a7106af7cdeba8f163798691dac8b95", "size": "2015", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Model/Table/FishingPlacesTable.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "834" }, { "name": "CSS", "bytes": "12827" }, { "name": "JavaScript", "bytes": "215256" }, { "name": "PHP", "bytes": "291927" }, { "name": "Shell", "bytes": "1457" } ], "symlink_target": "" }
<!-- @license Copyright (c) 2017 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt --> <link rel="import" href="../../polymer-element.html"> <link rel="import" href="../utils/templatize.html"> <link rel="import" href="../utils/debounce.html"> <link rel="import" href="../utils/flush.html"> <link rel="import" href="../mixins/mutable-data.html"> <script> (function() { 'use strict'; let TemplateInstanceBase = Polymer.TemplateInstanceBase; // eslint-disable-line /** * @constructor * @implements {Polymer_OptionalMutableData} * @extends {Polymer.Element} * @private */ const domRepeatBase = Polymer.OptionalMutableData(Polymer.Element); /** * The `<dom-repeat>` element will automatically stamp and binds one instance * of template content to each object in a user-provided array. * `dom-repeat` accepts an `items` property, and one instance of the template * is stamped for each item into the DOM at the location of the `dom-repeat` * element. The `item` property will be set on each instance's binding * scope, thus templates should bind to sub-properties of `item`. * * Example: * * ```html * <dom-module id="employee-list"> * * <template> * * <div> Employee list: </div> * <dom-repeat items="{{employees}}"> * <template> * <div>First name: <span>{{item.first}}</span></div> * <div>Last name: <span>{{item.last}}</span></div> * </template> * </dom-repeat> * * </template> * * </dom-module> * ``` * * With the following custom element definition: * * ```js * class EmployeeList extends Polymer.Element { * static get is() { return 'employee-list'; } * static get properties() { * return { * employees: { * value() { * return [ * {first: 'Bob', last: 'Smith'}, * {first: 'Sally', last: 'Johnson'}, * ... * ]; * } * } * }; * } * } * ``` * * Notifications for changes to items sub-properties will be forwarded to template * instances, which will update via the normal structured data notification system. * * Mutations to the `items` array itself should be made using the Array * mutation API's on `Polymer.Base` (`push`, `pop`, `splice`, `shift`, * `unshift`), and template instances will be kept in sync with the data in the * array. * * Events caught by event handlers within the `dom-repeat` template will be * decorated with a `model` property, which represents the binding scope for * each template instance. The model is an instance of Polymer.Base, and should * be used to manipulate data on the instance, for example * `event.model.set('item.checked', true);`. * * Alternatively, the model for a template instance for an element stamped by * a `dom-repeat` can be obtained using the `modelForElement` API on the * `dom-repeat` that stamped it, for example * `this.$.domRepeat.modelForElement(event.target).set('item.checked', true);`. * This may be useful for manipulating instance data of event targets obtained * by event handlers on parents of the `dom-repeat` (event delegation). * * A view-specific filter/sort may be applied to each `dom-repeat` by supplying a * `filter` and/or `sort` property. This may be a string that names a function on * the host, or a function may be assigned to the property directly. The functions * should implemented following the standard `Array` filter/sort API. * * In order to re-run the filter or sort functions based on changes to sub-fields * of `items`, the `observe` property may be set as a space-separated list of * `item` sub-fields that should cause a re-filter/sort when modified. If * the filter or sort function depends on properties not contained in `items`, * the user should observe changes to those properties and call `render` to update * the view based on the dependency change. * * For example, for an `dom-repeat` with a filter of the following: * * ```js * isEngineer(item) { * return item.type == 'engineer' || item.manager.type == 'engineer'; * } * ``` * * Then the `observe` property should be configured as follows: * * ```html * <dom-repeat items="{{employees}}" filter="isEngineer" observe="type manager.type"> * ``` * * @customElement * @polymer * @memberof Polymer * @extends {domRepeatBase} * @appliesMixin Polymer.OptionalMutableData * @summary Custom element for stamping instance of a template bound to * items in an array. */ class DomRepeat extends domRepeatBase { // Not needed to find template; can be removed once the analyzer // can find the tag name from customElements.define call static get is() { return 'dom-repeat'; } static get template() { return null; } static get properties() { /** * Fired whenever DOM is added or removed by this template (by * default, rendering occurs lazily). To force immediate rendering, call * `render`. * * @event dom-change */ return { /** * An array containing items determining how many instances of the template * to stamp and that that each template instance should bind to. */ items: { type: Array }, /** * The name of the variable to add to the binding scope for the array * element associated with a given template instance. */ as: { type: String, value: 'item' }, /** * The name of the variable to add to the binding scope with the index * of the instance in the sorted and filtered list of rendered items. * Note, for the index in the `this.items` array, use the value of the * `itemsIndexAs` property. */ indexAs: { type: String, value: 'index' }, /** * The name of the variable to add to the binding scope with the index * of the instance in the `this.items` array. Note, for the index of * this instance in the sorted and filtered list of rendered items, * use the value of the `indexAs` property. */ itemsIndexAs: { type: String, value: 'itemsIndex' }, /** * A function that should determine the sort order of the items. This * property should either be provided as a string, indicating a method * name on the element's host, or else be an actual function. The * function should match the sort function passed to `Array.sort`. * Using a sort function has no effect on the underlying `items` array. */ sort: { type: Function, observer: '__sortChanged' }, /** * A function that can be used to filter items out of the view. This * property should either be provided as a string, indicating a method * name on the element's host, or else be an actual function. The * function should match the sort function passed to `Array.filter`. * Using a filter function has no effect on the underlying `items` array. */ filter: { type: Function, observer: '__filterChanged' }, /** * When using a `filter` or `sort` function, the `observe` property * should be set to a space-separated list of the names of item * sub-fields that should trigger a re-sort or re-filter when changed. * These should generally be fields of `item` that the sort or filter * function depends on. */ observe: { type: String, observer: '__observeChanged' }, /** * When using a `filter` or `sort` function, the `delay` property * determines a debounce time in ms after a change to observed item * properties that must pass before the filter or sort is re-run. * This is useful in rate-limiting shuffling of the view when * item changes may be frequent. */ delay: Number, /** * Count of currently rendered items after `filter` (if any) has been applied. * If "chunking mode" is enabled, `renderedItemCount` is updated each time a * set of template instances is rendered. * */ renderedItemCount: { type: Number, notify: true, readOnly: true }, /** * Defines an initial count of template instances to render after setting * the `items` array, before the next paint, and puts the `dom-repeat` * into "chunking mode". The remaining items will be created and rendered * incrementally at each animation frame therof until all instances have * been rendered. */ initialCount: { type: Number, observer: '__initializeChunking' }, /** * When `initialCount` is used, this property defines a frame rate (in * fps) to target by throttling the number of instances rendered each * frame to not exceed the budget for the target frame rate. The * framerate is effectively the number of `requestAnimationFrame`s that * it tries to allow to actually fire in a given second. It does this * by measuring the time between `rAF`s and continuously adjusting the * number of items created each `rAF` to maintain the target framerate. * Setting this to a higher number allows lower latency and higher * throughput for event handlers and other tasks, but results in a * longer time for the remaining items to complete rendering. */ targetFramerate: { type: Number, value: 20 }, _targetFrameTime: { type: Number, computed: '__computeFrameTime(targetFramerate)' } }; } static get observers() { return [ '__itemsChanged(items.*)' ]; } constructor() { super(); this.__instances = []; this.__limit = Infinity; this.__pool = []; this.__renderDebouncer = null; this.__itemsIdxToInstIdx = {}; this.__chunkCount = null; this.__lastChunkTime = null; this.__sortFn = null; this.__filterFn = null; this.__observePaths = null; this.__ctor = null; this.__isDetached = true; this.template = null; } /** * @return {void} */ disconnectedCallback() { super.disconnectedCallback(); this.__isDetached = true; for (let i=0; i<this.__instances.length; i++) { this.__detachInstance(i); } } /** * @return {void} */ connectedCallback() { super.connectedCallback(); this.style.display = 'none'; // only perform attachment if the element was previously detached. if (this.__isDetached) { this.__isDetached = false; let parent = this.parentNode; for (let i=0; i<this.__instances.length; i++) { this.__attachInstance(i, parent); } } } __ensureTemplatized() { // Templatizing (generating the instance constructor) needs to wait // until ready, since won't have its template content handed back to // it until then if (!this.__ctor) { let template = this.template = /** @type {HTMLTemplateElement} */(this.querySelector('template')); if (!template) { // // Wait until childList changes and template should be there by then let observer = new MutationObserver(() => { if (this.querySelector('template')) { observer.disconnect(); this.__render(); } else { throw new Error('dom-repeat requires a <template> child'); } }); observer.observe(this, {childList: true}); return false; } // Template instance props that should be excluded from forwarding let instanceProps = {}; instanceProps[this.as] = true; instanceProps[this.indexAs] = true; instanceProps[this.itemsIndexAs] = true; this.__ctor = Polymer.Templatize.templatize(template, this, { mutableData: this.mutableData, parentModel: true, instanceProps: instanceProps, /** * @this {this} * @param {string} prop Property to set * @param {*} value Value to set property to */ forwardHostProp: function(prop, value) { let i$ = this.__instances; for (let i=0, inst; (i<i$.length) && (inst=i$[i]); i++) { inst.forwardHostProp(prop, value); } }, /** * @this {this} * @param {Object} inst Instance to notify * @param {string} prop Property to notify * @param {*} value Value to notify */ notifyInstanceProp: function(inst, prop, value) { if (Polymer.Path.matches(this.as, prop)) { let idx = inst[this.itemsIndexAs]; if (prop == this.as) { this.items[idx] = value; } let path = Polymer.Path.translate(this.as, 'items.' + idx, prop); this.notifyPath(path, value); } } }); } return true; } __getMethodHost() { // Technically this should be the owner of the outermost template. // In shadow dom, this is always getRootNode().host, but we can // approximate this via cooperation with our dataHost always setting // `_methodHost` as long as there were bindings (or id's) on this // instance causing it to get a dataHost. return this.__dataHost._methodHost || this.__dataHost; } __functionFromPropertyValue(functionOrMethodName) { if (typeof functionOrMethodName === 'string') { let methodName = functionOrMethodName; let obj = this.__getMethodHost(); return function() { return obj[methodName].apply(obj, arguments); }; } return functionOrMethodName; } __sortChanged(sort) { this.__sortFn = this.__functionFromPropertyValue(sort); if (this.items) { this.__debounceRender(this.__render); } } __filterChanged(filter) { this.__filterFn = this.__functionFromPropertyValue(filter); if (this.items) { this.__debounceRender(this.__render); } } __computeFrameTime(rate) { return Math.ceil(1000/rate); } __initializeChunking() { if (this.initialCount) { this.__limit = this.initialCount; this.__chunkCount = this.initialCount; this.__lastChunkTime = performance.now(); } } __tryRenderChunk() { // Debounced so that multiple calls through `_render` between animation // frames only queue one new rAF (e.g. array mutation & chunked render) if (this.items && this.__limit < this.items.length) { this.__debounceRender(this.__requestRenderChunk); } } __requestRenderChunk() { requestAnimationFrame(()=>this.__renderChunk()); } __renderChunk() { // Simple auto chunkSize throttling algorithm based on feedback loop: // measure actual time between frames and scale chunk count by ratio // of target/actual frame time let currChunkTime = performance.now(); let ratio = this._targetFrameTime / (currChunkTime - this.__lastChunkTime); this.__chunkCount = Math.round(this.__chunkCount * ratio) || 1; this.__limit += this.__chunkCount; this.__lastChunkTime = currChunkTime; this.__debounceRender(this.__render); } __observeChanged() { this.__observePaths = this.observe && this.observe.replace('.*', '.').split(' '); } __itemsChanged(change) { if (this.items && !Array.isArray(this.items)) { console.warn('dom-repeat expected array for `items`, found', this.items); } // If path was to an item (e.g. 'items.3' or 'items.3.foo'), forward the // path to that instance synchronously (returns false for non-item paths) if (!this.__handleItemPath(change.path, change.value)) { // Otherwise, the array was reset ('items') or spliced ('items.splices'), // so queue a full refresh this.__initializeChunking(); this.__debounceRender(this.__render); } } __handleObservedPaths(path) { // Handle cases where path changes should cause a re-sort/filter if (this.__sortFn || this.__filterFn) { if (!path) { // Always re-render if the item itself changed this.__debounceRender(this.__render, this.delay); } else if (this.__observePaths) { // Otherwise, re-render if the path changed matches an observed path let paths = this.__observePaths; for (let i=0; i<paths.length; i++) { if (path.indexOf(paths[i]) === 0) { this.__debounceRender(this.__render, this.delay); } } } } } /** * @param {function(this:DomRepeat)} fn Function to debounce. * @param {number=} delay Delay in ms to debounce by. */ __debounceRender(fn, delay = 0) { this.__renderDebouncer = Polymer.Debouncer.debounce( this.__renderDebouncer , delay > 0 ? Polymer.Async.timeOut.after(delay) : Polymer.Async.microTask , fn.bind(this)); Polymer.enqueueDebouncer(this.__renderDebouncer); } /** * Forces the element to render its content. Normally rendering is * asynchronous to a provoking change. This is done for efficiency so * that multiple changes trigger only a single render. The render method * should be called if, for example, template rendering is required to * validate application state. * @return {void} */ render() { // Queue this repeater, then flush all in order this.__debounceRender(this.__render); Polymer.flush(); } __render() { if (!this.__ensureTemplatized()) { // No template found yet return; } this.__applyFullRefresh(); // Reset the pool // TODO(kschaaf): Reuse pool across turns and nested templates // Now that objects/arrays are re-evaluated when set, we can safely // reuse pooled instances across turns, however we still need to decide // semantics regarding how long to hold, how many to hold, etc. this.__pool.length = 0; // Set rendered item count this._setRenderedItemCount(this.__instances.length); // Notify users this.dispatchEvent(new CustomEvent('dom-change', { bubbles: true, composed: true })); // Check to see if we need to render more items this.__tryRenderChunk(); } __applyFullRefresh() { let items = this.items || []; let isntIdxToItemsIdx = new Array(items.length); for (let i=0; i<items.length; i++) { isntIdxToItemsIdx[i] = i; } // Apply user filter if (this.__filterFn) { isntIdxToItemsIdx = isntIdxToItemsIdx.filter((i, idx, array) => this.__filterFn(items[i], idx, array)); } // Apply user sort if (this.__sortFn) { isntIdxToItemsIdx.sort((a, b) => this.__sortFn(items[a], items[b])); } // items->inst map kept for item path forwarding const itemsIdxToInstIdx = this.__itemsIdxToInstIdx = {}; let instIdx = 0; // Generate instances and assign items const limit = Math.min(isntIdxToItemsIdx.length, this.__limit); for (; instIdx<limit; instIdx++) { let inst = this.__instances[instIdx]; let itemIdx = isntIdxToItemsIdx[instIdx]; let item = items[itemIdx]; itemsIdxToInstIdx[itemIdx] = instIdx; if (inst) { inst._setPendingProperty(this.as, item); inst._setPendingProperty(this.indexAs, instIdx); inst._setPendingProperty(this.itemsIndexAs, itemIdx); inst._flushProperties(); } else { this.__insertInstance(item, instIdx, itemIdx); } } // Remove any extra instances from previous state for (let i=this.__instances.length-1; i>=instIdx; i--) { this.__detachAndRemoveInstance(i); } } __detachInstance(idx) { let inst = this.__instances[idx]; for (let i=0; i<inst.children.length; i++) { let el = inst.children[i]; inst.root.appendChild(el); } return inst; } __attachInstance(idx, parent) { let inst = this.__instances[idx]; parent.insertBefore(inst.root, this); } __detachAndRemoveInstance(idx) { let inst = this.__detachInstance(idx); if (inst) { this.__pool.push(inst); } this.__instances.splice(idx, 1); } __stampInstance(item, instIdx, itemIdx) { let model = {}; model[this.as] = item; model[this.indexAs] = instIdx; model[this.itemsIndexAs] = itemIdx; return new this.__ctor(model); } __insertInstance(item, instIdx, itemIdx) { let inst = this.__pool.pop(); if (inst) { // TODO(kschaaf): If the pool is shared across turns, hostProps // need to be re-set to reused instances in addition to item inst._setPendingProperty(this.as, item); inst._setPendingProperty(this.indexAs, instIdx); inst._setPendingProperty(this.itemsIndexAs, itemIdx); inst._flushProperties(); } else { inst = this.__stampInstance(item, instIdx, itemIdx); } let beforeRow = this.__instances[instIdx + 1]; let beforeNode = beforeRow ? beforeRow.children[0] : this; this.parentNode.insertBefore(inst.root, beforeNode); this.__instances[instIdx] = inst; return inst; } // Implements extension point from Templatize mixin /** * Shows or hides the template instance top level child elements. For * text nodes, `textContent` is removed while "hidden" and replaced when * "shown." * @param {boolean} hidden Set to true to hide the children; * set to false to show them. * @return {void} * @protected */ _showHideChildren(hidden) { for (let i=0; i<this.__instances.length; i++) { this.__instances[i]._showHideChildren(hidden); } } // Called as a side effect of a host items.<key>.<path> path change, // responsible for notifying item.<path> changes to inst for key __handleItemPath(path, value) { let itemsPath = path.slice(6); // 'items.'.length == 6 let dot = itemsPath.indexOf('.'); let itemsIdx = dot < 0 ? itemsPath : itemsPath.substring(0, dot); // If path was index into array... if (itemsIdx == parseInt(itemsIdx, 10)) { let itemSubPath = dot < 0 ? '' : itemsPath.substring(dot+1); // If the path is observed, it will trigger a full refresh this.__handleObservedPaths(itemSubPath); // Note, even if a rull refresh is triggered, always do the path // notification because unless mutableData is used for dom-repeat // and all elements in the instance subtree, a full refresh may // not trigger the proper update. let instIdx = this.__itemsIdxToInstIdx[itemsIdx]; let inst = this.__instances[instIdx]; if (inst) { let itemPath = this.as + (itemSubPath ? '.' + itemSubPath : ''); // This is effectively `notifyPath`, but avoids some of the overhead // of the public API inst._setPendingPropertyOrPath(itemPath, value, false, true); inst._flushProperties(); } return true; } } /** * Returns the item associated with a given element stamped by * this `dom-repeat`. * * Note, to modify sub-properties of the item, * `modelForElement(el).set('item.<sub-prop>', value)` * should be used. * * @param {!HTMLElement} el Element for which to return the item. * @return {*} Item associated with the element. */ itemForElement(el) { let instance = this.modelForElement(el); return instance && instance[this.as]; } /** * Returns the inst index for a given element stamped by this `dom-repeat`. * If `sort` is provided, the index will reflect the sorted order (rather * than the original array order). * * @param {!HTMLElement} el Element for which to return the index. * @return {?number} Row index associated with the element (note this may * not correspond to the array index if a user `sort` is applied). */ indexForElement(el) { let instance = this.modelForElement(el); return instance && instance[this.indexAs]; } /** * Returns the template "model" associated with a given element, which * serves as the binding scope for the template instance the element is * contained in. A template model is an instance of `Polymer.Base`, and * should be used to manipulate data associated with this template instance. * * Example: * * let model = modelForElement(el); * if (model.index < 10) { * model.set('item.checked', true); * } * * @param {!HTMLElement} el Element for which to return a template model. * @return {TemplateInstanceBase} Model representing the binding scope for * the element. */ modelForElement(el) { return Polymer.Templatize.modelForElement(this.template, el); } } customElements.define(DomRepeat.is, DomRepeat); /** @const */ Polymer.DomRepeat = DomRepeat; })(); </script>
{ "content_hash": "f709fd0564566ed95b2fb2fa2d6288b0", "timestamp": "", "source": "github", "line_count": 740, "max_line_length": 106, "avg_line_length": 35.76756756756757, "alnum_prop": 0.60121656339731, "repo_name": "Polymer/tools", "id": "23f78752680309cbd03e47908f3b7680e3b78c84", "size": "26468", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "packages/modulizer/fixtures/packages/polymer/source/lib/elements/dom-repeat.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "7605" }, { "name": "HTML", "bytes": "3110999" }, { "name": "JavaScript", "bytes": "903683" }, { "name": "Shell", "bytes": "6045" }, { "name": "TypeScript", "bytes": "3330477" } ], "symlink_target": "" }
using System.Collections.Generic; using Cake.Core.IO; namespace Cake.Common.Tools.DotNetCore.Build { /// <summary> /// Contains settings used by <see cref="DotNetCoreBuilder" />. /// </summary> public sealed class DotNetCoreBuildSettings : DotNetCoreSettings { /// <summary> /// Gets or sets the directory in which to place temporary outputs. /// </summary> public DirectoryPath BuildBasePath { get; set; } /// <summary> /// Gets or sets the output directory. /// </summary> public DirectoryPath OutputDirectory { get; set; } /// <summary> /// Gets or sets the target runtime. /// </summary> public string Runtime { get; set; } /// <summary> /// Gets or sets the configuration under which to build. /// </summary> public string Configuration { get; set; } /// <summary> /// Gets or sets specific frameworks to compile. /// </summary> public ICollection<string> Frameworks { get; set; } /// <summary> /// Gets or sets the value that defines what `*` should be replaced with in version field in project.json. /// </summary> public string VersionSuffix { get; set; } /// <summary> /// Gets or sets a value indicating whether to print the incremental safety checks that prevent incremental compilation. /// </summary> public bool BuildProfile { get; set; } /// <summary> /// Gets or sets a value indicating whether to mark the build as unsafe for incrementality. /// This turns off incremental compilation and forces a clean rebuild of the project dependency graph. /// </summary> public bool NoIncremental { get; set; } /// <summary> /// Gets or sets a value indicating whether to ignore project to project references and only build the root project. /// </summary> public bool NoDependencies { get; set; } } }
{ "content_hash": "3efa145bdcec345556156f78c6168347", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 128, "avg_line_length": 35.75438596491228, "alnum_prop": 0.6040235525024534, "repo_name": "SharpeRAD/Cake", "id": "158976d7b4864f1a7c6f525105eaacad0a493313", "size": "2040", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/Cake.Common/Tools/DotNetCore/Build/DotNetCoreBuildSettings.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "3026190" }, { "name": "PowerShell", "bytes": "1772" }, { "name": "Shell", "bytes": "2240" } ], "symlink_target": "" }
package com.amazonaws.services.servicecatalog.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.servicecatalog.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * FailedServiceActionAssociation JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class FailedServiceActionAssociationJsonUnmarshaller implements Unmarshaller<FailedServiceActionAssociation, JsonUnmarshallerContext> { public FailedServiceActionAssociation unmarshall(JsonUnmarshallerContext context) throws Exception { FailedServiceActionAssociation failedServiceActionAssociation = new FailedServiceActionAssociation(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("ServiceActionId", targetDepth)) { context.nextToken(); failedServiceActionAssociation.setServiceActionId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("ProductId", targetDepth)) { context.nextToken(); failedServiceActionAssociation.setProductId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("ProvisioningArtifactId", targetDepth)) { context.nextToken(); failedServiceActionAssociation.setProvisioningArtifactId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("ErrorCode", targetDepth)) { context.nextToken(); failedServiceActionAssociation.setErrorCode(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("ErrorMessage", targetDepth)) { context.nextToken(); failedServiceActionAssociation.setErrorMessage(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return failedServiceActionAssociation; } private static FailedServiceActionAssociationJsonUnmarshaller instance; public static FailedServiceActionAssociationJsonUnmarshaller getInstance() { if (instance == null) instance = new FailedServiceActionAssociationJsonUnmarshaller(); return instance; } }
{ "content_hash": "96411a641606621455c57f5e37fa2300", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 142, "avg_line_length": 43.24050632911393, "alnum_prop": 0.6545667447306791, "repo_name": "jentfoo/aws-sdk-java", "id": "aea64a7f5b50e2690a3a918befa021764047920a", "size": "3996", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/transform/FailedServiceActionAssociationJsonUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "270" }, { "name": "FreeMarker", "bytes": "173637" }, { "name": "Gherkin", "bytes": "25063" }, { "name": "Java", "bytes": "356214839" }, { "name": "Scilab", "bytes": "3924" }, { "name": "Shell", "bytes": "295" } ], "symlink_target": "" }
<fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:map="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/map" tools:context="com.example.kenny_liu.test.MapsActivity" android:name="com.google.android.gms.maps.SupportMapFragment" />
{ "content_hash": "21bd0dd041a466f7fadfc25f9331df92", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 91, "avg_line_length": 67.33333333333333, "alnum_prop": 0.7425742574257426, "repo_name": "sundyCoder/parapod", "id": "c55db2d6f3343c54d23d409d537ad79398e115c6", "size": "404", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/app/src/main/res/layout/activity_maps.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "487" }, { "name": "Java", "bytes": "35227" }, { "name": "Python", "bytes": "9508" } ], "symlink_target": "" }
<#include "inc/head.html"/> <div class="path"><em class="r"><img src="${contextPath}site/${site.sourcepath}/resources/images/top100.gif"/></em> <div class="path_inner">您目前的位置:<a href="${contextPath}site/${site.sourcepath}/index.html">首页</a> <@channelPath siteid="${site.id}" id="${currChannel.id}" ;channel> - <a href="${channel.pageurl}">${channel.name}</a> </ @channelPath> </div></div> <div class="category"> <h3>${currChannel.name}</h3> <div class="category_bd"> <ul> <@infoList siteid="${site.id}" channelParid="${currChannel.id}" num="100" titleLen="13"; info,index> <li><a href="${info.pageurl}" target="_blank">${info.showtitle}</a></li> </ @infoList> </ul></div> </div> <#include "inc/foot.html"/>
{ "content_hash": "727a71b8bd5a2f8e1b77fcec7be76dd0", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 115, "avg_line_length": 34.869565217391305, "alnum_prop": 0.5798004987531172, "repo_name": "tcxy/EasyCMS", "id": "da32b2d0a88c73a17e9bae44df597a55f5dc69fe", "size": "820", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "web/template/taoke/oneChannel.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "768" }, { "name": "CSS", "bytes": "658870" }, { "name": "HTML", "bytes": "2763323" }, { "name": "Java", "bytes": "1276182" }, { "name": "JavaScript", "bytes": "2338112" }, { "name": "PHP", "bytes": "2199" } ], "symlink_target": "" }
FROM balenalib/odroid-u3+-debian:bookworm-run # remove several traces of debian python RUN apt-get purge -y python.* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # install python dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates \ netbase \ && rm -rf /var/lib/apt/lists/* # key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 3.7.12 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.3.1 ENV SETUPTOOLS_VERSION 60.5.4 RUN set -x \ && buildDeps=' \ curl \ ' \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-armv7hf-libffi3.3.tar.gz" \ && echo "d8d0dd3457e8491022d8e736860f4dd747a0a8bb93a3b1319fe9d2610b0006b0 Python-$PYTHON_VERSION.linux-armv7hf-libffi3.3.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-armv7hf-libffi3.3.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-armv7hf-libffi3.3.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config # set PYTHONPATH to point to dist-packages ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \ && echo "Running test-stack@python" \ && chmod +x test-stack@python.sh \ && bash test-stack@python.sh \ && rm -rf test-stack@python.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Bookworm \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.7.12, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "dc6affed28ee5aac98d9e06d01c8b68f", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 711, "avg_line_length": 52.23076923076923, "alnum_prop": 0.7074128620520374, "repo_name": "resin-io-library/base-images", "id": "0d230c1b748fb9cbaecac84521452e707c5bab9a", "size": "4095", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/python/odroid-u3+/debian/bookworm/3.7.12/run/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "71234697" }, { "name": "JavaScript", "bytes": "13096" }, { "name": "Shell", "bytes": "12051936" }, { "name": "Smarty", "bytes": "59789" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_67) on Thu Feb 04 13:28:40 CST 2016 --> <title>AppMasterToExecutor$</title> <meta name="date" content="2016-02-04"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="AppMasterToExecutor$"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../io/gearpump/streaming/AppMasterToExecutor.TasksLaunched$.html" title="class in io.gearpump.streaming"><span class="strong">Prev Class</span></a></li> <li><a href="../../../io/gearpump/streaming/AppMasterToMaster.html" title="class in io.gearpump.streaming"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?io/gearpump/streaming/AppMasterToExecutor$.html" target="_top">Frames</a></li> <li><a href="AppMasterToExecutor$.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">io.gearpump.streaming</div> <h2 title="Class AppMasterToExecutor$" class="title">Class AppMasterToExecutor$</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>io.gearpump.streaming.AppMasterToExecutor$</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="strong">AppMasterToExecutor$</span> extends java.lang.Object</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../io/gearpump/streaming/AppMasterToExecutor$.html" title="class in io.gearpump.streaming">AppMasterToExecutor$</a></code></td> <td class="colLast"><code><strong><a href="../../../io/gearpump/streaming/AppMasterToExecutor$.html#MODULE$">MODULE$</a></strong></code> <div class="block">Static reference to the singleton instance of this Scala object.</div> </td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../io/gearpump/streaming/AppMasterToExecutor$.html#AppMasterToExecutor$()">AppMasterToExecutor$</a></strong>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field_detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="MODULE$"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>MODULE$</h4> <pre>public static final&nbsp;<a href="../../../io/gearpump/streaming/AppMasterToExecutor$.html" title="class in io.gearpump.streaming">AppMasterToExecutor$</a> MODULE$</pre> <div class="block">Static reference to the singleton instance of this Scala object.</div> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="AppMasterToExecutor$()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>AppMasterToExecutor$</h4> <pre>public&nbsp;AppMasterToExecutor$()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../io/gearpump/streaming/AppMasterToExecutor.TasksLaunched$.html" title="class in io.gearpump.streaming"><span class="strong">Prev Class</span></a></li> <li><a href="../../../io/gearpump/streaming/AppMasterToMaster.html" title="class in io.gearpump.streaming"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?io/gearpump/streaming/AppMasterToExecutor$.html" target="_top">Frames</a></li> <li><a href="AppMasterToExecutor$.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "490693969d32a8d7b2e2f7ae4aea3b23", "timestamp": "", "source": "github", "line_count": 265, "max_line_length": 176, "avg_line_length": 33.54716981132076, "alnum_prop": 0.6388076490438696, "repo_name": "stanleyxu2005/gearpump.github.io", "id": "c9d7dd86c26dff82528c12741f7f4ff246735721", "size": "8890", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "releases/0.7.6/api/java/io/gearpump/streaming/AppMasterToExecutor$.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "386903" }, { "name": "HTML", "bytes": "236673589" }, { "name": "JavaScript", "bytes": "2196377" }, { "name": "Shell", "bytes": "213" } ], "symlink_target": "" }
from helper import greeting def joint_greeting(msg1, msg2): greeting(msg1) greeting(msg2)
{ "content_hash": "76ce9f423de858d14f67934ba4363d47", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 31, "avg_line_length": 18.4, "alnum_prop": 0.782608695652174, "repo_name": "sdgennari/cs3240-labdemo", "id": "7577bd4255c44fa4096dbe9afe396eccb3457436", "size": "92", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "new_file.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "343" } ], "symlink_target": "" }
The Kinesis Streams appender is intended to be an entry point for log analytics, either as a direct feed to an analytics application, or via Kinesis Firehose to ElasticSearch or other destinations (which is also an easy way to back-up logs to S3). The Kinesis appender provides the following features: * Configurable destination stream, with substitution variables to specify stream name. * Auto-creation of streams, with configurable number of shards and retention period. * JSON messages (via [JsonLayout](jsonlayout.md)). * Configurable discard in case of network connectivity issues. ## Configuration This appender provides the following configuration properties, along with the common [connection properties](client.md#configuration-properties). Name | Description ----------------------------|---------------------------------------------------------------- `streamName` | The name of the Kinesis stream that will receive messages; may use [substitutions](substitutions.md). No default value. `partitionKey` | A string used to assign messages to shards; see below for more information. `autoCreate` | If present and "true", the stream will be created if it does not already exist. `shardCount` | When creating a stream, specifies the number of shards to use. Defaults to 1. `retentionPeriod` | When creating a stream, specifies the retention period for messages in hours. Range is 24 to 8760; default is 24. `synchronous` | If `true`, the appender will operate in [synchronous mode](design.md#synchronous-mode), sending messages from the invoking thread on every call to `append()`. `batchDelay` | The time, in milliseconds, that the writer will wait to accumulate messages for a batch. See the [design doc](design.md#message-batches) for more information. `truncateOversizeMessages` | If `true` (the default), truncate any messages that are too large for Kinesis; if `false`, discard them. See [below](#oversize-messages) for more information. `discardThreshold` | The maximum number of messages that can remain queued before they're discarded; default is 10,000. See the [design doc](design.md#message-discard) for more information. `discardAction` | Which messages will be discarded once the threshold is passed: `oldest` (the default), `newest`, or `none`. `useShutdownHook` | Controls whether the appender uses a shutdown hook to attempt to process outstanding messages when the JVM exits. This is `true` by default; set to `false` to disable. Ignored for Log4J2, which has its own shutdown hook. See [docs](design.md#shutdown) for more information. `initializationTimeout` | The number of milliseconds to wait for initialization; default is 120000 (120 seconds). See [docs](design.md#initialization) for more information. ### Example: Log4J 1.x ``` log4j.appender.kinesis=com.kdgregory.log4j.aws.KinesisAppender log4j.appender.kinesis.streamName=logging-stream log4j.appender.kinesis.partitionKey={pid} log4j.appender.kinesis.batchDelay=500 log4j.appender.kinesis.layout=com.kdgregory.log4j.aws.JsonLayout log4j.appender.kinesis.layout.enableHostname=true log4j.appender.kinesis.layout.enableLocation=true log4j.appender.kinesis.layout.tags=applicationName={env:APP_NAME},deployment={sysprop:deployment:dev} ``` ### Example: Log4J2 Note that this example uses Log4J [lookups](https://logging.apache.org/log4j/2.x/manual/lookups.html#EnvironmentLookup) in addition to library-provided substitutions. It also uses the Log4J [JsonLayout](https://logging.apache.org/log4j/2.x/manual/layouts.html#JSONLayout) with additional fields, including a `timestamp` field that's compatible with the Log4J1 and Logback `JsonLayout` implementations. ``` <KinesisAppender name="KINESIS"> <streamName>logging-stream</streamName> <partitionKey>{pid}</partitionKey> <batchDelay>500</batchDelay> <JsonLayout complete="false" compact="true" eventEol="true" properties="true" locationInfo="true"> <KeyValuePair key="applicationName" value="${env:APP_NAME}" /> <KeyValuePair key="environment" value="${sys:deployment:-dev}" /> <KeyValuePair key="processId" value="${awslogs:pid}" /> <KeyValuePair key="hostname" value="${awslogs:hostname}" /> <KeyValuePair key="timestamp" value="$${date:yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}" /> </JsonLayout> </KinesisAppender> ``` ### Example: Logback ``` <appender name="KINESIS" class="com.kdgregory.logback.aws.KinesisAppender"> <streamName>logging-stream</streamName> <partitionKey>{pid}</partitionKey> <batchDelay>500</batchDelay> <layout class="com.kdgregory.logback.aws.JsonLayout"> <enableHostname>true</enableHostname> <enableLocation>true</enableLocation> <tags>applicationName={env:APP_NAME},deployment={sysprop:deployment:dev}</tags> </layout> </appender> ``` ## Permissions To use this appender you need following IAM permissions: * `kinesis:DescribeStreamSummary` * `kinesis:PutRecords` To auto-create a stream you need these additional permissions: * `kinesis:CreateStream` * `kinesis:IncreaseStreamRetentionPeriod` ## Stream management You will normally pre-create the Kinesis stream and adjust its retention period and number of shards based on your deployment's needs. To support testing (and because it was the original behavior, copied from the CloudWatch appender), you can optionally configure the appender to create the stream if it does not already exist. Unlike the CloudWatch appender, if you delete the stream during use it will not be re-created even if you enable this parameter. ## Partition Keys Kinesis supports high-performance parallel writes via multiple shards per stream: each shard can accept up to 1,000 records and/or 1 MB of data per second. To distribute data between shards, Kinesis requires each record to have a partition key, and hashes that partition key to determine which shard is used to store the record. The Kinesis appender can be configured with an explicit partition key, which is applied to all messages generated by that appender. It can also be configured with a "random" parttion key, to distribute messages to all available shared. > The current implementation generates a six-digit numeric partition key. However, this behavior is an implementation detail and is subject to change in future releases. Example configuration, explicit partition key (you could also use substitutions in this name): ``` log4j.appender.kinesis.partitionKey=MyApplication ``` Example configuration, random partition keys: ``` log4j.appender.kinesis.partitionKey={random} ``` Note: `{random}` is a special keyword, not a substitution value. Substitutions are applied when the appender is created, not on a per-message basis. ## Retention Period By default, a Kinesis stream retains messages for 24 hours. For an extra charge, you can retain messages for up to 8760 hours (365 days). Prior to November 2020, this was 168 hours (7 days). ## Oversize Messages Kinesis has a maximum message size of 1,048,576 bytes minus the length of the partion key ([doc](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecordsRequestEntry.html)). While most logged messages won't exceed this limit, some (in particular, Spring exception traces) might. How the appender handles this depends on the `truncateOversizeMessages` configuration setting: * If `true` (the default), the message is truncated to the maximum allowed size. This is appropriate for simple text messages, as it preserves as much information as possible. However, it will corrupt messages formatted using JSON. * If `false`, the message is discarded. In either case, the oversize message is logged in the framework's internal status logger. The number of oversize messages is available through the JMX `oversizeMessages` attribute.
{ "content_hash": "5f90f6d6ee4e4d8935dd34ff8cfebd6b", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 303, "avg_line_length": 49.45962732919255, "alnum_prop": 0.7519778977772197, "repo_name": "kdgregory/log4j-aws-appenders", "id": "c885ac954d93f76d4b8fa8bb3a7cd8b5a4d8c5a6", "size": "7983", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "docs/kinesis.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1789845" } ], "symlink_target": "" }
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Cake.Hosts.Tests")]
{ "content_hash": "7a8e4d79d6835eee546f313e69895443", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 50, "avg_line_length": 30.333333333333332, "alnum_prop": 0.8131868131868132, "repo_name": "AMVSoftware/Cake.Hosts", "id": "c89a5faeda293113636de9c037c34c017de5b2e1", "size": "93", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Cake.Hosts/InternalVisibleTo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "35199" }, { "name": "PowerShell", "bytes": "7278" } ], "symlink_target": "" }
/** @constructor */ ScalaJS.c.scala_xml_dtd_PCDATA$ = (function() { ScalaJS.c.scala_xml_dtd_ContentModel.call(this) }); ScalaJS.c.scala_xml_dtd_PCDATA$.prototype = new ScalaJS.inheritable.scala_xml_dtd_ContentModel(); ScalaJS.c.scala_xml_dtd_PCDATA$.prototype.constructor = ScalaJS.c.scala_xml_dtd_PCDATA$; ScalaJS.c.scala_xml_dtd_PCDATA$.prototype.buildString__Lscala_collection_mutable_StringBuilder__Lscala_collection_mutable_StringBuilder = (function(sb$2) { return sb$2.append__T__Lscala_collection_mutable_StringBuilder("(#PCDATA)") }); ScalaJS.c.scala_xml_dtd_PCDATA$.prototype.productPrefix__T = (function() { return "PCDATA" }); ScalaJS.c.scala_xml_dtd_PCDATA$.prototype.productArity__I = (function() { return 0 }); ScalaJS.c.scala_xml_dtd_PCDATA$.prototype.productElement__I__O = (function(x$1) { var x1 = x$1; throw new ScalaJS.c.java_lang_IndexOutOfBoundsException().init___T(ScalaJS.objectToString(ScalaJS.bI(x$1))) }); ScalaJS.c.scala_xml_dtd_PCDATA$.prototype.productIterator__Lscala_collection_Iterator = (function() { return ScalaJS.modules.scala_runtime_ScalaRunTime().typedProductIterator__Lscala_Product__Lscala_collection_Iterator(this) }); ScalaJS.c.scala_xml_dtd_PCDATA$.prototype.canEqual__O__Z = (function(x$1) { return ScalaJS.is.scala_xml_dtd_PCDATA$(x$1) }); ScalaJS.c.scala_xml_dtd_PCDATA$.prototype.hashCode__I = (function() { return -1940668387 }); ScalaJS.c.scala_xml_dtd_PCDATA$.prototype.readResolve__p2__O = (function() { return ScalaJS.modules.scala_xml_dtd_PCDATA() }); ScalaJS.c.scala_xml_dtd_PCDATA$.prototype.init___ = (function() { ScalaJS.c.scala_xml_dtd_ContentModel.prototype.init___.call(this); ScalaJS.moduleInstances.scala_xml_dtd_PCDATA = this; ScalaJS.impls.scala_Product$class__$init$__Lscala_Product__V(this); return this }); ScalaJS.c.scala_xml_dtd_PCDATA$.prototype.canEqual__O__ = (function(x$1) { return ScalaJS.bZ(this.canEqual__O__Z(x$1)) }); ScalaJS.c.scala_xml_dtd_PCDATA$.prototype.productIterator__ = (function() { return this.productIterator__Lscala_collection_Iterator() }); ScalaJS.c.scala_xml_dtd_PCDATA$.prototype.productElement__I__ = (function(x$1$2) { return this.productElement__I__O(x$1$2) }); ScalaJS.c.scala_xml_dtd_PCDATA$.prototype.productArity__ = (function() { return ScalaJS.bI(this.productArity__I()) }); ScalaJS.c.scala_xml_dtd_PCDATA$.prototype.productPrefix__ = (function() { return this.productPrefix__T() }); /** @constructor */ ScalaJS.inheritable.scala_xml_dtd_PCDATA$ = (function() { /*<skip>*/ }); ScalaJS.inheritable.scala_xml_dtd_PCDATA$.prototype = ScalaJS.c.scala_xml_dtd_PCDATA$.prototype; ScalaJS.is.scala_xml_dtd_PCDATA$ = (function(obj) { return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_xml_dtd_PCDATA$))) }); ScalaJS.as.scala_xml_dtd_PCDATA$ = (function(obj) { if ((ScalaJS.is.scala_xml_dtd_PCDATA$(obj) || (obj === null))) { return obj } else { ScalaJS.throwClassCastException(obj, "scala.xml.dtd.PCDATA") } }); ScalaJS.isArrayOf.scala_xml_dtd_PCDATA$ = (function(obj, depth) { return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_xml_dtd_PCDATA$))) }); ScalaJS.asArrayOf.scala_xml_dtd_PCDATA$ = (function(obj, depth) { if ((ScalaJS.isArrayOf.scala_xml_dtd_PCDATA$(obj, depth) || (obj === null))) { return obj } else { ScalaJS.throwArrayCastException(obj, "Lscala.xml.dtd.PCDATA;", depth) } }); ScalaJS.data.scala_xml_dtd_PCDATA$ = new ScalaJS.ClassTypeData({ scala_xml_dtd_PCDATA$: 0 }, false, "scala.xml.dtd.PCDATA$", ScalaJS.data.scala_xml_dtd_ContentModel, { scala_xml_dtd_PCDATA$: 1, scala_Serializable: 1, java_io_Serializable: 1, scala_Product: 1, scala_Equals: 1, scala_xml_dtd_ContentModel: 1, java_lang_Object: 1 }); ScalaJS.c.scala_xml_dtd_PCDATA$.prototype.$classData = ScalaJS.data.scala_xml_dtd_PCDATA$; ScalaJS.moduleInstances.scala_xml_dtd_PCDATA = undefined; ScalaJS.modules.scala_xml_dtd_PCDATA = (function() { if ((!ScalaJS.moduleInstances.scala_xml_dtd_PCDATA)) { ScalaJS.moduleInstances.scala_xml_dtd_PCDATA = new ScalaJS.c.scala_xml_dtd_PCDATA$().init___() }; return ScalaJS.moduleInstances.scala_xml_dtd_PCDATA }); //@ sourceMappingURL=PCDATA$.js.map
{ "content_hash": "c843394bed3b6d41af548bcb086e2fbe", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 155, "avg_line_length": 43.93814432989691, "alnum_prop": 0.7151572031909902, "repo_name": "ignaciocases/hermeneumatics", "id": "082c8d182499bbe6f915aad34676cff300927415", "size": "4262", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/scala-node/main/target/streams/compile/externalDependencyClasspath/$global/package-js/extracted-jars/scalajs-library_2.10-0.4.0.jar--29fb2f8b/scala/xml/dtd/PCDATA$.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "430" }, { "name": "CoffeeScript", "bytes": "9579" } ], "symlink_target": "" }
#ifndef SPARROW_ONEELECTRONMATRIX_H #define SPARROW_ONEELECTRONMATRIX_H #include <Utils/Math/AutomaticDifferentiation/MethodsHelpers.h> #include <Utils/Typenames.h> #include <Eigen/Core> namespace Scine { namespace Utils { class MatrixWithDerivatives; class AtomsOrbitalsIndexes; } // namespace Utils namespace Sparrow { namespace nddo { class AtomicParameters; class ElementParameters; class TwoCenterIntegralContainer; /** * @brief This class generates the one-electron matrix H for semi-empirical methods. */ class OneElectronMatrix { public: //! @brief Constructor. OneElectronMatrix(const Utils::ElementTypeCollection& elements, const Utils::PositionCollection& positions, const Eigen::MatrixXd& densityMatrix, const TwoCenterIntegralContainer& twoCIntegrals, const ElementParameters& elementPar, const Utils::AtomsOrbitalsIndexes& aoIndexes); //! @brief Initializes one-electron matrix H and the used data structures. void initialize(); //! @brief Fills the one-electron matrix H by reading and calculating the required integrals. void calculate(const Utils::MatrixWithDerivatives& S); //! @brief Calculates all the blocks on the same atoms. void calculateSameAtomBlocks(); //! @brief Calculates a specific block on an atom. void calculateSameAtomBlock(int a, int startIndex, int nAOs); //! @brief Calculates all the blocks on different atom pairs. void calculateDifferentAtomsBlocks(const Utils::MatrixWithDerivatives& S); //! @brief Calculates a block between a specific atom pair. void calculateDifferentAtomsBlock(int startRow, int startCol, const AtomicParameters& pA, const AtomicParameters& pB, const Utils::MatrixWithDerivatives& S); //! @brief Calculates the derivative contribution up to the order \tparam O. template<Utils::Derivative O> void addDerivatives(Utils::AutomaticDifferentiation::DerivativeContainerType<O>& derivativeContainer, const Utils::MatrixWithDerivatives& S) const; //! @brief Getter for the one-electron matrix H. const Eigen::MatrixXd& operator()() const { return H_; } const Eigen::MatrixXd& getMatrix() const { return H_; } private: template<Utils::Derivative O> void addDerivativesContribution1(Utils::AutomaticDifferentiation::DerivativeContainerType<O>& derivativeContainer, int a, int startIndex, int nAOs) const; template<Utils::Derivative O> void addDerivativesContribution2(Utils::AutomaticDifferentiation::DerivativeContainerType<O>& derivativeContainer, int a, int b, int indexA, int indexB, int nAOsA, int nAOsB, const Utils::MatrixWithDerivatives& S) const; const Eigen::MatrixXd& P; const TwoCenterIntegralContainer& twoCenterIntegrals; const ElementParameters& elementParameters; const Utils::AtomsOrbitalsIndexes& aoIndexes_; int nAOs_ = 0; int nAtoms_ = 0; Eigen::MatrixXd H_; const Utils::ElementTypeCollection& elementTypes_; const Utils::PositionCollection& positions_; }; } // namespace nddo } // namespace Sparrow } // namespace Scine #endif // SPARROW_ONEELECTRONMATRIX_H
{ "content_hash": "f258a6d39278fece67bb16fee56afd0f", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 119, "avg_line_length": 38.93975903614458, "alnum_prop": 0.7295792079207921, "repo_name": "qcscine/sparrow", "id": "cb56a5a153cd57d742634b4770b76d946c48bb7d", "size": "3447", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Sparrow/Sparrow/Implementations/Nddo/Utils/OneElectronMatrix.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1273" }, { "name": "C++", "bytes": "84028157" }, { "name": "CMake", "bytes": "12604" }, { "name": "Mathematica", "bytes": "9361" }, { "name": "Python", "bytes": "74903" }, { "name": "TeX", "bytes": "37639" } ], "symlink_target": "" }
package org.assertj.core.internal.iterables; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.error.ShouldHaveSizeGreaterThanOrEqualTo.shouldHaveSizeGreaterThanOrEqualTo; import static org.assertj.core.test.TestData.someInfo; import static org.assertj.core.util.FailureMessages.actualIsNull; import org.assertj.core.internal.IterablesBaseTest; import org.junit.jupiter.api.Test; class Iterables_assertHasSizeGreaterThanOrEqualTo_Test extends IterablesBaseTest { @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> iterables.assertHasSizeGreaterThanOrEqualTo(someInfo(), null, 6)) .withMessage(actualIsNull()); } @Test void should_fail_if_size_of_actual_is_not_greater_than_or_equal_to_boundary() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> iterables.assertHasSizeGreaterThanOrEqualTo(someInfo(), actual, 6)) .withMessage(shouldHaveSizeGreaterThanOrEqualTo(actual, actual.size(), 6).create()); } @Test void should_pass_if_size_of_actual_is_greater_than_boundary() { iterables.assertHasSizeGreaterThanOrEqualTo(someInfo(), actual, 1); } @Test void should_pass_if_size_of_actual_is_equal_to_boundary() { iterables.assertHasSizeGreaterThanOrEqualTo(someInfo(), actual, actual.size()); } }
{ "content_hash": "97ee331524f41ecc8ecae077bd04e550", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 136, "avg_line_length": 42.02857142857143, "alnum_prop": 0.7375934738273283, "repo_name": "joel-costigliola/assertj-core", "id": "c588aedf3a98357a11fe08fd61add36923a59360", "size": "2077", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/test/java/org/assertj/core/internal/iterables/Iterables_assertHasSizeGreaterThanOrEqualTo_Test.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "13752510" }, { "name": "Shell", "bytes": "36956" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Threading.Tasks; using Newtonsoft.Json; namespace CloudStack.Net { public class ListAutoScaleVmProfilesRequest : APIListRequest { public ListAutoScaleVmProfilesRequest() : base("listAutoScaleVmProfiles") {} /// <summary> /// list resources by account. Must be used with the domainId parameter. /// </summary> public string Account { get { return GetParameterValue<string>(nameof(Account).ToLower()); } set { SetParameterValue(nameof(Account).ToLower(), value); } } /// <summary> /// list only resources belonging to the domain specified /// </summary> public Guid? DomainId { get { return GetParameterValue<Guid?>(nameof(DomainId).ToLower()); } set { SetParameterValue(nameof(DomainId).ToLower(), value); } } /// <summary> /// list resources by display flag; only ROOT admin is eligible to pass this parameter /// </summary> public bool? Fordisplay { get { return GetParameterValue<bool?>(nameof(Fordisplay).ToLower()); } set { SetParameterValue(nameof(Fordisplay).ToLower(), value); } } /// <summary> /// the ID of the autoscale vm profile /// </summary> public Guid? Id { get { return GetParameterValue<Guid?>(nameof(Id).ToLower()); } set { SetParameterValue(nameof(Id).ToLower(), value); } } /// <summary> /// defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves. /// </summary> public bool? Isrecursive { get { return GetParameterValue<bool?>(nameof(Isrecursive).ToLower()); } set { SetParameterValue(nameof(Isrecursive).ToLower(), value); } } /// <summary> /// List by keyword /// </summary> public string Keyword { get { return GetParameterValue<string>(nameof(Keyword).ToLower()); } set { SetParameterValue(nameof(Keyword).ToLower(), value); } } /// <summary> /// If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false /// </summary> public bool? ListAll { get { return GetParameterValue<bool?>(nameof(ListAll).ToLower()); } set { SetParameterValue(nameof(ListAll).ToLower(), value); } } /// <summary> /// the otherdeployparameters of the autoscale vm profile /// </summary> public string OtherDeployParams { get { return GetParameterValue<string>(nameof(OtherDeployParams).ToLower()); } set { SetParameterValue(nameof(OtherDeployParams).ToLower(), value); } } /// <summary> /// list objects by project /// </summary> public Guid? ProjectId { get { return GetParameterValue<Guid?>(nameof(ProjectId).ToLower()); } set { SetParameterValue(nameof(ProjectId).ToLower(), value); } } /// <summary> /// list profiles by service offering id /// </summary> public Guid? Serviceofferingid { get { return GetParameterValue<Guid?>(nameof(Serviceofferingid).ToLower()); } set { SetParameterValue(nameof(Serviceofferingid).ToLower(), value); } } /// <summary> /// the templateid of the autoscale vm profile /// </summary> public Guid? TemplateId { get { return GetParameterValue<Guid?>(nameof(TemplateId).ToLower()); } set { SetParameterValue(nameof(TemplateId).ToLower(), value); } } /// <summary> /// availability zone for the auto deployed virtual machine /// </summary> public Guid? ZoneId { get { return GetParameterValue<Guid?>(nameof(ZoneId).ToLower()); } set { SetParameterValue(nameof(ZoneId).ToLower(), value); } } } /// <summary> /// Lists autoscale vm profiles. /// </summary> public partial interface ICloudStackAPIClient { ListResponse<AutoScaleVmProfileResponse> ListAutoScaleVmProfiles(ListAutoScaleVmProfilesRequest request); Task<ListResponse<AutoScaleVmProfileResponse>> ListAutoScaleVmProfilesAsync(ListAutoScaleVmProfilesRequest request); ListResponse<AutoScaleVmProfileResponse> ListAutoScaleVmProfilesAllPages(ListAutoScaleVmProfilesRequest request); Task<ListResponse<AutoScaleVmProfileResponse>> ListAutoScaleVmProfilesAllPagesAsync(ListAutoScaleVmProfilesRequest request); } public partial class CloudStackAPIClient : ICloudStackAPIClient { public ListResponse<AutoScaleVmProfileResponse> ListAutoScaleVmProfiles(ListAutoScaleVmProfilesRequest request) => Proxy.Request<ListResponse<AutoScaleVmProfileResponse>>(request); public Task<ListResponse<AutoScaleVmProfileResponse>> ListAutoScaleVmProfilesAsync(ListAutoScaleVmProfilesRequest request) => Proxy.RequestAsync<ListResponse<AutoScaleVmProfileResponse>>(request); public ListResponse<AutoScaleVmProfileResponse> ListAutoScaleVmProfilesAllPages(ListAutoScaleVmProfilesRequest request) => Proxy.RequestAllPages<AutoScaleVmProfileResponse>(request); public Task<ListResponse<AutoScaleVmProfileResponse>> ListAutoScaleVmProfilesAllPagesAsync(ListAutoScaleVmProfilesRequest request) => Proxy.RequestAllPagesAsync<AutoScaleVmProfileResponse>(request); } }
{ "content_hash": "e8cb12c43e9029f0fb59e7a44e042bfb", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 206, "avg_line_length": 44.78740157480315, "alnum_prop": 0.6529535864978903, "repo_name": "richardlawley/cloudstack.net", "id": "faf51864e426eaa7dd1dcfeae0e7467bd4f04728", "size": "5688", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/CloudStack.Net/Generated/ListAutoScaleVmProfiles.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "34" }, { "name": "C#", "bytes": "1822509" }, { "name": "Java", "bytes": "75375" }, { "name": "PowerShell", "bytes": "3037" } ], "symlink_target": "" }
import {test} from 'ava'; import {createContainer} from "../lib/index"; import {Action} from "typescript-fsa"; const fsa = require('typescript-fsa'); const isType = fsa.isType; const container = createContainer(); const createAction = fsa.default(); const plus = createAction('PLUS'); const minus = createAction('MINUS'); const multiply = createAction('MULTIPLY'); test('initial', t => { const plusOrMinus = container.createDependency<number>([plus, minus], (state = 0, action) => { if (isType(action, plus)) { return state + action.payload; } else if (isType(action, minus)) { return state - action.payload; } return state; }, 0); const multiplyOrDivide = container.createDependency<number>([multiply], (state, action: Action<number>) => { return state * action.payload; }, 1); const sumAllOperators = container.createDependency<number>([plusOrMinus, multiplyOrDivide], (state, action, plusOrMinusValue: number, multiplyOrDivideValue: number) => { if (state > 100) { throw Error(); } if (isType(action, plus) || isType(action, minus)) { return state + plusOrMinusValue; } else if (isType(action, multiply)) { return state + multiplyOrDivideValue; } return state; }, 0); interface IState { plusOrMinus: number, multiplyOrDivide: number, sumAllOperators: number, } const reducer = container.combine({ plusOrMinus, multiplyOrDivide, sumAllOperators, }); const store = require('redux').createStore(reducer, {}); store.dispatch(plus(5)); t.is(store.getState().plusOrMinus, 5); store.dispatch(minus(1)); t.is(store.getState().plusOrMinus, 4); store.dispatch(minus(1)); t.is(store.getState().plusOrMinus, 3); store.dispatch(multiply(100)); t.is(store.getState().multiplyOrDivide, 100); t.is(store.getState().sumAllOperators, 112); const prevState = store.getState(); try { store.dispatch(plus(100)); } catch (e) { // testing transactions } t.deepEqual(store.getState(), prevState); t.pass(); });
{ "content_hash": "ad6c34171bd9dd0bcd3099493a0edebb", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 112, "avg_line_length": 31, "alnum_prop": 0.6084843128590367, "repo_name": "shura-v/redux-dependent-reducers", "id": "bb50a4395b2b46b6f707fe7598dec69ffe96e486", "size": "2263", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/index.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4525" }, { "name": "TypeScript", "bytes": "7725" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Compute.Models { public partial class ResourceSkusResult { internal static ResourceSkusResult DeserializeResourceSkusResult(JsonElement element) { IReadOnlyList<ResourceSku> value = default; string nextLink = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("value")) { List<ResourceSku> array = new List<ResourceSku>(); foreach (var item in property.Value.EnumerateArray()) { if (item.ValueKind == JsonValueKind.Null) { array.Add(null); } else { array.Add(ResourceSku.DeserializeResourceSku(item)); } } value = array; continue; } if (property.NameEquals("nextLink")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } nextLink = property.Value.GetString(); continue; } } return new ResourceSkusResult(value, nextLink); } } }
{ "content_hash": "ab549380605963741476f0fa61845214", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 93, "avg_line_length": 34.17777777777778, "alnum_prop": 0.4486345903771131, "repo_name": "stankovski/azure-sdk-for-net", "id": "80ee38fbb2496f8c71e2f85ec43d5a9c9a19521b", "size": "1676", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/ResourceSkusResult.Serialization.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "33972632" }, { "name": "Cucumber", "bytes": "89597" }, { "name": "Shell", "bytes": "675" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.github.inikolaev</groupId> <artifactId>vertx-web-kotlin</artifactId> <version>1.0.1-SNAPSHOT</version> <properties> <kotlin.version>1.1.1</kotlin.version> <junit.version>4.12</junit.version> <vertx.version>3.4.1</vertx.version> <snakeyaml.version>1.17</snakeyaml.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib</artifactId> <version>${kotlin.version}</version> </dependency> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-core</artifactId> <version>${vertx.version}</version> </dependency> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-web</artifactId> <version>${vertx.version}</version> </dependency> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-web-client</artifactId> <version>${vertx.version}</version> </dependency> <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>${snakeyaml.version}</version> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-test-junit</artifactId> <version>${kotlin.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-test</artifactId> <version>${kotlin.version}</version> <scope>test</scope> </dependency> </dependencies> <build> <sourceDirectory>src/main/kotlin</sourceDirectory> <plugins> <plugin> <artifactId>kotlin-maven-plugin</artifactId> <groupId>org.jetbrains.kotlin</groupId> <version>${kotlin.version}</version> <executions> <execution> <id>compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> </execution> <execution> <id>test-compile</id> <phase>test-compile</phase> <goals> <goal>test-compile</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
{ "content_hash": "2e4223de8fa8801d80fc989117e18b5a", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 108, "avg_line_length": 36.44705882352941, "alnum_prop": 0.5229180116204003, "repo_name": "inikolaev/vertx-web-kotlin", "id": "11b30ecd7111c538d8ab9096f44d3d2cc61b2fc6", "size": "3098", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pom.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Kotlin", "bytes": "6480" } ], "symlink_target": "" }
using namespace std; ScalarDataSet::ScalarDataSet(const string& fname, int first, int last):Grouped(false) { read(fname,first,last); } ScalarDataSet::~ScalarDataSet() { RawDataSetType::iterator oit(Data.begin()), oit_end(Data.end()); while(oit != oit_end) { delete (*oit).second; ++oit; } } ScalarDataSet* ScalarDataSet::clone(int nc) { if(nc<0) nc=NumRows; ScalarDataSet* c= new ScalarDataSet; RawDataSetType::const_iterator it(Data.begin()), it_end(Data.end()); while(it != it_end) { ScalarObservable* s=new ScalarObservable; s->resize(nc,0.0); c->Data[(*it).first]=s; ++it; } return c; } void ScalarDataSet::read(const string& fname, int first, int last) { ifstream fin(fname.c_str()); if(!fin.is_open()) { cerr << " Cannot open " << fname << endl; return; } string aline; vector<std::string> columnList; bool find_data=true; int nskip=0; while(find_data && !fin.eof()) { streampos cur=fin.tellg(); if(std::getline(fin,aline)) { typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> sep(" "); tokenizer tok(aline, sep); tokenizer::iterator it=tok.begin(); if(isdigit((*it)[0])) { find_data=false; fin.seekg(cur); } else { nskip++; columnList.clear(); if((*it).find("#") == 0) { ++it; } for(; it!=tok.end(); it++) { columnList.push_back(*it); } } } } //temporary vector for the columns so that we can use index vector<ScalarObservable*> dtemp; vector<std::string>::iterator cit(columnList.begin()), cit_end(columnList.end()); while(cit != cit_end) { map<string,ScalarObservable*>::iterator dit(Data.find(*cit)); if(dit == Data.end()) //add to newSet { ScalarObservable* newO=new ScalarObservable; dtemp.push_back(newO); Data[*cit]=newO; } else { //this should be optional for append (*dit).second->Self.clear(); dtemp.push_back((*dit).second); } ++cit; } int nc=columnList.size(); vector<double> arow(nc); double firstColumn=-1; if(last<0) last=numeric_limits<int>::max(); int nr=0; while(nr<first) { std::getline(fin,aline); nr++; } //treat the first column as string string dummy,prev("invalid"); while(nr < last && !fin.eof()) { fin >> dummy; for(int ic=1; ic<nc; ic++) fin >> arow[ic]; if(dummy != prev) { dtemp[0]->push_back(nr); for(int ic=1; ic<nc; ic++) dtemp[ic]->push_back(arow[ic]); nr++; } prev=dummy; } FirstRow=first; LastRow=nr; NumRows=dtemp[0]->size(); } void ScalarDataSet::accumulate(const RawDataSetType& raw) { RawDataSetType::const_iterator sit(raw.begin()), sit_end(raw.end()); RawDataSetType::iterator tit(Data.begin()); while(sit != sit_end) //loop over the ScalarObservables { ScalarObservable::iterator in((*sit).second->begin()); ScalarObservable::iterator out((*tit).second->begin()); ScalarObservable::iterator out_end((*tit).second->end()); while(out!=out_end) { *out++ += *in++; } ++sit; ++tit; } } void ScalarDataSet::group(const map<string,ScalarDataSet*>& dlist) { Grouped=true; FirstRow=0; LastRow=NumRows=(*Data.begin()).second->size(); map<string,ScalarDataSet*>::const_iterator first(dlist.begin()), last(dlist.end()); double dn=0; while(first != last) { accumulate((*first).second->Data); dn+=1.0; ++first; } //divide by the sample numbers dn=1.0/dn; RawDataSetType::iterator tit(Data.begin()), tit_end(Data.end()); while(tit != tit_end) //loop over the ScalarObservables { ScalarObservable::iterator out((*tit).second->begin()); ScalarObservable::iterator out_end((*tit).second->end()); while(out!=out_end) { *out++ *= dn; } ++tit; } } void ScalarDataSet::writeCollect(ostream& os, const string& cname) { map<string,ScalarObservable*>::iterator dit(Data.find(cname)); if(dit != Data.end()) { os << " <collect name=\""<<(*dit).first << "\"" << " value=\"" <<(*dit).second->get_average() << "\"/>\n"; cout << (*dit).first << " " << (*dit).second->get_average() << endl; } } void ScalarDataSet::writeObservable(ostream& os, const string& oname) { map<string,ScalarObservable*>::iterator dit(Data.find(oname)); if(dit != Data.end()) { cout.setf(ios::left,ios::adjustfield); cout << setw(16) << (*dit).first; cout.setf(ios::right,ios::adjustfield); os << " <observable name=\""<<(*dit).first << "\">\n"; (*dit).second->get_stat(); (*dit).second->write(os); os << " </observable>\n"; } }
{ "content_hash": "f6de14858ce80e055073e1fc18e23aed", "timestamp": "", "source": "github", "line_count": 205, "max_line_length": 85, "avg_line_length": 23.502439024390245, "alnum_prop": 0.58302200083022, "repo_name": "habanero-rice/hcpp", "id": "68d8dc631f72b272cb25c588185a257a1cfe862a", "size": "5038", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/performance-regression/full-apps/qmcpack/src/dataspork/ScalarDataSet.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "26226" }, { "name": "C", "bytes": "330261" }, { "name": "C++", "bytes": "255831" }, { "name": "Cuda", "bytes": "10347" }, { "name": "Makefile", "bytes": "7838" }, { "name": "Perl", "bytes": "1748" }, { "name": "Shell", "bytes": "16630" } ], "symlink_target": "" }
package com.mxh.weibo.common.model; import java.util.ArrayList; import java.util.List; public class FollowFollowerExample { /** * @mbggenerated */ protected String orderByClause; /** * @mbggenerated */ protected boolean distinct; /** * @mbggenerated */ protected List<Criteria> oredCriteria; /** * This method corresponds to the database table weibo_follow_follower * @mbggenerated */ public FollowFollowerExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method corresponds to the database table weibo_follow_follower * @mbggenerated */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method corresponds to the database table weibo_follow_follower * @mbggenerated */ public String getOrderByClause() { return orderByClause; } /** * This method corresponds to the database table weibo_follow_follower * @mbggenerated */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method corresponds to the database table weibo_follow_follower * @mbggenerated */ public boolean isDistinct() { return distinct; } /** * This method corresponds to the database table weibo_follow_follower * @mbggenerated */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method corresponds to the database table weibo_follow_follower * @mbggenerated */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method corresponds to the database table weibo_follow_follower * @mbggenerated */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method corresponds to the database table weibo_follow_follower * @mbggenerated */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method corresponds to the database table weibo_follow_follower * @mbggenerated */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method corresponds to the database table weibo_follow_follower * @mbggenerated */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. This class corresponds to the database table weibo_follow_follower * @mbggenerated */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("followFollower.ID is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("followFollower.ID is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("followFollower.ID =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("followFollower.ID <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("followFollower.ID >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("followFollower.ID >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("followFollower.ID <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("followFollower.ID <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("followFollower.ID in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("followFollower.ID not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("followFollower.ID between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("followFollower.ID not between", value1, value2, "id"); return (Criteria) this; } public Criteria andFollowIsNull() { addCriterion("followFollower.FOLLOW is null"); return (Criteria) this; } public Criteria andFollowIsNotNull() { addCriterion("followFollower.FOLLOW is not null"); return (Criteria) this; } public Criteria andFollowEqualTo(String value) { addCriterion("followFollower.FOLLOW =", value, "follow"); return (Criteria) this; } public Criteria andFollowNotEqualTo(String value) { addCriterion("followFollower.FOLLOW <>", value, "follow"); return (Criteria) this; } public Criteria andFollowGreaterThan(String value) { addCriterion("followFollower.FOLLOW >", value, "follow"); return (Criteria) this; } public Criteria andFollowGreaterThanOrEqualTo(String value) { addCriterion("followFollower.FOLLOW >=", value, "follow"); return (Criteria) this; } public Criteria andFollowLessThan(String value) { addCriterion("followFollower.FOLLOW <", value, "follow"); return (Criteria) this; } public Criteria andFollowLessThanOrEqualTo(String value) { addCriterion("followFollower.FOLLOW <=", value, "follow"); return (Criteria) this; } public Criteria andFollowLike(String value) { addCriterion("followFollower.FOLLOW like", value, "follow"); return (Criteria) this; } public Criteria andFollowNotLike(String value) { addCriterion("followFollower.FOLLOW not like", value, "follow"); return (Criteria) this; } public Criteria andFollowIn(List<String> values) { addCriterion("followFollower.FOLLOW in", values, "follow"); return (Criteria) this; } public Criteria andFollowNotIn(List<String> values) { addCriterion("followFollower.FOLLOW not in", values, "follow"); return (Criteria) this; } public Criteria andFollowBetween(String value1, String value2) { addCriterion("followFollower.FOLLOW between", value1, value2, "follow"); return (Criteria) this; } public Criteria andFollowNotBetween(String value1, String value2) { addCriterion("followFollower.FOLLOW not between", value1, value2, "follow"); return (Criteria) this; } public Criteria andFollowedIsNull() { addCriterion("followFollower.FOLLOWED is null"); return (Criteria) this; } public Criteria andFollowedIsNotNull() { addCriterion("followFollower.FOLLOWED is not null"); return (Criteria) this; } public Criteria andFollowedEqualTo(String value) { addCriterion("followFollower.FOLLOWED =", value, "followed"); return (Criteria) this; } public Criteria andFollowedNotEqualTo(String value) { addCriterion("followFollower.FOLLOWED <>", value, "followed"); return (Criteria) this; } public Criteria andFollowedGreaterThan(String value) { addCriterion("followFollower.FOLLOWED >", value, "followed"); return (Criteria) this; } public Criteria andFollowedGreaterThanOrEqualTo(String value) { addCriterion("followFollower.FOLLOWED >=", value, "followed"); return (Criteria) this; } public Criteria andFollowedLessThan(String value) { addCriterion("followFollower.FOLLOWED <", value, "followed"); return (Criteria) this; } public Criteria andFollowedLessThanOrEqualTo(String value) { addCriterion("followFollower.FOLLOWED <=", value, "followed"); return (Criteria) this; } public Criteria andFollowedLike(String value) { addCriterion("followFollower.FOLLOWED like", value, "followed"); return (Criteria) this; } public Criteria andFollowedNotLike(String value) { addCriterion("followFollower.FOLLOWED not like", value, "followed"); return (Criteria) this; } public Criteria andFollowedIn(List<String> values) { addCriterion("followFollower.FOLLOWED in", values, "followed"); return (Criteria) this; } public Criteria andFollowedNotIn(List<String> values) { addCriterion("followFollower.FOLLOWED not in", values, "followed"); return (Criteria) this; } public Criteria andFollowedBetween(String value1, String value2) { addCriterion("followFollower.FOLLOWED between", value1, value2, "followed"); return (Criteria) this; } public Criteria andFollowedNotBetween(String value1, String value2) { addCriterion("followFollower.FOLLOWED not between", value1, value2, "followed"); return (Criteria) this; } public Criteria andMutualIsNull() { addCriterion("followFollower.MUTUAL is null"); return (Criteria) this; } public Criteria andMutualIsNotNull() { addCriterion("followFollower.MUTUAL is not null"); return (Criteria) this; } public Criteria andMutualEqualTo(Byte value) { addCriterion("followFollower.MUTUAL =", value, "mutual"); return (Criteria) this; } public Criteria andMutualNotEqualTo(Byte value) { addCriterion("followFollower.MUTUAL <>", value, "mutual"); return (Criteria) this; } public Criteria andMutualGreaterThan(Byte value) { addCriterion("followFollower.MUTUAL >", value, "mutual"); return (Criteria) this; } public Criteria andMutualGreaterThanOrEqualTo(Byte value) { addCriterion("followFollower.MUTUAL >=", value, "mutual"); return (Criteria) this; } public Criteria andMutualLessThan(Byte value) { addCriterion("followFollower.MUTUAL <", value, "mutual"); return (Criteria) this; } public Criteria andMutualLessThanOrEqualTo(Byte value) { addCriterion("followFollower.MUTUAL <=", value, "mutual"); return (Criteria) this; } public Criteria andMutualIn(List<Byte> values) { addCriterion("followFollower.MUTUAL in", values, "mutual"); return (Criteria) this; } public Criteria andMutualNotIn(List<Byte> values) { addCriterion("followFollower.MUTUAL not in", values, "mutual"); return (Criteria) this; } public Criteria andMutualBetween(Byte value1, Byte value2) { addCriterion("followFollower.MUTUAL between", value1, value2, "mutual"); return (Criteria) this; } public Criteria andMutualNotBetween(Byte value1, Byte value2) { addCriterion("followFollower.MUTUAL not between", value1, value2, "mutual"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. This class corresponds to the database table weibo_follow_follower * @mbggenerated */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } /** * This class corresponds to the database table weibo_follow_follower * @mbggenerated do_not_delete_during_merge */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } }
{ "content_hash": "a54052e0bd47c70d0500f8e12c62bb34", "timestamp": "", "source": "github", "line_count": 517, "max_line_length": 117, "avg_line_length": 27.087040618955513, "alnum_prop": 0.6847329334475865, "repo_name": "miracle857/weibo", "id": "9402ed4062d17b9404b0881c9723f82c7f92c891", "size": "14004", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "weibo/src/main/java/com/mxh/weibo/common/model/FollowFollowerExample.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "165167" }, { "name": "HTML", "bytes": "52877" }, { "name": "Java", "bytes": "281922" }, { "name": "JavaScript", "bytes": "35776" } ], "symlink_target": "" }
const bodyParser = require('body-parser') const express = require('express') const mongodb = require('mongodb') const pathToRegexp = require('path-to-regexp') const morgan = require('morgan') const mongoUri = 'mongodb://localhost:27017/usDebt' const app = express() app.use(bodyParser.json()) app.use(morgan('combined')) app.use(function (req, res, next) { res.header("Access-Control-Allow-Origin", "*") res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE") res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization") next() }) app.get('/', (req, res) => { res.send('Hello world!') }) app.get('/api/states', (req, res) => { db.collection('states').find() .toArray((err, states) => { res.send(states) }) }) app.post('/api/states', (req, res) => { const state = Object.assign({}, req.body) db.collection('states') .insert(state, (err, result) => { if (err) return console.log(err) res.json(result) }) }) app.get('/api/states/:_id', (req, res) => { const objectId = mongodb.ObjectID(req.params['_id']) db.collection('states') .findOne({ '_id': objectId }, (err, state) => { res.json(state) }) }) app.put('/api/states/:_id', (req, res) => { const objectId = mongodb.ObjectID(req.params['_id']) let state = Object.assign({}, req.body) delete state._id db.collection('states') .update({ '_id': objectId }, state, (err, result) => { if (err) return console.log(err) res.json(result) }) }) app.delete('/api/states/:_id', (req, res) => { const objectId = mongodb.ObjectID(req.params['_id']) db.collection('states') .remove({ '_id': objectId }, (err, result) => { if (err) return console.log(err) res.json(result) }) }) mongodb.MongoClient.connect(mongoUri, (err, database) => { if (err) return console.log(err) console.log('Connected to database: ' + mongoUri) db = database app.listen(3000, () => { console.log('Example app listening on port 3000!') }) })
{ "content_hash": "1c90e1f02be71693573b2487507e424e", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 109, "avg_line_length": 26.714285714285715, "alnum_prop": 0.6208070004861449, "repo_name": "TYMG/USDebtMap", "id": "f47ebe4dd6be30620b5e9c7fc4fa26672e9b9a3c", "size": "2057", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "143" }, { "name": "HTML", "bytes": "1607" }, { "name": "JavaScript", "bytes": "3703" }, { "name": "Python", "bytes": "2614" }, { "name": "TypeScript", "bytes": "9899" } ], "symlink_target": "" }
describe GraylogAPI::Client, vcr: true do include_context 'graylogapi' let(:client) { graylogapi.client } context 'success requests' do let(:dashboard) do client.request(:post, '/dashboards', title: 'Test_Dashboard', description: 'Test_Dashboard') end let(:dashboard_id) do client.request(:get, '/dashboards')['dashboards'] .select { |e| e['title'] = 'Test_Dashboard' } .first['id'] end it 'post' do dash = client.request(:post, '/dashboards', title: 'Post Dashboard', description: 'post dashboard') expect(dash.keys).to include 'dashboard_id' end it 'get' do expect(client.request(:get, '/count/total').code).to eq 200 end it 'put' do req = client.request(:put, "/dashboards/#{dashboard_id}", title: 'Edited_Dashboard') expect(req.code).to eq 204 end it 'delete' do request = client.request(:delete, "/dashboards/#{dashboard_id}") expect(request.code).to eq 204 end it' return request' do request = client.request(:get, '/') expect(request.class).to eq GraylogAPI::Client::Response end end context 'auth by token' do subject(:api) { GraylogAPI.new(base_url: 'http://localhost:9000/api', token: token) } let(:token) { graylogapi.users.create_token('admin', 'rest')['token'] } after { graylogapi.users.delete_token('admin', token) } it 'shoud authorize' do expect(api.dashboards.all.code).to eq 200 end end end
{ "content_hash": "0b1a7ed5c5e508656b56ab2844e28a3a", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 89, "avg_line_length": 29.545454545454547, "alnum_prop": 0.5821538461538461, "repo_name": "postgred/graylogapi", "id": "5efdd15cf37897c0dd268f5581605f9fdacb53b3", "size": "1625", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/graylog_api/client_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "42999" } ], "symlink_target": "" }
var app = {}; $(function() { app.picFilter = ""; /** * The basic Pic Model represents an image that can be * favorited or deleted as needed. */ var Pic = Backbone.Model.extend({ defaults: function() { return { title: "Untitled Photo", deleted: false, favorited: false, picId: Pics.nextPicId(), }; }, toggleFavorited: function() { this.save({favorited: !this.get("favorited")}); }, toggleDeleted: function() { this.save({deleted: !this.get("deleted")}); }, }); /** * A Collection of pictures: */ var PicSet = Backbone.Collection.extend({ model: Pic, localStorage: new Backbone.LocalStorage("picpik-backbone"), deleted: function() { return this.where({deleted: true}); }, favorited: function() { return this.where({favorited: true}); }, nextPicId: function() { if (!this.length) return 1; return (this.last().get('picId') % 4) + 1; }, comparator: 'order' }); var Pics = new PicSet; /** * The View object for a Picture in the grid. * The view object is a div */ var PicView = Backbone.View.extend({ tagName: "div", template: _.template($("#pic-template").html()), events: { "click .favorite" : "toggleFavorited", "click .delete" : "toggleDeleted", }, initialize: function() { this.listenTo(this.model, 'change', this.render); this.listenTo(this.model, 'destroy', this.remove); this.listenTo(this.model, 'visible', this.toggleVisible); }, render: function() { this.$el.html(this.template(this.model.toJSON())); this.$el.toggleClass('favorited', this.model.get('favorited')); this.toggleVisible(); return this; }, toggleFavorited: function() { this.model.toggleFavorited(); }, toggleDeleted: function() { this.$el.fadeOut(400, (function() { this.model.toggleDeleted(); }).bind(this)); }, toggleVisible: function() { if (this.isHidden()) { this.$el.hide(); } else { this.$el.show(); } }, isHidden: function() { console.log('Check isHidden'); var isDeleted = this.model.get('deleted'); var isFavorited = this.model.get('favorited'); console.log(isFavorited); return ( (!isFavorited && app.picFilter === "favorited") || (isDeleted && app.picFilter != "deleted") || (!isDeleted && app.picFilter === "deleted") ); }, }); /** * The top-level piece of UI for the App. */ var AppView = Backbone.View.extend({ el: $("#picpikapp"), statsTemplate: _.template($('#stats-template').html()), events: { "click #add-pic": "createPic" }, initialize: function() { this.listenTo(Pics, 'add', this.addOne); this.listenTo(Pics, 'reset', this.addAll); this.listenTo(Pics, 'all', this.render); this.listenTo(Pics, 'change:completed', this.filterOne); this.listenTo(Pics, 'filter', this.filterAll); this.$main = $('#main'); this.$footer = $('#footer-stats'); Pics.fetch(); }, render: function() { var deleted = Pics.deleted().length; var favorited = Pics.favorited().length; this.$footer.html(this.statsTemplate({ num_favorited: favorited, num_deleted: deleted })); this.$('#filters a').removeClass('selected') .filter('[href="#/' + (app.picFilter || '') + '"]') .addClass('selected'); }, addOne: function(pic) { var view = new PicView({model: pic}); this.$('#pic-grid').append(view.render().el); }, addAll: function() { Pics.each(this.addOne, this); }, filterOne: function (pic) { pic.trigger('visible'); }, filterAll: function() { Pics.each(this.filterOne, this); }, createPic: function(e) { console.log('create pic!'); Pics.create({title: "New Pic"}); }, }); var App = new AppView; var PicsRouter = Backbone.Router.extend({ routes: { '*filter': 'setFilter' }, setFilter: function (param) { app.picFilter = param || ''; Pics.trigger('filter'); } }); var PicPikRouter = new PicsRouter(); Backbone.history.start(); });
{ "content_hash": "ba6a37d9815a938dabb11c3599059b76", "timestamp": "", "source": "github", "line_count": 195, "max_line_length": 75, "avg_line_length": 27.682051282051283, "alnum_prop": 0.44979622082252685, "repo_name": "lrsjohnson/picpik", "id": "a7e6e91cc65542049be1b03b478102ae59fe10d8", "size": "5398", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "demos/backbone-basic/js/app.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "386" }, { "name": "JavaScript", "bytes": "407439" } ], "symlink_target": "" }
package org.jboss.pnc.facade.rsql.mapper; import org.jboss.pnc.model.GenericEntity; import org.jboss.pnc.model.ProductMilestone; import org.jboss.pnc.model.ProductMilestone_; import javax.enterprise.context.ApplicationScoped; import javax.persistence.metamodel.SingularAttribute; /** * * @author Honza Brázdil &lt;jbrazdil@redhat.com&gt; */ @ApplicationScoped public class ProductMilestoneRSQLMapper extends AbstractRSQLMapper<Integer, ProductMilestone> { public ProductMilestoneRSQLMapper() { super(ProductMilestone.class); } @Override protected SingularAttribute<ProductMilestone, ? extends GenericEntity<Integer>> toEntity(String name) { switch (name) { case "productVersion": return ProductMilestone_.productVersion; case "productRelease": return ProductMilestone_.productRelease; default: return null; } } @Override protected SingularAttribute<ProductMilestone, ?> toAttribute(String name) { switch (name) { case "id": return ProductMilestone_.id; case "version": return ProductMilestone_.version; case "endDate": return ProductMilestone_.endDate; case "startingDate": return ProductMilestone_.startingDate; case "plannedEndDate": return ProductMilestone_.plannedEndDate; default: return null; } } }
{ "content_hash": "4b3799386bc9773224362d135f897581", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 107, "avg_line_length": 29.615384615384617, "alnum_prop": 0.6357142857142857, "repo_name": "alexcreasy/pnc", "id": "e7953f3c78e501fd0513e59a1cb7841c652c4249", "size": "2249", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "facade/src/main/java/org/jboss/pnc/facade/rsql/mapper/ProductMilestoneRSQLMapper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "113413" }, { "name": "HTML", "bytes": "394550" }, { "name": "Java", "bytes": "4283733" }, { "name": "JavaScript", "bytes": "3099544" }, { "name": "TSQL", "bytes": "47567" } ], "symlink_target": "" }
require 'rails_helper' RSpec.describe Favorite, type: :model do let(:topic) { create(:topic) } let(:user) { create(:user) } let(:post) { create(:post) } let(:favorite) { Favorite.create!(post: post, user: user) } it { is_expected.to belong_to(:post) } it { is_expected.to belong_to(:user) } end
{ "content_hash": "df4682f7942c4984ac602c8e0b84eab2", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 62, "avg_line_length": 28.545454545454547, "alnum_prop": 0.6337579617834395, "repo_name": "stellanorthm/bloccit", "id": "01a159275eba0150c9562eb714b266c15ad0cb2d", "size": "314", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bloccit/spec/models/favorite_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9267" }, { "name": "CoffeeScript", "bytes": "2321" }, { "name": "HTML", "bytes": "32745" }, { "name": "JavaScript", "bytes": "129888" }, { "name": "Ruby", "bytes": "122226" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using WeifenLuo.WinFormsUI.Docking; namespace SuperPutty.Utils { /// <summary> /// Helper class to track single instance tool windows (sessions, log viewer, layouts) /// </summary> public class SingletonToolWindowHelper<T> where T : ToolWindow { public delegate T WindowInitializer(SingletonToolWindowHelper<T> helper); public SingletonToolWindowHelper(string name, DockPanel dockPanel) : this(name, dockPanel, null) {} public SingletonToolWindowHelper(string name, DockPanel dockPanel, WindowInitializer initializer) { this.Name = name; this.DockPanel = dockPanel; this.Initializer = initializer; } public void ShowWindow(DockState dockState) { if (this.Instance == null) { Initialize(); this.Instance.Show(DockPanel, dockState); SuperPuTTY.ReportStatus("Showing " + this.Name); } else { this.Instance.Show(DockPanel); SuperPuTTY.ReportStatus("Bringing {0} to Front", this.Name); } } public void ShowWindow(DockPane pane, DockAlignment dockAlign, double proportion) { if (this.Instance == null) { Initialize(); this.Instance.Show(pane, dockAlign, proportion); SuperPuTTY.ReportStatus("Showing " + this.Name); } else { this.Instance.Show(DockPanel); SuperPuTTY.ReportStatus("Bringing {0} to Front", this.Name); } } public bool IsVisibleAsToolWindow { get { return this.Instance != null && this.Instance.DockHandler.Pane != null && !this.Instance.DockHandler.Pane.IsAutoHide; } } public T Initialize() { if (this.Initializer == null) { // assume defautl ctor ok this.Instance = Activator.CreateInstance<T>(); } else { // some kind of factor method throw in this.Instance = this.Initializer(this); } this.Instance.FormClosed += new FormClosedEventHandler(Instance_FormClosed); return Instance; } void Instance_FormClosed(object sender, FormClosedEventArgs e) { this.Instance = null; SuperPuTTY.ReportStatus("Closed {0}", this.Name); } public void Hide() { if (this.Instance != null) { this.Instance.Hide(); } } public void Restore() { if (this.Instance != null) { this.Instance.Show(this.DockPanel); } } public bool IsVisible { get { return this.Instance != null && this.Instance.Visible; } } public string Name { get; private set; } public DockPanel DockPanel { get; private set; } public WindowInitializer Initializer { get; private set; } public T Instance { get; private set; } } }
{ "content_hash": "97409f03688bd4a2cbd9822da45d5331", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 133, "avg_line_length": 30.01769911504425, "alnum_prop": 0.5356721698113207, "repo_name": "Dukobpa3/superputty", "id": "26a33a710797499c4313fd1c8d7f4ee427d7c055", "size": "3394", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "SuperPutty/Utils/SingletonToolWindowHelper.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "659463" } ], "symlink_target": "" }
<?php namespace Eloqua\Api\Soap\Service; class DynamicEntityQueryResults { /** * @var ArrayOfDynamicEntity $Entities */ protected $Entities = null; /** * @var int $TotalPages */ protected $TotalPages = null; /** * @var int $TotalRecords */ protected $TotalRecords = null; /** * @param int $TotalPages * @param int $TotalRecords */ public function __construct($TotalPages, $TotalRecords) { $this->TotalPages = $TotalPages; $this->TotalRecords = $TotalRecords; } /** * @return ArrayOfDynamicEntity */ public function getEntities() { return $this->Entities; } /** * @param ArrayOfDynamicEntity $Entities * @return \Eloqua\Api\Soap\Service\DynamicEntityQueryResults */ public function setEntities($Entities) { $this->Entities = $Entities; return $this; } /** * @return int */ public function getTotalPages() { return $this->TotalPages; } /** * @param int $TotalPages * @return \Eloqua\Api\Soap\Service\DynamicEntityQueryResults */ public function setTotalPages($TotalPages) { $this->TotalPages = $TotalPages; return $this; } /** * @return int */ public function getTotalRecords() { return $this->TotalRecords; } /** * @param int $TotalRecords * @return \Eloqua\Api\Soap\Service\DynamicEntityQueryResults */ public function setTotalRecords($TotalRecords) { $this->TotalRecords = $TotalRecords; return $this; } }
{ "content_hash": "64abea9d79ed16063582eabe5c43126e", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 65, "avg_line_length": 20.70886075949367, "alnum_prop": 0.5825183374083129, "repo_name": "revvi/eloqua-php-api", "id": "d3569f3bfb4ad109bfb27a8900cdb1fc1e0547be", "size": "1636", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Api/Soap/Service/DynamicEntityQueryResults.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "183000" } ], "symlink_target": "" }
// ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_DRAGIMAGE #ifndef WX_PRECOMP #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly" #include <stdio.h> #include "wx/window.h" #include "wx/dcclient.h" #include "wx/dcscreen.h" #include "wx/dcmemory.h" #include "wx/settings.h" #include "wx/intl.h" #include "wx/log.h" #include "wx/frame.h" #include "wx/image.h" #endif #include "wx/msw/private.h" #include "wx/msw/dragimag.h" #include "wx/msw/private.h" #ifdef __WXWINCE__ // for SM_CXCURSOR and SM_CYCURSOR #include "wx/msw/wince/missing.h" #endif // __WXWINCE__ // Wine doesn't have this yet #ifndef ListView_CreateDragImage #define ListView_CreateDragImage(hwnd, i, lpptUpLeft) \ (HIMAGELIST)SNDMSG((hwnd), LVM_CREATEDRAGIMAGE, (WPARAM)(int)(i), (LPARAM)(LPPOINT)(lpptUpLeft)) #endif // ---------------------------------------------------------------------------- // macros // ---------------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(wxDragImage, wxObject) #define GetHimageList() ((HIMAGELIST) m_hImageList) // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // wxDragImage ctors/dtor // ---------------------------------------------------------------------------- wxDragImage::wxDragImage() { Init(); } wxDragImage::~wxDragImage() { if ( m_hImageList ) ImageList_Destroy(GetHimageList()); #if !wxUSE_SIMPLER_DRAGIMAGE if ( m_hCursorImageList ) ImageList_Destroy((HIMAGELIST) m_hCursorImageList); #endif } void wxDragImage::Init() { m_hImageList = 0; #if !wxUSE_SIMPLER_DRAGIMAGE m_hCursorImageList = 0; #endif m_window = NULL; m_fullScreen = false; } // Attributes //////////////////////////////////////////////////////////////////////////// // Operations //////////////////////////////////////////////////////////////////////////// // Create a drag image from a bitmap and optional cursor bool wxDragImage::Create(const wxBitmap& image, const wxCursor& cursor) { if ( m_hImageList ) ImageList_Destroy(GetHimageList()); m_hImageList = 0; #ifdef __WXWINCE__ UINT flags = ILC_COLOR; #else UINT flags wxDUMMY_INITIALIZE(0) ; if (image.GetDepth() <= 4) flags = ILC_COLOR4; else if (image.GetDepth() <= 8) flags = ILC_COLOR8; else if (image.GetDepth() <= 16) flags = ILC_COLOR16; else if (image.GetDepth() <= 24) flags = ILC_COLOR24; else flags = ILC_COLOR32; #endif bool mask = (image.GetMask() != 0); // Curiously, even if the image doesn't have a mask, // we still have to use ILC_MASK or the image won't show // up when dragged. // if ( mask ) flags |= ILC_MASK; m_hImageList = (WXHIMAGELIST) ImageList_Create(image.GetWidth(), image.GetHeight(), flags, 1, 1); int index; if (!mask) { HBITMAP hBitmap1 = (HBITMAP) image.GetHBITMAP(); index = ImageList_Add(GetHimageList(), hBitmap1, 0); } else { HBITMAP hBitmap1 = (HBITMAP) image.GetHBITMAP(); HBITMAP hBitmap2 = (HBITMAP) image.GetMask()->GetMaskBitmap(); HBITMAP hbmpMask = wxInvertMask(hBitmap2); index = ImageList_Add(GetHimageList(), hBitmap1, hbmpMask); ::DeleteObject(hbmpMask); } if ( index == -1 ) { wxLogError(_("Couldn't add an image to the image list.")); } m_cursor = cursor; // Can only combine with drag image after calling BeginDrag. return (index != -1) ; } // Create a drag image from an icon and optional cursor bool wxDragImage::Create(const wxIcon& image, const wxCursor& cursor) { if ( m_hImageList ) ImageList_Destroy(GetHimageList()); m_hImageList = 0; #ifdef __WXWINCE__ UINT flags = ILC_COLOR; #else UINT flags wxDUMMY_INITIALIZE(0) ; if (image.GetDepth() <= 4) flags = ILC_COLOR4; else if (image.GetDepth() <= 8) flags = ILC_COLOR8; else if (image.GetDepth() <= 16) flags = ILC_COLOR16; else if (image.GetDepth() <= 24) flags = ILC_COLOR24; else flags = ILC_COLOR32; #endif flags |= ILC_MASK; m_hImageList = (WXHIMAGELIST) ImageList_Create(image.GetWidth(), image.GetHeight(), flags, 1, 1); HICON hIcon = (HICON) image.GetHICON(); int index = ImageList_AddIcon(GetHimageList(), hIcon); if ( index == -1 ) { wxLogError(_("Couldn't add an image to the image list.")); } m_cursor = cursor; // Can only combine with drag image after calling BeginDrag. return (index != -1) ; } // Create a drag image from a string and optional cursor bool wxDragImage::Create(const wxString& str, const wxCursor& cursor) { wxFont font(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT)); wxCoord w = 0, h = 0; wxScreenDC dc; dc.SetFont(font); dc.GetTextExtent(str, & w, & h); dc.SetFont(wxNullFont); wxMemoryDC dc2; dc2.SetFont(font); wxBitmap bitmap((int) w+2, (int) h+2); dc2.SelectObject(bitmap); dc2.SetBackground(* wxWHITE_BRUSH); dc2.Clear(); dc2.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT); dc2.SetTextForeground(* wxLIGHT_GREY); dc2.DrawText(str, 0, 0); dc2.DrawText(str, 1, 0); dc2.DrawText(str, 2, 0); dc2.DrawText(str, 1, 1); dc2.DrawText(str, 2, 1); dc2.DrawText(str, 1, 2); dc2.DrawText(str, 2, 2); dc2.SetTextForeground(* wxBLACK); dc2.DrawText(str, 1, 1); dc2.SelectObject(wxNullBitmap); #if wxUSE_WXDIB // Make the bitmap masked wxImage image = bitmap.ConvertToImage(); image.SetMaskColour(255, 255, 255); return Create(wxBitmap(image), cursor); #else return false; #endif } #if wxUSE_TREECTRL // Create a drag image for the given tree control item bool wxDragImage::Create(const wxTreeCtrl& treeCtrl, wxTreeItemId& id) { if ( m_hImageList ) ImageList_Destroy(GetHimageList()); m_hImageList = (WXHIMAGELIST) TreeView_CreateDragImage(GetHwndOf(&treeCtrl), (HTREEITEM) id.m_pItem); if ( !m_hImageList ) { // fall back on just the item text if there is no image return Create(treeCtrl.GetItemText(id)); } return true; } #endif #if wxUSE_LISTCTRL // Create a drag image for the given list control item bool wxDragImage::Create(const wxListCtrl& listCtrl, long id) { if ( m_hImageList ) ImageList_Destroy(GetHimageList()); POINT pt; pt.x = pt.y = 0; m_hImageList = (WXHIMAGELIST) ListView_CreateDragImage(GetHwndOf(&listCtrl), id, &pt); if ( !m_hImageList ) { // as for wxTreeCtrl, fall back on dragging just the item text return Create(listCtrl.GetItemText(id)); } return true; } #endif // Begin drag bool wxDragImage::BeginDrag(const wxPoint& hotspot, wxWindow* window, bool fullScreen, wxRect* rect) { wxASSERT_MSG( (m_hImageList != 0), wxT("Image list must not be null in BeginDrag.")); wxASSERT_MSG( (window != 0), wxT("Window must not be null in BeginDrag.")); m_fullScreen = fullScreen; if (rect) m_boundingRect = * rect; bool ret = (ImageList_BeginDrag(GetHimageList(), 0, hotspot.x, hotspot.y) != 0); if (!ret) { wxFAIL_MSG( wxT("BeginDrag failed.") ); return false; } if (m_cursor.Ok()) { #if wxUSE_SIMPLER_DRAGIMAGE m_oldCursor = window->GetCursor(); window->SetCursor(m_cursor); #else if (!m_hCursorImageList) { #ifndef SM_CXCURSOR // Smartphone may not have these metric symbol int cxCursor = 16; int cyCursor = 16; #else int cxCursor = ::GetSystemMetrics(SM_CXCURSOR); int cyCursor = ::GetSystemMetrics(SM_CYCURSOR); #endif m_hCursorImageList = (WXHIMAGELIST) ImageList_Create(cxCursor, cyCursor, ILC_MASK, 1, 1); } // See if we can find the cursor hotspot wxPoint curHotSpot(hotspot); // Although it seems to produce the right position, when the hotspot goeos // negative it has strange effects on the image. // How do we stop the cursor jumping right and below of where it should be? #if 0 ICONINFO iconInfo; if (::GetIconInfo((HICON) (HCURSOR) m_cursor.GetHCURSOR(), & iconInfo) != 0) { curHotSpot.x -= iconInfo.xHotspot; curHotSpot.y -= iconInfo.yHotspot; } #endif //wxString msg; //msg.Printf("Hotspot = %d, %d", curHotSpot.x, curHotSpot.y); //wxLogDebug(msg); // First add the cursor to the image list HCURSOR hCursor = (HCURSOR) m_cursor.GetHCURSOR(); int cursorIndex = ImageList_AddIcon((HIMAGELIST) m_hCursorImageList, (HICON) hCursor); wxASSERT_MSG( (cursorIndex != -1), wxT("ImageList_AddIcon failed in BeginDrag.")); if (cursorIndex != -1) { ImageList_SetDragCursorImage((HIMAGELIST) m_hCursorImageList, cursorIndex, curHotSpot.x, curHotSpot.y); } #endif } #if !wxUSE_SIMPLER_DRAGIMAGE if (m_cursor.Ok()) ::ShowCursor(FALSE); #endif m_window = window; ::SetCapture(GetHwndOf(window)); return true; } // Begin drag. hotspot is the location of the drag position relative to the upper-left // corner of the image. This is full screen only. fullScreenRect gives the // position of the window on the screen, to restrict the drag to. bool wxDragImage::BeginDrag(const wxPoint& hotspot, wxWindow* window, wxWindow* fullScreenRect) { wxRect rect; int x = fullScreenRect->GetPosition().x; int y = fullScreenRect->GetPosition().y; wxSize sz = fullScreenRect->GetSize(); if (fullScreenRect->GetParent() && !fullScreenRect->IsKindOf(CLASSINFO(wxFrame))) fullScreenRect->GetParent()->ClientToScreen(& x, & y); rect.x = x; rect.y = y; rect.width = sz.x; rect.height = sz.y; return BeginDrag(hotspot, window, true, & rect); } // End drag bool wxDragImage::EndDrag() { wxASSERT_MSG( (m_hImageList != 0), wxT("Image list must not be null in EndDrag.")); ImageList_EndDrag(); if ( !::ReleaseCapture() ) { wxLogLastError(wxT("ReleaseCapture")); } #if wxUSE_SIMPLER_DRAGIMAGE if (m_cursor.Ok() && m_oldCursor.Ok()) m_window->SetCursor(m_oldCursor); #else ::ShowCursor(TRUE); #endif m_window = NULL; return true; } // Move the image: call from OnMouseMove. Pt is in window client coordinates if window // is non-NULL, or in screen coordinates if NULL. bool wxDragImage::Move(const wxPoint& pt) { wxASSERT_MSG( (m_hImageList != 0), wxT("Image list must not be null in Move.")); // These are in window, not client coordinates. // So need to convert to client coordinates. wxPoint pt2(pt); if (m_window && !m_fullScreen) { RECT rect; rect.left = 0; rect.top = 0; rect.right = 0; rect.bottom = 0; DWORD style = ::GetWindowLong((HWND) m_window->GetHWND(), GWL_STYLE); #ifdef __WIN32__ DWORD exStyle = ::GetWindowLong((HWND) m_window->GetHWND(), GWL_EXSTYLE); ::AdjustWindowRectEx(& rect, style, FALSE, exStyle); #else ::AdjustWindowRect(& rect, style, FALSE); #endif // Subtract the (negative) values, i.e. add a small increment pt2.x -= rect.left; pt2.y -= rect.top; } else if (m_window && m_fullScreen) { pt2 = m_window->ClientToScreen(pt2); } bool ret = (ImageList_DragMove( pt2.x, pt2.y ) != 0); m_position = pt2; return ret; } bool wxDragImage::Show() { wxASSERT_MSG( (m_hImageList != 0), wxT("Image list must not be null in Show.")); HWND hWnd = 0; if (m_window && !m_fullScreen) hWnd = (HWND) m_window->GetHWND(); bool ret = (ImageList_DragEnter( hWnd, m_position.x, m_position.y ) != 0); return ret; } bool wxDragImage::Hide() { wxASSERT_MSG( (m_hImageList != 0), wxT("Image list must not be null in Hide.")); HWND hWnd = 0; if (m_window && !m_fullScreen) hWnd = (HWND) m_window->GetHWND(); bool ret = (ImageList_DragLeave( hWnd ) != 0); return ret; } #endif // wxUSE_DRAGIMAGE
{ "content_hash": "f225d037b28ae8502467fd131bc62d19", "timestamp": "", "source": "github", "line_count": 463, "max_line_length": 115, "avg_line_length": 28.647948164146868, "alnum_prop": 0.5628015681544029, "repo_name": "airgames/vuforia-gamekit-integration", "id": "28f6a8ec3a352e94c264f5df24de5808c26a0952", "size": "13653", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Gamekit/wxWidgets-2.9.1/src/msw/dragimag.cpp", "mode": "33261", "license": "mit", "language": [], "symlink_target": "" }
/* @flow */ import { warn, invokeWithErrorHandling } from 'core/util/index' import { cached, isUndef, isTrue, isPlainObject } from 'shared/util' const normalizeEvent = cached((name: string): { name: string, once: boolean, capture: boolean, passive: boolean, handler?: Function, params?: Array<any> } => { const passive = name.charAt(0) === '&' name = passive ? name.slice(1) : name const once = name.charAt(0) === '~' // Prefixed last, checked first name = once ? name.slice(1) : name const capture = name.charAt(0) === '!' name = capture ? name.slice(1) : name return { name, once, capture, passive } }) export function createFnInvoker (fns: Function | Array<Function>, vm: ?Component): Function { function invoker () { const fns = invoker.fns if (Array.isArray(fns)) { const cloned = fns.slice() for (let i = 0; i < cloned.length; i++) { invokeWithErrorHandling(cloned[i], null, arguments, vm, `v-on handler`) } } else { // return handler return value for single handlers return invokeWithErrorHandling(fns, null, arguments, vm, `v-on handler`) } } invoker.fns = fns return invoker } export function updateListeners ( on: Object, oldOn: Object, add: Function, remove: Function, createOnceHandler: Function, vm: Component ) { let name, def, cur, old, event for (name in on) { def = cur = on[name] old = oldOn[name] event = normalizeEvent(name) /* istanbul ignore if */ if (__WEEX__ && isPlainObject(def)) { cur = def.handler event.params = def.params } if (isUndef(cur)) { process.env.NODE_ENV !== 'production' && warn( `Invalid handler for event "${event.name}": got ` + String(cur), vm ) } else if (isUndef(old)) { if (isUndef(cur.fns)) { cur = on[name] = createFnInvoker(cur, vm) } if (isTrue(event.once)) { cur = on[name] = createOnceHandler(event.name, cur, event.capture) } add(event.name, cur, event.capture, event.passive, event.params) } else if (cur !== old) { old.fns = cur on[name] = old } } for (name in oldOn) { if (isUndef(on[name])) { event = normalizeEvent(name) remove(event.name, oldOn[name], event.capture) } } }
{ "content_hash": "a75b309f8c5605796fd3113a67f96ff6", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 93, "avg_line_length": 24.589473684210525, "alnum_prop": 0.5980308219178082, "repo_name": "zhaoshuxue/document", "id": "dcde7f488fe523584af8f946646ada2bc9a36cbc", "size": "2336", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "JavaScript/vue/vue-cli2/node_modules/vue/src/core/vdom/helpers/update-listeners.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "56" }, { "name": "CSS", "bytes": "44449" }, { "name": "Dockerfile", "bytes": "3719" }, { "name": "Go", "bytes": "612" }, { "name": "HTML", "bytes": "63306" }, { "name": "Java", "bytes": "58482" }, { "name": "JavaScript", "bytes": "42036" }, { "name": "Python", "bytes": "23932" }, { "name": "Shell", "bytes": "3789" }, { "name": "VBScript", "bytes": "52" }, { "name": "Vue", "bytes": "2895" } ], "symlink_target": "" }
namespace Google.Cloud.Vision.V1.Snippets { // [START vision_v1_generated_ProductSearch_ListProductSets_async_flattened] using Google.Api.Gax; using Google.Cloud.Vision.V1; using System; using System.Linq; using System.Threading.Tasks; public sealed partial class GeneratedProductSearchClientSnippets { /// <summary>Snippet for ListProductSetsAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task ListProductSetsAsync() { // Create client ProductSearchClient productSearchClient = await ProductSearchClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedAsyncEnumerable<ListProductSetsResponse, ProductSet> response = productSearchClient.ListProductSetsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((ProductSet item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListProductSetsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ProductSet item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ProductSet> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ProductSet item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; } } // [END vision_v1_generated_ProductSearch_ListProductSets_async_flattened] }
{ "content_hash": "57c9acbadeb8b9ad87311f35db5fcfea", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 130, "avg_line_length": 43.61666666666667, "alnum_prop": 0.6102407336645014, "repo_name": "jskeet/google-cloud-dotnet", "id": "357068fe7239cdba597c46fa5a795965e278900b", "size": "3239", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "apis/Google.Cloud.Vision.V1/Google.Cloud.Vision.V1.GeneratedSnippets/ProductSearchClient.ListProductSetsAsyncSnippet.g.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "767" }, { "name": "C#", "bytes": "268415427" }, { "name": "CSS", "bytes": "1346" }, { "name": "Dockerfile", "bytes": "3173" }, { "name": "HTML", "bytes": "3823" }, { "name": "JavaScript", "bytes": "226" }, { "name": "PowerShell", "bytes": "3303" }, { "name": "Python", "bytes": "2744" }, { "name": "Shell", "bytes": "65260" }, { "name": "sed", "bytes": "1030" } ], "symlink_target": "" }
package com.github.mdr.mash.ns.core import com.github.mdr.mash.classes.MashClass import com.github.mdr.mash.evaluator._ import com.github.mdr.mash.functions._ import com.github.mdr.mash.inference._ import com.github.mdr.mash.ns.time._ import com.github.mdr.mash.runtime._ object NumberClass extends MashClass("core.Number") { override val methods = Seq( BytesMethod, DaysMethod, GbMethod, HoursMethod, KbMethod, MbMethod, MillisecondsMethod, MinutesMethod, MonthsMethod, NegateMethod, PowerMethod, SecondsMethod, TagMethod, TimesMethod, ToIntMethod, ToMethod, UntaggedMethod, UntilMethod, WeeksMethod) object PowerMethod extends MashMethod("power") { val Exponent = Parameter( nameOpt = Some("exponent"), summaryOpt = Some("Exponent")) val params = ParameterModel(Exponent) def call(target: MashValue, boundParams: BoundParams): MashNumber = { val exponent = boundParams.validateNumber(Exponent) MashNumber(math.pow(target.asInstanceOf[MashNumber].n, exponent)) } override def typeInferenceStrategy = NumberClass override def summaryOpt = Some("Returns this number raised to the power of the given exponent") } object ToMethod extends MashMethod("to") { object Params { val End = Parameter( nameOpt = Some("end"), summaryOpt = Some("Final number in sequence (inclusive)")) val Step = Parameter( nameOpt = Some("step"), summaryOpt = Some("The number to increase by for each step of the sequence (default 1)"), defaultValueGeneratorOpt = Some(MashNumber(1))) } import Params._ val params = ParameterModel(End, Step) def call(target: MashValue, boundParams: BoundParams): MashList = { val start = target.asInstanceOf[MashNumber].asInt.getOrElse( throw EvaluatorException("Can only call this method on an integer, but was " + target)) val end = boundParams.validateInteger(End) val step = boundParams.validateInteger(Step) MashList(start.to(end, step).map(MashNumber(_))) } override def typeInferenceStrategy = Seq(NumberClass) override def summaryOpt = Some("Return a list of values from this number to the given end value (inclusive)") } object UntilMethod extends MashMethod("until") { object Params { val End = Parameter( nameOpt = Some("end"), summaryOpt = Some("Final number in sequence (exclusive)")) val Step = Parameter( nameOpt = Some("step"), summaryOpt = Some("The number to increase by for each step of the sequence (default 1)"), defaultValueGeneratorOpt = Some(MashNumber(1))) } import Params._ val params = ParameterModel(End, Step) def call(target: MashValue, boundParams: BoundParams): MashList = { val start = target.asInstanceOf[MashNumber].asInt.getOrElse( throw EvaluatorException("Can only call this method on an integer, but was " + target)) val end = boundParams.validateInteger(End) val step = boundParams.validateInteger(Step) MashList(start.until(end, step).map(MashNumber(_))) } override def typeInferenceStrategy = Seq(NumberClass) override def summaryOpt = Some("Return a list of values from this number to the given end value (exclusive)") } object TimesMethod extends MashMethod("times") { object Params { val Block = Parameter( nameOpt = Some("block"), summaryOpt = Some("Code to execute"), isLazy = true) } import Params._ val params = ParameterModel(Block) def call(target: MashValue, boundParams: BoundParams): MashList = { val f = boundParams(Block).asInstanceOf[MashFunction] val iterations = target.asInstanceOf[MashNumber].asInt.getOrElse( throw EvaluatorException("Can only call this method on an integer, but was " + target)) val results = for (n ← 1 to iterations) yield f.callNullary() MashList(results) } override def typeInferenceStrategy = new MethodTypeInferenceStrategy { def inferTypes(inferencer: Inferencer, targetTypeOpt: Option[Type], arguments: TypedArguments): Option[Type] = { val argBindings = params.bindTypes(arguments) argBindings.getType(Params.Block).map(_.seq) } } override def summaryOpt = Some("Run the given argument this amount of times") } object ToIntMethod extends MashMethod("toInt") { val params = ParameterModel.Empty def call(target: MashValue, boundParams: BoundParams): MashNumber = { target.asInstanceOf[MashNumber].modify(n ⇒ if (n < 0) math.ceil(n) else math.floor(n)) } override def typeInferenceStrategy = new MethodTypeInferenceStrategy { def inferTypes(inferencer: Inferencer, targetTypeOpt: Option[Type], arguments: TypedArguments): Option[Type] = targetTypeOpt } override def summaryOpt = Some("Convert number to an integer (rounding towards zero)") } object TagMethod extends MashMethod("tag") { val params = ParameterModel.Empty def call(target: MashValue, boundParams: BoundParams): MashValue = { target.asInstanceOf[MashNumber].tagClassOpt.getOrElse(MashNull) } override def typeInferenceStrategy = ClassClass override def summaryOpt = Some("This number's tagged type if any, else null") } object UntaggedMethod extends MashMethod("untagged") { val params = ParameterModel.Empty def call(target: MashValue, boundParams: BoundParams): MashNumber = { target.asInstanceOf[MashNumber].copy(tagClassOpt = None) } override def typeInferenceStrategy = NumberClass override def summaryOpt = Some("This number without any tag class") } object BytesMethod extends MashMethod("bytes") { val params = ParameterModel.Empty def call(target: MashValue, boundParams: BoundParams): MashNumber = { target.asInstanceOf[MashNumber].withTag(BytesClass) } override def typeInferenceStrategy = NumberClass taggedWith BytesClass override def summaryOpt = Some("This number of bytes") } object KbMethod extends MashMethod("kb") { val params = ParameterModel.Empty def call(target: MashValue, boundParams: BoundParams): MashNumber = { val n = target.asInstanceOf[MashNumber] MashNumber(n.n * 1024, BytesClass) } override def typeInferenceStrategy = NumberClass taggedWith BytesClass override def summaryOpt = Some("This number of kilobytes") } object MbMethod extends MashMethod("mb") { val params = ParameterModel.Empty def call(target: MashValue, boundParams: BoundParams): MashNumber = { val n = target.asInstanceOf[MashNumber] MashNumber(n.n * 1024 * 1024, BytesClass) } override def typeInferenceStrategy = NumberClass taggedWith BytesClass override def summaryOpt = Some("This number of megabytes") } object GbMethod extends MashMethod("gb") { val params = ParameterModel.Empty def call(target: MashValue, boundParams: BoundParams): MashNumber = { val n = target.asInstanceOf[MashNumber] MashNumber(n.n * 1024 * 1024 * 1024, BytesClass) } override def typeInferenceStrategy = NumberClass taggedWith BytesClass override def summaryOpt = Some("This number of gigabytes") } abstract class ChronoUnitMethod(name: String, klass: MashClass) extends MashMethod(name) { override def aliases = Seq(name.init) val params = ParameterModel.Empty def call(target: MashValue, boundParams: BoundParams): MashNumber = { target.asInstanceOf[MashNumber].withTag(klass) } override def typeInferenceStrategy = NumberClass taggedWith klass override def summaryOpt = Some("This number of " + name) } object MillisecondsMethod extends ChronoUnitMethod("milliseconds", MillisecondsClass) object SecondsMethod extends ChronoUnitMethod("seconds", SecondsClass) object MinutesMethod extends ChronoUnitMethod("minutes", MinutesClass) object HoursMethod extends ChronoUnitMethod("hours", HoursClass) object DaysMethod extends ChronoUnitMethod("days", DaysClass) object WeeksMethod extends ChronoUnitMethod("weeks", WeeksClass) object MonthsMethod extends ChronoUnitMethod("months", MonthsClass) object NegateMethod extends MashMethod("negate") { val params = ParameterModel.Empty def call(target: MashValue, boundParams: BoundParams): MashNumber = { val n = target.asInstanceOf[MashNumber] n.negate } override object typeInferenceStrategy extends MethodTypeInferenceStrategy { def inferTypes(inferencer: Inferencer, targetTypeOpt: Option[Type], arguments: TypedArguments): Option[Type] = targetTypeOpt } override def summaryOpt = Some("Negate this number") } override def summaryOpt = Some("A number") def taggedWith(klass: MashClass) = Type.Tagged(this, klass) override def parentOpt = Some(AnyClass) }
{ "content_hash": "ebff8f88c07777a878251433bc9c9299", "timestamp": "", "source": "github", "line_count": 302, "max_line_length": 118, "avg_line_length": 29.837748344370862, "alnum_prop": 0.7042503606702919, "repo_name": "mdr/mash", "id": "d7c37f762d9e45e09d67a7224ba8241ddbc49bbc", "size": "9015", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/com/github/mdr/mash/ns/core/NumberClass.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "1632923" } ], "symlink_target": "" }
exports.problem4 = function () { 'use strict'; var input = require('../test-inputs/problem4/1.json'); console.log('Input', input.join((', '))); input.sort(function (a, b) { return a.toString() < b.toString(); }); console.log('Largest possible number', input.join('')); };
{ "content_hash": "468fa09cae92e2070c219281a06ea7b9", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 57, "avg_line_length": 22.46153846153846, "alnum_prop": 0.6061643835616438, "repo_name": "d3xter666/the-5-programming-problems", "id": "fdf2628598ce85d479284d0e0d0b0b3349397932", "size": "292", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node/problem_4.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3315" } ], "symlink_target": "" }
#ifndef NFC_HELLO_WORLD2_H #define NFC_HELLO_WORLD2_H #include "NFComm/NFPluginModule/NFIPlugin.h" #include "NFComm/NFPluginModule/NFIPluginManager.h" class HelloWorld2 : public NFILogicModule { public: HelloWorld2(NFIPluginManager* p) { pPluginManager = p; } virtual bool Init(); virtual bool AfterInit(); virtual bool Execute(); virtual bool BeforeShut(); virtual bool Shut(); protected: int OnPropertyCallBackEvent(const NFGUID& self, const std::string& strProperty, const NFIDataList::TData& oldVarList, const NFIDataList::TData& newVarList); }; #endif
{ "content_hash": "6fc7417d391b9e27143b6e664fa6cac3", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 160, "avg_line_length": 20.25, "alnum_prop": 0.6774691358024691, "repo_name": "zh423328/NFServer", "id": "da0b3b0a4691f60e8b86fe188cec343796d010af", "size": "978", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tutorial/Tutorial2/HelloWorld2.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89080" }, { "name": "Assembly", "bytes": "138199" }, { "name": "Batchfile", "bytes": "7652" }, { "name": "C", "bytes": "1565372" }, { "name": "C#", "bytes": "1680643" }, { "name": "C++", "bytes": "2488970" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "1034" }, { "name": "DIGITAL Command Language", "bytes": "27303" }, { "name": "Groff", "bytes": "7559" }, { "name": "HTML", "bytes": "143733" }, { "name": "Java", "bytes": "49650" }, { "name": "Lua", "bytes": "18496" }, { "name": "M4", "bytes": "1572" }, { "name": "Makefile", "bytes": "262212" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "Pascal", "bytes": "70297" }, { "name": "Perl", "bytes": "3895" }, { "name": "Protocol Buffer", "bytes": "60983" }, { "name": "Python", "bytes": "2980" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "12909" }, { "name": "Smalltalk", "bytes": "2796" }, { "name": "XSLT", "bytes": "82915" } ], "symlink_target": "" }
<?php /* @WebProfiler/Profiler/base_js.html.twig */ class __TwigTemplate_e7980dfb8bff76e82b49ca15a592b08d8e457a6b35170d5e64a247a3d4b200aa 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()) { // line 1 echo "<script>/*<![CDATA[*/ Sfjs = (function() { \"use strict\"; var noop = function() {}, profilerStorageKey = 'sf2/profiler/', request = function(url, onSuccess, onError, payload, options) { var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); options = options || {}; options.maxTries = options.maxTries || 0; xhr.open(options.method || 'GET', url, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onreadystatechange = function(state) { if (4 !== xhr.readyState) { return null; } if (xhr.status == 404 && options.maxTries > 1) { setTimeout(function(){ options.maxTries--; request(url, onSuccess, onError, payload, options); }, 500); return null; } if (200 === xhr.status) { (onSuccess || noop)(xhr); } else { (onError || noop)(xhr); } }; xhr.send(payload || ''); }, hasClass = function(el, klass) { return el.className && el.className.match(new RegExp('\\\\b' + klass + '\\\\b')); }, removeClass = function(el, klass) { if (el.className) { el.className = el.className.replace(new RegExp('\\\\b' + klass + '\\\\b'), ' '); } }, addClass = function(el, klass) { if (!hasClass(el, klass)) { el.className += \" \" + klass; } }, getPreference = function(name) { if (!window.localStorage) { return null; } return localStorage.getItem(profilerStorageKey + name); }, setPreference = function(name, value) { if (!window.localStorage) { return null; } localStorage.setItem(profilerStorageKey + name, value); }, requestStack = [], renderAjaxRequests = function() { var requestCounter = document.querySelectorAll('.sf-toolbar-ajax-requests'); if (!requestCounter.length) { return; } var tbodies = document.querySelectorAll('.sf-toolbar-ajax-request-list'); var state = 'ok'; if (tbodies.length) { var tbody = tbodies[0]; var rows = document.createDocumentFragment(); if (requestStack.length) { for (var i = 0; i < requestStack.length; i++) { var request = requestStack[i]; var row = document.createElement('tr'); rows.appendChild(row); var methodCell = document.createElement('td'); methodCell.textContent = request.method; row.appendChild(methodCell); var pathCell = document.createElement('td'); pathCell.className = 'sf-ajax-request-url'; pathCell.textContent = request.url; pathCell.setAttribute('title', request.url); row.appendChild(pathCell); var durationCell = document.createElement('td'); durationCell.className = 'sf-ajax-request-duration'; if (request.duration) { durationCell.textContent = request.duration + \"ms\"; } else { durationCell.textContent = '-'; } row.appendChild(durationCell); row.appendChild(document.createTextNode(' ')); var profilerCell = document.createElement('td'); if (request.profilerUrl) { var profilerLink = document.createElement('a'); profilerLink.setAttribute('href', request.profilerUrl); profilerLink.textContent = request.profile; profilerCell.appendChild(profilerLink); } else { profilerCell.textContent = 'n/a'; } row.appendChild(profilerCell); var requestState = 'ok'; if (request.error) { requestState = 'error'; if (state != \"loading\" && i > requestStack.length - 4) { state = 'error'; } } else if (request.loading) { requestState = 'loading'; state = 'loading' } row.className = 'sf-ajax-request sf-ajax-request-' + requestState; } var infoSpan = document.querySelectorAll(\".sf-toolbar-ajax-info\")[0]; var children = Array.prototype.slice.call(tbody.children); for (var i = 0; i < children.length; i++) { tbody.removeChild(children[i]); } tbody.appendChild(rows); if (infoSpan) { var text = requestStack.length + ' call' + (requestStack.length > 1 ? 's' : ''); infoSpan.textContent = text; } } else { var cell = document.createElement('td'); cell.setAttribute('colspan', '4'); cell.textContent = \"No AJAX requests yet.\"; var row = document.createElement('tr'); row.appendChild(cell); tbody.appendChild(row); } } requestCounter[0].textContent = requestStack.length; var className = 'sf-toolbar-ajax-requests sf-toolbar-status'; if (state == 'ok') { className += ' sf-toolbar-status-green'; } else if (state == 'error') { className += ' sf-toolbar-status-red'; } else { className += ' sf-ajax-request-loading'; } requestCounter[0].className = className; }; var addEventListener; if (document.attachEvent) { addEventListener = function (element, eventName, callback) { element.attachEvent('on' + eventName, callback); }; } else { addEventListener = function (element, eventName, callback) { element.addEventListener(eventName, callback, false); }; } "; // line 186 if (array_key_exists("excluded_ajax_paths", $context)) { // line 187 echo " var proxied = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, url, async, user, pass) { var self = this; /* prevent logging AJAX calls to static and inline files, like templates */ if (url.substr(0, 1) === '/' && !url.match(new RegExp(\""; // line 193 echo twig_escape_filter($this->env, (isset($context["excluded_ajax_paths"]) ? $context["excluded_ajax_paths"] : $this->getContext($context, "excluded_ajax_paths")), "html", null, true); echo "\"))) { var stackElement = { loading: true, error: false, url: url, method: method, start: new Date() }; requestStack.push(stackElement); addEventListener(this, 'readystatechange', function() { if (self.readyState == 4) { stackElement.duration = new Date() - stackElement.start; stackElement.loading = false; stackElement.error = self.status < 200 || self.status >= 400; stackElement.profile = self.getResponseHeader(\"X-Debug-Token\"); stackElement.profilerUrl = self.getResponseHeader(\"X-Debug-Token-Link\"); Sfjs.renderAjaxRequests(); } }); Sfjs.renderAjaxRequests(); } proxied.apply(this, Array.prototype.slice.call(arguments)); }; "; } // line 222 echo " return { hasClass: hasClass, removeClass: removeClass, addClass: addClass, getPreference: getPreference, setPreference: setPreference, addEventListener: addEventListener, request: request, renderAjaxRequests: renderAjaxRequests, load: function(selector, url, onSuccess, onError, options) { var el = document.getElementById(selector); if (el && el.getAttribute('data-sfurl') !== url) { request( url, function(xhr) { el.innerHTML = xhr.responseText; el.setAttribute('data-sfurl', url); removeClass(el, 'loading'); (onSuccess || noop)(xhr, el); }, function(xhr) { (onError || noop)(xhr, el); }, '', options ); } return this; }, toggle: function(selector, elOn, elOff) { var i, style, tmp = elOn.style.display, el = document.getElementById(selector); elOn.style.display = elOff.style.display; elOff.style.display = tmp; if (el) { el.style.display = 'none' === tmp ? 'none' : 'block'; } return this; } } })(); /*]]>*/</script> "; } public function getTemplateName() { return "@WebProfiler/Profiler/base_js.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 248 => 222, 216 => 193, 208 => 187, 206 => 186, 19 => 1,); } }
{ "content_hash": "accaa677207166d3aa8983fcfa7a26b2", "timestamp": "", "source": "github", "line_count": 322, "max_line_length": 197, "avg_line_length": 37.02795031055901, "alnum_prop": 0.4314350415163969, "repo_name": "novikovm/Store", "id": "87eb58ce6f9be9b0c2501bbea64a2cba081e7680", "size": "11923", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/cache/dev/twig/e7/98/0dfb8bff76e82b49ca15a592b08d8e457a6b35170d5e64a247a3d4b200aa.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3073" }, { "name": "CSS", "bytes": "792" }, { "name": "JavaScript", "bytes": "2824" }, { "name": "PHP", "bytes": "77153" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Code Coverage for C:\xampp\htdocs\bookManagerApp\src/BookManagerApp/ManagerBundle/DataFixtures/ORM</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="../../../../css/bootstrap.min.css" rel="stylesheet"> <link href="../../../../css/style.css" rel="stylesheet"> <!--[if lt IE 9]> <script src="../../../../js/html5shiv.min.js"></script> <script src="../../../../js/respond.min.js"></script> <![endif]--> </head> <body> <header> <div class="container"> <div class="row"> <div class="col-md-12"> <ol class="breadcrumb"> <li><a href="../../../../index.html">C:\xampp\htdocs\bookManagerApp\src</a></li> <li><a href="../../../index.html">BookManagerApp</a></li> <li><a href="../../index.html">ManagerBundle</a></li> <li><a href="../index.html">DataFixtures</a></li> <li class="active">ORM</li> <li>(<a href="dashboard.html">Dashboard</a>)</li> </ol> </div> </div> </div> </header> <div class="container"> <table class="table table-bordered"> <thead> <tr> <td>&nbsp;</td> <td colspan="9"><div align="center"><strong>Code Coverage</strong></div></td> </tr> <tr> <td>&nbsp;</td> <td colspan="3"><div align="center"><strong>Lines</strong></div></td> <td colspan="3"><div align="center"><strong>Functions and Methods</strong></div></td> <td colspan="3"><div align="center"><strong>Classes and Traits</strong></div></td> </tr> </thead> <tbody> <tr> <td class="success">Total</td> <td class="success big"> <div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%"> <span class="sr-only">100.00% covered (success)</span> </div> </div> </td> <td class="success small"><div align="right">100.00%</div></td> <td class="success small"><div align="right">7&nbsp;/&nbsp;7</div></td> <td class="success big"> <div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%"> <span class="sr-only">100.00% covered (success)</span> </div> </div> </td> <td class="success small"><div align="right">100.00%</div></td> <td class="success small"><div align="right">1&nbsp;/&nbsp;1</div></td> <td class="success big"> <div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%"> <span class="sr-only">100.00% covered (success)</span> </div> </div> </td> <td class="success small"><div align="right">100.00%</div></td> <td class="success small"><div align="right">1&nbsp;/&nbsp;1</div></td> </tr> <tr> <td class="success"><span class="glyphicon glyphicon-file"></span> <a href="LoadBookData.php.html">LoadBookData.php</a></td> <td class="success big"> <div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%"> <span class="sr-only">100.00% covered (success)</span> </div> </div> </td> <td class="success small"><div align="right">100.00%</div></td> <td class="success small"><div align="right">7&nbsp;/&nbsp;7</div></td> <td class="success big"> <div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%"> <span class="sr-only">100.00% covered (success)</span> </div> </div> </td> <td class="success small"><div align="right">100.00%</div></td> <td class="success small"><div align="right">1&nbsp;/&nbsp;1</div></td> <td class="success big"> <div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%"> <span class="sr-only">100.00% covered (success)</span> </div> </div> </td> <td class="success small"><div align="right">100.00%</div></td> <td class="success small"><div align="right">1&nbsp;/&nbsp;1</div></td> </tr> </tbody> </table> <footer> <hr/> <h4>Legend</h4> <p> <span class="danger"><strong>Low</strong>: 0% to 50%</span> <span class="warning"><strong>Medium</strong>: 50% to 90%</span> <span class="success"><strong>High</strong>: 90% to 100%</span> </p> <p> <small>Generated by <a href="http://github.com/sebastianbergmann/php-code-coverage" target="_top">PHP_CodeCoverage 2.1.4</a> using <a href="http://php.net/" target="_top">PHP 5.6.3</a> and <a href="http://phpunit.de/">PHPUnit 4.7.2</a> at Mon Jun 8 3:37:16 CEST 2015.</small> </p> </footer> </div> <script src="../../../../js/jquery.min.js" type="text/javascript"></script> <script src="../../../../js/bootstrap.min.js" type="text/javascript"></script> <script src="../../../../js/holder.min.js" type="text/javascript"></script> </body> </html>
{ "content_hash": "955c3310157b5652f5e56657f4523e8e", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 280, "avg_line_length": 44.86178861788618, "alnum_prop": 0.5839072127582458, "repo_name": "jsuman/bookManagerApp", "id": "d5d512673af28d250a9e13e6a1bbb26e7cb36eb3", "size": "5518", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "coverage-report/BookManagerApp/ManagerBundle/DataFixtures/ORM/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3297" }, { "name": "CSS", "bytes": "3420" }, { "name": "HTML", "bytes": "436721" }, { "name": "PHP", "bytes": "58253" } ], "symlink_target": "" }
using System; using System.Reactive; namespace Qactive.Tests.WebSockets { internal static class WebSocketTestService { public static readonly QbservableServiceOptions DefaultOptions = TestService.DefaultOptions; public static readonly QbservableServiceOptions UnrestrictedOptions = TestService.UnrestrictedOptions; /// <summary> /// Same as <see cref="UnrestrictedOptions"/> except that <see cref="QbservableServiceOptions.EnableDuplex"/> is false. /// </summary> public static readonly QbservableServiceOptions UnrestrictedExpressionsOptions = TestService.UnrestrictedExpressionsOptions; public static WebSocketTestService<TSource> Create<TSource>(params Notification<TSource>[] notifications) => new WebSocketTestService<TSource>(DefaultOptions, (Type[])null, notifications); public static WebSocketTestService<TSource> Create<TSource>(Type[] knownTypes, params Notification<TSource>[] notifications) => new WebSocketTestService<TSource>(DefaultOptions, knownTypes, notifications); public static WebSocketTestService<TSource> Create<TSource>(QbservableServiceOptions options, params Notification<TSource>[] notifications) => new WebSocketTestService<TSource>(options, (Type[])null, notifications); public static WebSocketTestService<TSource> Create<TSource>(QbservableServiceOptions options, Type[] knownTypes, params Notification<TSource>[] notifications) => new WebSocketTestService<TSource>(options, knownTypes, notifications); public static WebSocketTestService<TSource> Create<TSource>(IObservable<TSource> source) => new WebSocketTestService<TSource>(DefaultOptions, (Type[])null, source); public static WebSocketTestService<TSource> Create<TSource>(Type[] knownTypes, IObservable<TSource> source) => new WebSocketTestService<TSource>(DefaultOptions, knownTypes, source); public static WebSocketTestService<TSource> Create<TSource>(QbservableServiceOptions options, IObservable<TSource> source) => new WebSocketTestService<TSource>(options, (Type[])null, source); public static WebSocketTestService<TSource> Create<TSource>(QbservableServiceOptions options, Type[] knownTypes, IObservable<TSource> source) => new WebSocketTestService<TSource>(options, knownTypes, source); } }
{ "content_hash": "59ec7dbc7052c18eef72ab768ec27ee1", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 162, "avg_line_length": 57.65, "alnum_prop": 0.7862098872506504, "repo_name": "RxDave/Qactive", "id": "0f5744488afa0a020afd2290011669482b17ef6e", "size": "2308", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Testing/Qactive.Tests/WebSockets/WebSocketTestService.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "720128" }, { "name": "Smalltalk", "bytes": "13108" } ], "symlink_target": "" }
namespace TheAsocialNetwork.UI.UWP { using System; using TheAsocialNetwork.UI.UWP.Views; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml; using Windows.UI.Xaml.Navigation; using Models; using Parse; using TheAsocialNetwork.UI.UWP.Models.Parse; using TheAsocialNetwork.UI.UWP.Models.SqLite; using TheAsocialNetwork.UI.UWP.Services.Data.SqLite; /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += this.OnSuspending; this.InitParse(); this.InitSqLite(); } private void InitParse() { ParseObject.RegisterSubclass<LocationParse>(); ParseObject.RegisterSubclass<AvatarParse>(); ParseObject.RegisterSubclass<VideoParse>(); ParseObject.RegisterSubclass<ImageParse>(); ParseObject.RegisterSubclass<PostParse>(); ParseUser.RegisterSubclass<UserParse>(); ParseClient.Initialize("bDYtk2EzONdRX8bmH47R58R1jNmrcaQW0lXoJNpu", "ckfGVINo8UNIWJ5CRpC0jgzpL38AWnEayXbIwp4S"); } private async void InitSqLite() { var sqliteService = new SqlConnectionService(); var connection = sqliteService.GetDbConnectionAsync(); await connection.CreateTableAsync<UserSql>(); await connection.CreateTableAsync<PostSql>(); await connection.CreateTableAsync<LocationSql>(); await connection.CreateTableAsync<VideoSql>(); await connection.CreateTableAsync<AvatarSql>(); await connection.CreateTableAsync<ImageSql>(); await connection.CreateTableAsync<ImageInfoSql>(); } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { // This just gets in the way. //this.DebugSettings.EnableFrameRateCounter = true; } #endif AppShell shell = Window.Current.Content as AppShell; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (shell == null) { // Create a AppShell to act as the navigation context and navigate to the first page shell = new AppShell(); // Set the default language shell.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; shell.AppFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } } // Place our app shell in the current Window Window.Current.Content = shell; if (shell.AppFrame.Content == null) { // If the parse user is not logged in - go to the login/register page if (ParseUser.CurrentUser == null) { shell.AppFrame.Navigate(typeof(IdentityPage), e.Arguments, new Windows.UI.Xaml.Media.Animation.SuppressNavigationTransitionInfo()); } // When the navigation stack isn't restored, navigate to the first page // suppressing the initial entrance animation. shell.AppFrame.Navigate(typeof(LandingPage), e.Arguments, new Windows.UI.Xaml.Media.Animation.SuppressNavigationTransitionInfo()); } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
{ "content_hash": "4ad900de88999f0b941ee937b91b8cc3", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 151, "avg_line_length": 39.8936170212766, "alnum_prop": 0.6172444444444445, "repo_name": "Monk-TA/The-Asocial-Network", "id": "3c3dcbdfcecde60e2027615e74fdb011985e78c9", "size": "5627", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/UI/TheAsocialNetwork.UI.UWP/App.xaml.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "141980" } ], "symlink_target": "" }
class Howl < ActiveRecord::Base acts_as_votable validates :image, presence: true validates :caption, length: { minimum: 3, maximum: 300 } validates :user_id, presence: true has_attached_file :image, styles: { :medium => "640x" } validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/ belongs_to :user has_many :scents, dependent: :destroy has_many :barkbacks, dependent: :destroy scope :of_followed_users, -> (following_users) { where user_id: following_users } def scents_attributes=(scents_attributes) scents_attributes.values.each do |attr| self.scents.build(attr) end end end
{ "content_hash": "6ab152240f402f9a39075bb8621c88cc", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 83, "avg_line_length": 29.09090909090909, "alnum_prop": 0.7, "repo_name": "lukeymac/doggo", "id": "1f21c12d62dc739b169e3483c10296a8719485d6", "size": "640", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/howl.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7067" }, { "name": "CoffeeScript", "bytes": "633" }, { "name": "HTML", "bytes": "26734" }, { "name": "JavaScript", "bytes": "1507" }, { "name": "Ruby", "bytes": "73105" } ], "symlink_target": "" }
external help file: PSDataConduIT-help.xml Module Name: PSDataConduIT online version: https://github.com/erwindevreugd/PSDataConduIT schema: 2.0.0 --- # Get-Badge ## SYNOPSIS Gets a badge. ## SYNTAX ``` Get-Badge [[-Server] <String>] [[-Credential] <PSCredential>] [-BadgeID <Int64>] [-BadgeKey <Int32>] [-PersonID <Int32>] [<CommonParameters>] ``` ## DESCRIPTION Gets all badges or a single badge if a badge id or badgekey is specified. If the result returns null, try the parameter "-Verbose" to get more details. ## EXAMPLES ### EXAMPLE 1 ``` Get-Badge ``` ## PARAMETERS ### -Server The name of the server where the DataConduIT service is running or localhost. ```yaml Type: String Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: $Script:Server Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Credential The credentials used to authenticate the user to the DataConduIT service. ```yaml Type: PSCredential Parameter Sets: (All) Aliases: Required: False Position: 2 Default value: $Script:Credential Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -BadgeID Specifies the badge id of the badge to get. ```yaml Type: Int64 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 0 Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -BadgeKey Specifies the badge key of the badge to get. ```yaml Type: Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 0 Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PersonID Specifies the person id for which to get the badge(s). ```yaml Type: Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 0 Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS ## NOTES ## RELATED LINKS
{ "content_hash": "777bfb8f16f790f8b7da9e9d0be27fb9", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 216, "avg_line_length": 19.466101694915253, "alnum_prop": 0.7483674357858076, "repo_name": "erwindevreugd/PSDataConduIT", "id": "f199ed60f6df8321d8debea8a1b9d26c741eb7ce", "size": "2301", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Docs/en-US/Get-Badge.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "171" }, { "name": "PowerShell", "bytes": "502426" } ], "symlink_target": "" }
using namespace hsm; class Character { public: Character(); void Update(); bool mJump; private: friend struct CharacterStates; StateMachine mStateMachine; }; struct CharacterStates { struct BaseState : StateWithOwner<Character> { }; struct Alive : BaseState { virtual Transition GetTransition() { return InnerEntryTransition<Stand>(); } }; struct Stand : BaseState { virtual Transition GetTransition() { if (Owner().mJump) { Owner().mJump = false; return SiblingTransition<Jump>(); } return NoTransition(); } }; struct Jump : BaseState { int mJumpValue1; float mJumpValue2; bool mJumpValue3; Jump() : mJumpValue1(0), mJumpValue2(0.0f), mJumpValue3(false) { } virtual Transition GetTransition() { if (IsInInnerState<Jump_Done>()) return SiblingTransition<Stand>(); return InnerEntryTransition<Jump_Up>(); } }; struct Jump_Up : BaseState { virtual void OnEnter() { GetOuterState<Jump>()->mJumpValue1 = 1; GetOuterState<Jump>()->mJumpValue2 = 2.0f; GetOuterState<Jump>()->mJumpValue3 = true; } virtual Transition GetTransition() { return SiblingTransition<Jump_Down>(); } }; struct Jump_Down : BaseState { virtual void OnEnter() { GetOuterState<Jump>()->mJumpValue1 = 2; GetOuterState<Jump>()->mJumpValue2 = 4.0f; GetOuterState<Jump>()->mJumpValue3 = false; } virtual Transition GetTransition() { return SiblingTransition<Jump_Done>(); } }; struct Jump_Done : BaseState { }; }; Character::Character() : mJump(false) { mStateMachine.Initialize<CharacterStates::Alive>(this); mStateMachine.SetDebugInfo("TestHsm", TraceLevel::Basic); } void Character::Update() { // Update state machine mStateMachine.ProcessStateTransitions(); mStateMachine.UpdateStates(); } int main() { Character character; character.Update(); character.mJump = true; character.Update(); }
{ "content_hash": "f36bf1c197897fb439196d95851307a7", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 68, "avg_line_length": 16.551724137931036, "alnum_prop": 0.6838541666666667, "repo_name": "amaiorano/hsm", "id": "846614303d73dc120a9b39a990f046aed4b67a91", "size": "1972", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/hsm_book_samples/source/ch4/cluster_root_state_data_1.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "42830" }, { "name": "Python", "bytes": "26175" } ], "symlink_target": "" }
<?php namespace app\models; use Yii; use yii\base\Model; /** * LoginForm is the model behind the login form. */ class LoginForm extends Model { public $username; public $password; public $rememberMe = true; private $_user = false; /** * @return array the validation rules. */ public function rules() { return [ // username and password are both required [['username', 'password'], 'required'], // rememberMe must be a boolean value ['rememberMe', 'boolean'], // password is validated by validatePassword() ['password', 'validatePassword'], ]; } /** * Validates the password. * This method serves as the inline validation for password. * * @param string $attribute the attribute currently being validated * @param array $params the additional name-value pairs given in the rule */ public function validatePassword($attribute, $params) { if (!$this->hasErrors()) { $user = $this->getUser(); if (!$user || !$user->validatePassword($this->password)) { $this->addError($attribute, 'Incorrect username or password.'); } } } /** * Logs in a user using the provided username and password. * @return boolean whether the user is logged in successfully */ public function login() { if ($this->validate()) { return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0); } else { return false; } } /** * Finds user by [[username]] * * @return UserModel|null */ public function getUser() { if ($this->_user === false) { $this->_user = UserModel::findByLogin($this->username); } return $this->_user; } }
{ "content_hash": "acc4fc7f88020172c1aaadb41f4c578d", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 96, "avg_line_length": 24.58974358974359, "alnum_prop": 0.5500521376433786, "repo_name": "MaximRad/Store-Notebook", "id": "139c492052fd01740dec0775d16801c6d3adc8a8", "size": "1918", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "models/LoginForm.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1364" }, { "name": "PHP", "bytes": "163596" }, { "name": "Shell", "bytes": "1041" } ], "symlink_target": "" }
@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set SOURCEDIR=. set BUILDDIR=_build set SPHINXPROJ=AWSWebStacks if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% :end popd
{ "content_hash": "2d14b37917d0bf9c5cce3f816cfd56e5", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 74, "avg_line_length": 21.666666666666668, "alnum_prop": 0.735897435897436, "repo_name": "caktus/aws-web-stacks", "id": "d4bcea569509ed4783390a03a998a8ee17f8c317", "size": "780", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "docs/make.bat", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "1309" }, { "name": "Python", "bytes": "140766" } ], "symlink_target": "" }
package healthcheck import ( log "gopkg.in/inconshreveable/log15.v2" "net/url" "os/exec" "strings" ) type HealthCheck struct { Script string Log log.Logger Host string } func New(l log.Logger, script string, host string) *HealthCheck { u, _ := url.Parse(host) ip_host := strings.Split(u.Host, ":")[0] return &HealthCheck{Log: l, Script: script, Host: ip_host} } func (h *HealthCheck) Check() bool { script := strings.Split(h.Script, " ") for i, p := range script { if p == "$HOST" { script[i] = h.Host } } cmd := exec.Command(script[0], script...) cmd.Env = []string{"HOST=" + h.Host} h.Log.Info("[ ] Running health check: " + strings.Join(script, " ")) out, err := cmd.CombinedOutput() if err != nil { h.Log.Error("[F] Health check failed") h.Log.Error(err.Error()) h.Log.Error(string(out)) return false } else { h.Log.Info("[P] Health check passed") return true } }
{ "content_hash": "87a15e28115441784f6b6507cb1d4cb0", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 69, "avg_line_length": 21.80952380952381, "alnum_prop": 0.6331877729257642, "repo_name": "ychaim/docker-conductor", "id": "3126039a289508c7cb4e87cfad330d2f63b5986b", "size": "916", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "healthcheck/healthcheck.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "6511" } ], "symlink_target": "" }
namespace ash { namespace { // Defines a |SessionControllerClient| that is used to create and destroy the // test lock screen widget. class LockScreenSessionControllerClient : public TestSessionControllerClient { public: LockScreenSessionControllerClient(SessionControllerImpl* controller, TestPrefServiceProvider* prefs_provider) : TestSessionControllerClient(controller, prefs_provider) { InitializeAndSetClient(); CreatePredefinedUserSessions(1); } LockScreenSessionControllerClient(const LockScreenSessionControllerClient&) = delete; LockScreenSessionControllerClient& operator=( const LockScreenSessionControllerClient&) = delete; ~LockScreenSessionControllerClient() override = default; // TestSessionControllerClient: void RequestLockScreen() override { TestSessionControllerClient::RequestLockScreen(); CreateLockScreen(); Shelf::UpdateShelfVisibility(); } void UnlockScreen() override { TestSessionControllerClient::UnlockScreen(); if (lock_screen_widget_.get()) { lock_screen_widget_->Close(); lock_screen_widget_.reset(nullptr); } Shelf::UpdateShelfVisibility(); } private: void CreateLockScreen() { auto lock_view = std::make_unique<views::View>(); lock_screen_widget_ = std::make_unique<views::Widget>(); views::Widget::InitParams params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); gfx::Size ps = lock_view->GetPreferredSize(); gfx::Size root_window_size = Shell::GetPrimaryRootWindow()->bounds().size(); params.bounds = gfx::Rect((root_window_size.width() - ps.width()) / 2, (root_window_size.height() - ps.height()) / 2, ps.width(), ps.height()); params.parent = Shell::GetContainer(Shell::GetPrimaryRootWindow(), kShellWindowId_LockScreenContainer); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; lock_screen_widget_->Init(std::move(params)); lock_screen_widget_->SetContentsView(std::move(lock_view)); lock_screen_widget_->Show(); lock_screen_widget_->GetNativeView()->SetName("LockView"); lock_screen_widget_->GetNativeView()->Focus(); } std::unique_ptr<views::Widget> lock_screen_widget_; }; //////////////////////////////////////////////////////////////////////////////// // Defines a class that will be used to test the correct behavior of // |AshFocusRules| when locking and unlocking the screen. class LockScreenAshFocusRulesTest : public AshTestBase { public: LockScreenAshFocusRulesTest() = default; LockScreenAshFocusRulesTest(const LockScreenAshFocusRulesTest&) = delete; LockScreenAshFocusRulesTest& operator=(const LockScreenAshFocusRulesTest&) = delete; ~LockScreenAshFocusRulesTest() override = default; void SetUp() override { AshTestBase::SetUp(); ash_test_helper()->set_test_session_controller_client( std::make_unique<LockScreenSessionControllerClient>( Shell::Get()->session_controller(), ash_test_helper()->prefs_provider())); } aura::Window* CreateWindowInActiveDesk() { return CreateWindowInContainer(desks_util::GetActiveDeskContainerId()); } aura::Window* CreateWindowInAppListContainer() { return CreateWindowInContainer(kShellWindowId_AppListContainer); } aura::Window* CreateWindowInAlwaysOnTopContainer() { aura::Window* window = CreateWindowInContainer(kShellWindowId_AlwaysOnTopContainer); window->SetProperty(aura::client::kZOrderingKey, ui::ZOrderLevel::kFloatingWindow); return window; } aura::Window* CreateWindowInLockContainer() { return CreateWindowInContainer(kShellWindowId_LockScreenContainer); } aura::Window* CreateWindowInShelfContainer() { return CreateWindowInContainer(kShellWindowId_ShelfContainer); } aura::Window* CreateWindowInLockSystemModalContainer() { aura::Window* window = CreateWindowInContainer(kShellWindowId_LockSystemModalContainer); window->SetProperty(aura::client::kModalKey, ui::MODAL_TYPE_SYSTEM); return window; } aura::Window* CreateWindowInSystemModalContainer() { aura::Window* window = CreateWindowInContainer(kShellWindowId_SystemModalContainer); window->SetProperty(aura::client::kModalKey, ui::MODAL_TYPE_SYSTEM); return window; } private: aura::Window* CreateWindowInContainer(int container_id) { aura::Window* root_window = Shell::GetPrimaryRootWindow(); aura::Window* container = Shell::GetContainer(root_window, container_id); aura::Window* window = new aura::Window(nullptr); window->SetId(0); window->SetType(aura::client::WINDOW_TYPE_NORMAL); window->Init(ui::LAYER_TEXTURED); window->Show(); window->SetProperty(aura::client::kResizeBehaviorKey, aura::client::kResizeBehaviorCanMaximize | aura::client::kResizeBehaviorCanMinimize | aura::client::kResizeBehaviorCanResize); container->AddChild(window); return window; } std::unique_ptr<LockScreenSessionControllerClient> session_controller_client_; }; } // namespace // Verifies focus is returned (after unlocking the screen) to the most recent // window that had it before locking the screen. TEST_F(LockScreenAshFocusRulesTest, RegainFocusAfterUnlock) { std::unique_ptr<aura::Window> normal_window(CreateWindowInActiveDesk()); std::unique_ptr<aura::Window> always_on_top_window( CreateWindowInAlwaysOnTopContainer()); wm::ActivateWindow(always_on_top_window.get()); wm::ActivateWindow(normal_window.get()); EXPECT_TRUE(wm::IsActiveWindow(normal_window.get())); EXPECT_TRUE(normal_window->IsVisible()); EXPECT_TRUE(always_on_top_window->IsVisible()); EXPECT_TRUE(normal_window->HasFocus()); EXPECT_FALSE(always_on_top_window->HasFocus()); WindowState* normal_window_state = WindowState::Get(normal_window.get()); WindowState* always_on_top_window_state = WindowState::Get(always_on_top_window.get()); EXPECT_TRUE(normal_window_state->CanActivate()); EXPECT_TRUE(always_on_top_window_state->CanActivate()); BlockUserSession(BLOCKED_BY_LOCK_SCREEN); EXPECT_TRUE(Shell::Get()->session_controller()->IsScreenLocked()); EXPECT_FALSE(normal_window->HasFocus()); EXPECT_FALSE(always_on_top_window->HasFocus()); EXPECT_FALSE(normal_window_state->IsMinimized()); EXPECT_FALSE(always_on_top_window_state->IsMinimized()); EXPECT_FALSE(normal_window_state->CanActivate()); EXPECT_FALSE(always_on_top_window_state->CanActivate()); UnblockUserSession(); EXPECT_FALSE(Shell::Get()->session_controller()->IsScreenLocked()); EXPECT_FALSE(normal_window_state->IsMinimized()); EXPECT_FALSE(always_on_top_window_state->IsMinimized()); EXPECT_TRUE(normal_window_state->CanActivate()); EXPECT_TRUE(always_on_top_window_state->CanActivate()); EXPECT_FALSE(always_on_top_window->HasFocus()); EXPECT_TRUE(normal_window->HasFocus()); } // Tests that if a widget has a view which should be initially focused, this // view doesn't get focused if the widget shows behind the lock screen. TEST_F(LockScreenAshFocusRulesTest, PreventFocusChangeWithLockScreenPresent) { BlockUserSession(BLOCKED_BY_LOCK_SCREEN); EXPECT_TRUE(Shell::Get()->session_controller()->IsScreenLocked()); views::test::TestInitialFocusWidgetDelegate delegate(GetContext()); EXPECT_FALSE(delegate.view()->HasFocus()); delegate.GetWidget()->Show(); EXPECT_FALSE(delegate.GetWidget()->IsActive()); EXPECT_FALSE(delegate.view()->HasFocus()); UnblockUserSession(); EXPECT_FALSE(Shell::Get()->session_controller()->IsScreenLocked()); EXPECT_TRUE(delegate.GetWidget()->IsActive()); EXPECT_TRUE(delegate.view()->HasFocus()); } // Verifies that a window in lock container cannot be activated if a lock // system modal window is shown. TEST_F(LockScreenAshFocusRulesTest, PreventLockScreenActivationUnderLockSystemModalWindow) { // System modal window - given that it's not lock system modal, it should // have no impact on activation of windows while user session is locked. std::unique_ptr<aura::Window> system_modal_window( CreateWindowInSystemModalContainer()); EXPECT_TRUE(wm::IsActiveWindow(system_modal_window.get())); BlockUserSession(BLOCKED_BY_LOCK_SCREEN); EXPECT_TRUE(Shell::Get()->session_controller()->IsScreenLocked()); std::unique_ptr<aura::Window> lock_window(CreateWindowInLockContainer()); std::unique_ptr<aura::Window> lock_system_modal_window( CreateWindowInLockSystemModalContainer()); EXPECT_TRUE(wm::IsActiveWindow(lock_system_modal_window.get())); // Try to activate a lock container window - it should not succeed if a lock // system modal dialog is present. wm::ActivateWindow(lock_window.get()); EXPECT_TRUE(wm::IsActiveWindow(lock_system_modal_window.get())); lock_system_modal_window.reset(); // Activating lock window should succeed after system modal widnow is closed. wm::ActivateWindow(lock_window.get()); EXPECT_TRUE(wm::IsActiveWindow(lock_window.get())); lock_window.reset(); EXPECT_FALSE(wm::IsActiveWindow(system_modal_window.get())); UnblockUserSession(); // Upon unlocking the session, the system modal window should be reactivated. EXPECT_TRUE(wm::IsActiveWindow(system_modal_window.get())); } // Verifies that the shelf can be activated in login/lock screen even if there // is a lock system modal present. TEST_F(LockScreenAshFocusRulesTest, AllowShelfActivationWithLockSystemModalWindow) { BlockUserSession(BLOCKED_BY_LOCK_SCREEN); EXPECT_TRUE(Shell::Get()->session_controller()->IsScreenLocked()); std::unique_ptr<aura::Window> lock_window(CreateWindowInLockContainer()); std::unique_ptr<aura::Window> lock_shelf_window( CreateWindowInShelfContainer()); std::unique_ptr<aura::Window> lock_system_modal_window( CreateWindowInLockSystemModalContainer()); EXPECT_TRUE(wm::IsActiveWindow(lock_system_modal_window.get())); wm::ActivateWindow(lock_shelf_window.get()); EXPECT_TRUE(wm::IsActiveWindow(lock_shelf_window.get())); } // Simulates a transient child dialog of the applist when it gets closed and // loses focus, the focus should be returned to the applist transient parent, // not to another window in the MRU list. https://crbug.com/950469. TEST_F(LockScreenAshFocusRulesTest, TransientChildLosingFocus) { std::unique_ptr<aura::Window> normal_window(CreateWindowInActiveDesk()); std::unique_ptr<aura::Window> transient_parent( CreateWindowInAppListContainer()); std::unique_ptr<aura::Window> transient_child( CreateWindowInAppListContainer()); ::wm::AddTransientChild(transient_parent.get(), transient_child.get()); wm::ActivateWindow(transient_child.get()); EXPECT_TRUE(wm::IsActiveWindow(transient_child.get())); transient_child->Hide(); EXPECT_TRUE(wm::IsActiveWindow(transient_parent.get())); } } // namespace ash
{ "content_hash": "6253e8d9113570c9616bd31f436464ae", "timestamp": "", "source": "github", "line_count": 283, "max_line_length": 80, "avg_line_length": 39.081272084805654, "alnum_prop": 0.7183544303797469, "repo_name": "chromium/chromium", "id": "b1e32b7b17d012e1e6378d83594be3e6785da854", "size": "11992", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "ash/wm/ash_focus_rules_unittest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package rx.reactivestreams; import java.io.IOException; import org.reactivestreams.Publisher; import org.reactivestreams.tck.*; import org.testng.annotations.Test; import rx.*; import rx.schedulers.Schedulers; @Test public class TckCompletableAsyncConversionTest extends PublisherVerification<Long> { public TckCompletableAsyncConversionTest() { super(new TestEnvironment(300L)); } @Override public Publisher<Long> createPublisher(long elements) { return RxReactiveStreams.toPublisher(Completable.complete().observeOn(Schedulers.computation())); } @Override public long maxElementsFromPublisher() { return 0L; } @Override public Publisher<Long> createFailedPublisher() { return RxReactiveStreams.toPublisher(Completable.error(new IOException()).observeOn(Schedulers.computation())); } }
{ "content_hash": "5ee0a3a770b20ef8c505ad464ad6c9d9", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 119, "avg_line_length": 24.38888888888889, "alnum_prop": 0.7380410022779044, "repo_name": "ReactiveX/RxJavaReactiveStreams", "id": "195472b176c415d7c6ea62195b32ea00614af5df", "size": "1471", "binary": false, "copies": "1", "ref": "refs/heads/1.x", "path": "rxjava-reactive-streams/src/test/java/rx/reactivestreams/TckCompletableAsyncConversionTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "66881" }, { "name": "Shell", "bytes": "1136" } ], "symlink_target": "" }
package org.apache.calcite.adapter.enumerable; import org.apache.calcite.adapter.java.JavaTypeFactory; import org.apache.calcite.linq4j.tree.BlockBuilder; import org.apache.calcite.linq4j.tree.Expression; import org.apache.calcite.linq4j.tree.Expressions; import org.apache.calcite.linq4j.tree.Primitive; import org.apache.calcite.plan.RelOptCluster; import org.apache.calcite.plan.RelTraitSet; import org.apache.calcite.rel.RelCollationTraitDef; import org.apache.calcite.rel.RelDistributionTraitDef; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.core.Values; import org.apache.calcite.rel.metadata.RelMdCollation; import org.apache.calcite.rel.metadata.RelMdDistribution; import org.apache.calcite.rel.metadata.RelMetadataQuery; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeField; import org.apache.calcite.rex.RexLiteral; import org.apache.calcite.util.BuiltInMethod; import org.apache.calcite.util.Pair; import com.google.common.collect.ImmutableList; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; /** Implementation of {@link org.apache.calcite.rel.core.Values} in * {@link org.apache.calcite.adapter.enumerable.EnumerableConvention enumerable calling convention}. */ public class EnumerableValues extends Values implements EnumerableRel { /** Creates an EnumerableValues. */ private EnumerableValues(RelOptCluster cluster, RelDataType rowType, ImmutableList<ImmutableList<RexLiteral>> tuples, RelTraitSet traitSet) { super(cluster, rowType, tuples, traitSet); } /** Creates an EnumerableValues. */ public static EnumerableValues create(RelOptCluster cluster, final RelDataType rowType, final ImmutableList<ImmutableList<RexLiteral>> tuples) { final RelMetadataQuery mq = cluster.getMetadataQuery(); final RelTraitSet traitSet = cluster.traitSetOf(EnumerableConvention.INSTANCE) .replaceIfs(RelCollationTraitDef.INSTANCE, () -> RelMdCollation.values(mq, rowType, tuples)) .replaceIf(RelDistributionTraitDef.INSTANCE, () -> RelMdDistribution.values(rowType, tuples)); return new EnumerableValues(cluster, rowType, tuples, traitSet); } @Override public RelNode copy(RelTraitSet traitSet, List<RelNode> inputs) { assert inputs.isEmpty(); return create(getCluster(), rowType, tuples); } public Result implement(EnumerableRelImplementor implementor, Prefer pref) { /* return Linq4j.asEnumerable( new Object[][] { new Object[] {1, 2}, new Object[] {3, 4} }); */ final JavaTypeFactory typeFactory = (JavaTypeFactory) getCluster().getTypeFactory(); final BlockBuilder builder = new BlockBuilder(); final PhysType physType = PhysTypeImpl.of( implementor.getTypeFactory(), getRowType(), pref.preferCustom()); final Type rowClass = physType.getJavaRowType(); final List<Expression> expressions = new ArrayList<Expression>(); final List<RelDataTypeField> fields = rowType.getFieldList(); for (List<RexLiteral> tuple : tuples) { final List<Expression> literals = new ArrayList<Expression>(); for (Pair<RelDataTypeField, RexLiteral> pair : Pair.zip(fields, tuple)) { literals.add( RexToLixTranslator.translateLiteral( pair.right, pair.left.getType(), typeFactory, RexImpTable.NullAs.NULL)); } expressions.add(physType.record(literals)); } builder.add( Expressions.return_( null, Expressions.call( BuiltInMethod.AS_ENUMERABLE.method, Expressions.newArrayInit( Primitive.box(rowClass), expressions)))); return implementor.result(physType, builder.toBlock()); } } // End EnumerableValues.java
{ "content_hash": "7b83e023c337b808a0a20896e932b4d8", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 103, "avg_line_length": 39.15686274509804, "alnum_prop": 0.7060590886329494, "repo_name": "arina-ielchiieva/calcite", "id": "ebf6ffd0a32f7d733d4be6b10627a86121a750d4", "size": "4791", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableValues.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3037" }, { "name": "CSS", "bytes": "36560" }, { "name": "FreeMarker", "bytes": "14696" }, { "name": "HTML", "bytes": "28465" }, { "name": "Java", "bytes": "15187544" }, { "name": "Python", "bytes": "1610" }, { "name": "Ruby", "bytes": "1807" }, { "name": "Shell", "bytes": "5326" } ], "symlink_target": "" }
/*** * Inferno Engine v4 2015-2017 * Written by Tomasz "Rex Dex" Jonarski * * [# filter: elements\controls\text #] ***/ #pragma once #include "ui/toolkit/include/uiElement.h" namespace ui { class TextBuffer; struct CursorNavigation; class ScrolableContainer; class EditBoxSelectionDragInputAction; /// a simple editable text box class UI_WIDGETS_API EditBox : public IElement { RTTI_DECLARE_VIRTUAL_CLASS(EditBox, IElement); public: EditBox(const Bool multiline = false); virtual ~EditBox(); ///---- TCallback OnAccepted; // enter key was pressed TCallback OnModified; // text was modified ///---- // set text, forces regeneration of the glyph buffer (UTF8) void setText(const base::StringBuf& txt); // get text for the whole buffer (UTF8) const base::StringBuf getText() const; // select whole text void selectWholeText(); // reset selection void clearSelection(); // get selected text (UTF8) const base::StringBuf getSelectedText() const; ///---- // set the uneditable postfix text (usually used for units) void setPosfixText(const base::StringBuf& txt); // set the uneditable prefix text (usually used for prompt or limited) void setPrefixText(const base::StringBuf& txt); ///--- // pass char event from the outside (kind of hackish) void handleExternalCharEvent(const base::input::CharEvent &evt); private: base::UniquePtr<TextBuffer> m_textBuffer; Bool m_cursorVisible; Bool m_multiline; // IElement virtual void computeSize(Size& outSize) const override; virtual void prepareShadowGeometry(const ElementArea& drawArea, CachedGeometryBuilder& builder) const override; virtual void prepareBackgroundGeometry(const ElementArea& drawArea, CachedGeometryBuilder& builder) const override; virtual void renderDynamicBackground(const ElementArea& drawArea, const RenderingContext& ctx, const Float mergedOpacity) override; virtual void renderDynamicForeground(const ElementArea& drawArea, const RenderingContext& ctx, const Float mergedOpacity) override; virtual const Bool handleKeyEvent(const base::input::KeyEvent& evt) override; virtual const Bool handleCharEvent(const base::input::CharEvent& evt) override; virtual const Bool handleCursorQuery(const ElementArea& area, const Position& absolutePosition, base::input::CursorType& outCursorType) const override; virtual InputActionPtr handleMouseClick(const ElementArea& area, const base::input::MouseClickEvent& evt) override; virtual const Bool handleContextMenu(const ElementArea& area, const Position& absolutePosition) override; virtual Bool handleTemplateProperty(const base::StringView<AnsiChar>& name, const base::StringView<AnsiChar>& value) override; virtual void invalidateGeometry() override; base::SharedPtr<PopupMenu> createContextMenu() const; void refreshGeometry(); void moveCursor(const CursorNavigation& pos, const Bool extendSelection); void showCursor(); void hideCursor(); void blinkCursor(); void cmdCopySelection(); void cmdCutSelection(); void cmdPasteSelection(); void cmdDeleteSelection(); void cmdSelectAll(); void bindCommands(); void textModified(); void configureMultiline(); const Bool canModify() const; friend class EditBoxSelectionDragInputAction; }; //-- } // ui
{ "content_hash": "c455187efcf810a0ed84a2803a80465b", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 159, "avg_line_length": 32.875, "alnum_prop": 0.6778924497555676, "repo_name": "InfernoEngine/engine", "id": "c64136f6a5439b02d408474bd4a80935f4ece446", "size": "3682", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dev/src/ui/widgets/include/uiEditBox.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2330" }, { "name": "C", "bytes": "3093219" }, { "name": "C++", "bytes": "16712786" }, { "name": "CSS", "bytes": "41369" }, { "name": "Lua", "bytes": "27464" }, { "name": "Shell", "bytes": "3813" }, { "name": "Yacc", "bytes": "72956" } ], "symlink_target": "" }
package integrationTests.data; import org.junit.*; import integrationTests.*; public final class ClassWithInstanceFieldsTest extends CoverageTest { ClassWithInstanceFields tested; @Test public void finalField() { assert tested.getFinalField() == 123; assertFieldIgnored("finalField"); } @Test public void coveredBooleanFieldOnMultipleInstances() { tested.setBooleanField(true); assert tested.isBooleanField(); ClassWithInstanceFields tested2 = new ClassWithInstanceFields(); tested2.setBooleanField(false); assert !tested2.isBooleanField(); assertInstanceFieldCovered("booleanField"); } @Test public void uncoveredByteFieldOnMultipleInstances() { assert tested.getByteField() == 0; tested.setByteField((byte) 1); assert tested.getByteField() == 1; ClassWithInstanceFields tested2 = new ClassWithInstanceFields(); assert tested2.getByteField() == 0; ClassWithInstanceFields tested3 = new ClassWithInstanceFields(); tested3.setByteField((byte) 3); assertInstanceFieldUncovered("byteField", tested3); } @Test public void coveredCharField() { tested.setCharField('c'); assert tested.getCharField() == 'c'; assert tested.getCharField() != 'd'; assertInstanceFieldCovered("charField"); } @Test public void uncoveredShortFieldOnMultipleInstances() { tested.setShortField((short) 1); ClassWithInstanceFields tested2 = new ClassWithInstanceFields(); tested2.setShortField((short) 2); assertInstanceFieldUncovered("shortField", tested, tested2); } @Test public void coveredIntFieldOnMultipleInstances() { ClassWithInstanceFields tested2 = new ClassWithInstanceFields(); tested.setIntField(1); tested2.setIntField(-1); assert tested2.getIntField() == -1; assert tested.getIntField() == 1; assertInstanceFieldCovered("intField"); } @Test public void coveredLongFieldOnMultipleInstances() { tested.setLongField(1); assert tested.getLongField() == 1; ClassWithInstanceFields tested2 = new ClassWithInstanceFields(); tested2.setLongField(2); assert tested2.getLongField() == 2; assertInstanceFieldCovered("longField"); } @Test public void uncoveredFloatFieldOnMultipleInstances() { tested.setFloatField(1); ClassWithInstanceFields tested2 = new ClassWithInstanceFields(); tested2.setFloatField(2.0F); assert tested2.getFloatField() >= 2.0F; assertInstanceFieldUncovered("floatField", tested); } @Test public void coveredDoubleFieldOnMultipleInstances() { tested.setDoubleField(1); assert tested.getDoubleField() >= 1; ClassWithInstanceFields tested2 = new ClassWithInstanceFields(); tested2.setDoubleField(2); assert tested2.getDoubleField() <= 2; assertInstanceFieldCovered("doubleField"); } @Test public void coveredArrayFieldOnMultipleInstances() { tested.setArrayField(null); assert tested.getArrayField() == null; ClassWithInstanceFields tested2 = new ClassWithInstanceFields(); tested2.setArrayField(new int[0]); assert tested2.getArrayField().length == 0; assertInstanceFieldCovered("arrayField"); } @AfterClass public static void verifyDataCoverage() { verifyDataCoverage(9, 6, 67); } }
{ "content_hash": "49a97b59c40ac1a0ffa01399eb1180b7", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 70, "avg_line_length": 25.8, "alnum_prop": 0.6641749723145072, "repo_name": "borisbrodski/jmockit", "id": "477c70058f7616caab2c713510d063aaca0a7ce3", "size": "3743", "binary": false, "copies": "3", "ref": "refs/heads/JUnitRuleSupport", "path": "coverage/test/integrationTests/data/ClassWithInstanceFieldsTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2617406" }, { "name": "JavaScript", "bytes": "7998" } ], "symlink_target": "" }
package com.qihoo360.replugin.utils; import android.content.Context; import com.qihoo360.replugin.helper.LogRelease; import java.io.FileDescriptor; import java.io.PrintWriter; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import static com.qihoo360.replugin.helper.LogDebug.MISC_TAG; import static com.qihoo360.replugin.helper.LogRelease.LOGR; /** * 和反射操作有关的Utils * * @author RePlugin Team */ public final class ReflectUtils { // ---------------- // Class & Constructor // ---------------- public static Class<?> getClass(final String className) throws ClassNotFoundException { return Class.forName(className); } public static <T> T invokeConstructor(Class<T> cls, Class[] parameterTypes, Object... args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Constructor<T> c = cls.getConstructor(parameterTypes); if (c != null) { c.setAccessible(true); return c.newInstance(args); } return null; } // ---------------- // Field // ---------------- public static Field getField(Class<?> cls, String fieldName) { // From Apache: FieldUtils.getField() // check up the superclass hierarchy for (Class<?> acls = cls; acls != null; acls = acls.getSuperclass()) { try { final Field field = acls.getDeclaredField(fieldName); // getDeclaredField checks for non-public scopes as well // and it returns accurate results setAccessible(field, true); return field; } catch (final NoSuchFieldException ex) { // NOPMD // ignore } } // check the public interface case. This must be manually searched for // incase there is a public supersuperclass field hidden by a private/package // superclass field. Field match = null; for (final Class<?> class1 : cls.getInterfaces()) { try { final Field test = class1.getField(fieldName); Validate.isTrue(match == null, "Reference to field %s is ambiguous relative to %s" + "; a matching field exists on two or more implemented interfaces.", fieldName, cls); match = test; } catch (final NoSuchFieldException ex) { // NOPMD // ignore } } return match; } public static Object readStaticField(Class<?> c, String fieldName) throws NoSuchFieldException, IllegalAccessException { return readField(c, null, fieldName); } public static Object readField(Object target, String fieldName) throws IllegalAccessException, NoSuchFieldException { return readField(target.getClass(), target, fieldName); } public static Object readField(Class<?> c, Object target, String fieldName) throws IllegalAccessException, NoSuchFieldException { Field f = getField(c, fieldName); return readField(f, target); } public static Object readField(final Field field, final Object target) throws IllegalAccessException { return field.get(target); } public static void writeField(Object target, String fName, Object value) throws NoSuchFieldException, IllegalAccessException { writeField(target.getClass(), target, fName, value); } public static void writeField(Class<?> c, Object object, String fName, Object value) throws NoSuchFieldException, IllegalAccessException { Field f = getField(c, fName); writeField(f, object, value); } public static void writeField(final Field field, final Object target, final Object value) throws IllegalAccessException { field.set(target, value); } public static List<Field> getAllFieldsList(final Class<?> cls) { // From Apache: FieldUtils.getAllFieldsList() Validate.isTrue(cls != null, "The class must not be null"); final List<Field> allFields = new ArrayList<>(); Class<?> currentClass = cls; while (currentClass != null) { final Field[] declaredFields = currentClass.getDeclaredFields(); for (final Field field : declaredFields) { allFields.add(field); } currentClass = currentClass.getSuperclass(); } return allFields; } public static void removeFieldFinalModifier(final Field field) { // From Apache: FieldUtils.removeFinalModifier() Validate.isTrue(field != null, "The field must not be null"); try { if (Modifier.isFinal(field.getModifiers())) { // Do all JREs implement Field with a private ivar called "modifiers"? final Field modifiersField = Field.class.getDeclaredField("modifiers"); final boolean doForceAccess = !modifiersField.isAccessible(); if (doForceAccess) { modifiersField.setAccessible(true); } try { modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); } finally { if (doForceAccess) { modifiersField.setAccessible(false); } } } } catch (final NoSuchFieldException ignored) { // The field class contains always a modifiers field } catch (final IllegalAccessException ignored) { // The modifiers field is made accessible } } // ---------------- // Method // ---------------- public static Method getMethod(Class<?> cls, String fieldName, Class<?>... parameterTypes) { // check up the superclass hierarchy for (Class<?> acls = cls; acls != null; acls = acls.getSuperclass()) { try { final Method field = acls.getDeclaredMethod(fieldName, parameterTypes); // getDeclaredField checks for non-public scopes as well // and it returns accurate results setAccessible(field, true); return field; } catch (final NoSuchMethodException ex) { // NOPMD // ignore } } // check the public interface case. This must be manually searched for // incase there is a public supersuperclass field hidden by a private/package // superclass field. Method match = null; for (final Class<?> class1 : cls.getInterfaces()) { try { final Method test = class1.getMethod(fieldName, parameterTypes); Validate.isTrue(match == null, "Reference to field %s is ambiguous relative to %s" + "; a matching field exists on two or more implemented interfaces.", fieldName, cls); match = test; } catch (final NoSuchMethodException ex) { // NOPMD // ignore } } return match; } public static Object invokeMethod(final Object object, final String methodName, Class<?>[] methodParamTypes, Object... args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Class clz = object.getClass(); Method m = getMethod(clz, methodName, methodParamTypes); return m.invoke(args); } public static Object invokeMethod(ClassLoader loader, String clzName, String methodName, Object methodReceiver, Class<?>[] methodParamTypes, Object... methodParamValues) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { if (methodReceiver == null) { return null; } Class clz = Class.forName(clzName, false, loader); if (clz != null) { Method med = clz.getMethod(methodName, methodParamTypes); if (med != null) { med.setAccessible(true); return med.invoke(methodReceiver, methodParamValues); } } return null; } public static void setAccessible(AccessibleObject ao, boolean value) { if (ao.isAccessible() != value) { ao.setAccessible(value); } } // ---------------- // Other // ---------------- public static final void dumpObject(Object object, FileDescriptor fd, PrintWriter writer, String[] args) { try { Class<?> c = object.getClass(); do { writer.println("c=" + c.getName()); Field fields[] = c.getDeclaredFields(); for (Field f : fields) { boolean acc = f.isAccessible(); if (!acc) { f.setAccessible(true); } Object o = f.get(object); writer.print(f.getName()); writer.print("="); if (o != null) { writer.println(o.toString()); } else { writer.println("null"); } if (!acc) { f.setAccessible(acc); } } c = c.getSuperclass(); } while (c != null && !c.equals(Object.class) && !c.equals(Context.class)); } catch (Throwable e) { if (LOGR) { LogRelease.e(MISC_TAG, e.getMessage(), e); } } } }
{ "content_hash": "df1ca3a3fe5c8b29d21fe5924c35a5ea", "timestamp": "", "source": "github", "line_count": 264, "max_line_length": 142, "avg_line_length": 37.628787878787875, "alnum_prop": 0.5751962955506342, "repo_name": "247321453/RePlugin", "id": "9ddafc4d33b94681badff820a3c3e7185e6351f1", "size": "10552", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "replugin-host-library/replugin-host-lib/src/main/java/com/qihoo360/replugin/utils/ReflectUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "126376" }, { "name": "IDL", "bytes": "4741" }, { "name": "Java", "bytes": "1591283" }, { "name": "Kotlin", "bytes": "20556" }, { "name": "Prolog", "bytes": "954" } ], "symlink_target": "" }
package org.elasticsearch.gradle.internal; import org.gradle.api.DefaultTask; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.TaskAction; import org.gradle.internal.file.Chmod; import java.io.File; import javax.inject.Inject; /** * Creates an empty directory. */ public class EmptyDirTask extends DefaultTask { private File dir; private int dirMode = 0755; /** * Creates an empty directory with the configured permissions. */ @TaskAction public void create() { dir.mkdirs(); getChmod().chmod(dir, dirMode); } @Inject public Chmod getChmod() { throw new UnsupportedOperationException(); } @Internal public File getDir() { return dir; } @Input public String getDirPath() { return dir.getPath(); } /** * @param dir The directory to create */ public void setDir(File dir) { this.dir = dir; } /** * @param dir The path of the directory to create. Takes a String and coerces it to a file. */ public void setDir(String dir) { this.dir = getProject().file(dir); } @Input public int getDirMode() { return dirMode; } /** * @param dirMode The permissions to apply to the new directory */ public void setDirMode(int dirMode) { this.dirMode = dirMode; } }
{ "content_hash": "4c1310a0d09219d76e35f440acdd0add", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 95, "avg_line_length": 19.90277777777778, "alnum_prop": 0.619678995115143, "repo_name": "GlenRSmith/elasticsearch", "id": "bbcaabe18905e9ae94ecdfa2f4e19d085e8cee68", "size": "1786", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/EmptyDirTask.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "11082" }, { "name": "Batchfile", "bytes": "11057" }, { "name": "Emacs Lisp", "bytes": "3341" }, { "name": "FreeMarker", "bytes": "45" }, { "name": "Groovy", "bytes": "337461" }, { "name": "HTML", "bytes": "2186" }, { "name": "Java", "bytes": "43224931" }, { "name": "Perl", "bytes": "11756" }, { "name": "Python", "bytes": "19852" }, { "name": "Shell", "bytes": "99571" } ], "symlink_target": "" }
#ifndef HPIPM_S_TREE_OCP_QCQP_IPM_H_ #define HPIPM_S_TREE_OCP_QCQP_IPM_H_ #include <blasfeo_target.h> #include <blasfeo_common.h> #include <hpipm_common.h> #include <hpipm_s_tree_ocp_qcqp_dim.h> #include <hpipm_s_tree_ocp_qp.h> #include <hpipm_s_tree_ocp_qcqp_res.h> #include <hpipm_s_tree_ocp_qcqp_sol.h> #ifdef __cplusplus extern "C" { #endif struct s_tree_ocp_qcqp_ipm_arg { struct s_tree_ocp_qp_ipm_arg *qp_arg; float mu0; // initial value for complementarity slackness float alpha_min; // exit cond on step length float res_g_max; // exit cond on inf norm of residuals float res_b_max; // exit cond on inf norm of residuals float res_d_max; // exit cond on inf norm of residuals float res_m_max; // exit cond on inf norm of residuals float reg_prim; // reg of primal hessian float lam_min; // min value in lam vector float t_min; // min value in t vector int iter_max; // exit cond in iter number int stat_max; // iterations saved in stat int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm int cond_pred_corr; // conditional Mehrotra's predictor-corrector int itref_pred_max; // max number of iterative refinement steps for predictor step int itref_corr_max; // max number of iterative refinement steps for corrector step int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol // int square_root_alg; // 0 classical Riccati, 1 square-root Riccati int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq (for square_root_alg==1) int abs_form; // absolute IPM formulation int comp_dual_sol_eq; // dual solution of equality constraints (only for abs_form==1) int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol_eq==1) // int comp_res_pred; // compute residuals of prediction int split_step; // use different step for primal and dual variables int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution int mode; hpipm_size_t memsize; }; struct s_tree_ocp_qcqp_ipm_ws { struct s_tree_ocp_qp_ipm_ws *qp_ws; struct s_tree_ocp_qp *qp; struct s_tree_ocp_qp_sol *qp_sol; struct s_tree_ocp_qcqp_res_ws *qcqp_res_ws; struct s_tree_ocp_qcqp_res *qcqp_res; struct blasfeo_svec *tmp_nuxM; int iter; // iteration number int status; hpipm_size_t memsize; }; // hpipm_size_t s_tree_ocp_qcqp_ipm_arg_strsize(); // hpipm_size_t s_tree_ocp_qcqp_ipm_arg_memsize(struct s_tree_ocp_qcqp_dim *ocp_dim); // void s_tree_ocp_qcqp_ipm_arg_create(struct s_tree_ocp_qcqp_dim *ocp_dim, struct s_tree_ocp_qcqp_ipm_arg *arg, void *mem); // void s_tree_ocp_qcqp_ipm_arg_set_default(enum hpipm_mode mode, struct s_tree_ocp_qcqp_ipm_arg *arg); // void s_tree_ocp_qcqp_ipm_arg_set(char *field, void *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // set maximum number of iterations void s_tree_ocp_qcqp_ipm_arg_set_iter_max(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // set minimum step lenght void s_tree_ocp_qcqp_ipm_arg_set_alpha_min(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // set initial value of barrier parameter void s_tree_ocp_qcqp_ipm_arg_set_mu0(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // set exit tolerance on stationarity condition void s_tree_ocp_qcqp_ipm_arg_set_tol_stat(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // set exit tolerance on equality constr void s_tree_ocp_qcqp_ipm_arg_set_tol_eq(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // set exit tolerance on inequality constr void s_tree_ocp_qcqp_ipm_arg_set_tol_ineq(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // set exit tolerance on complementarity condition void s_tree_ocp_qcqp_ipm_arg_set_tol_comp(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // set regularization of primal variables void s_tree_ocp_qcqp_ipm_arg_set_reg_prim(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // set warm start: 0 no warm start, 1 primal var void s_tree_ocp_qcqp_ipm_arg_set_warm_start(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // Mehrotra's predictor-corrector IPM algorithm: 0 no predictor-corrector, 1 use predictor-corrector void s_tree_ocp_qcqp_ipm_arg_set_pred_corr(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // conditional predictor-corrector: 0 no conditinal predictor-corrector, 1 conditional predictor-corrector void s_tree_ocp_qcqp_ipm_arg_set_cond_pred_corr(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // set riccati algorithm: 0 classic, 1 square-root //void s_tree_ocp_qcqp_ipm_arg_set_ric_alg(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // compute residuals after solution void s_tree_ocp_qcqp_ipm_arg_set_comp_res_exit(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // compute residuals of prediction //void s_tree_ocp_qcqp_ipm_arg_set_comp_res_pred(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // min value of lam in the solution void s_tree_ocp_qcqp_ipm_arg_set_lam_min(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // min value of t in the solution void s_tree_ocp_qcqp_ipm_arg_set_t_min(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // use different step for primal and dual variables void s_tree_ocp_qcqp_ipm_arg_set_split_step(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution void s_tree_ocp_qcqp_ipm_arg_set_t_lam_min(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); // hpipm_size_t s_tree_ocp_qcqp_ipm_ws_strsize(); // hpipm_size_t s_tree_ocp_qcqp_ipm_ws_memsize(struct s_tree_ocp_qcqp_dim *ocp_dim, struct s_tree_ocp_qcqp_ipm_arg *arg); // void s_tree_ocp_qcqp_ipm_ws_create(struct s_tree_ocp_qcqp_dim *ocp_dim, struct s_tree_ocp_qcqp_ipm_arg *arg, struct s_tree_ocp_qcqp_ipm_ws *ws, void *mem); // void s_tree_ocp_qcqp_ipm_get(char *field, struct s_tree_ocp_qcqp_ipm_ws *ws, void *value); // void s_tree_ocp_qcqp_ipm_get_status(struct s_tree_ocp_qcqp_ipm_ws *ws, int *status); // void s_tree_ocp_qcqp_ipm_get_iter(struct s_tree_ocp_qcqp_ipm_ws *ws, int *iter); // void s_tree_ocp_qcqp_ipm_get_max_res_stat(struct s_tree_ocp_qcqp_ipm_ws *ws, float *res_stat); // void s_tree_ocp_qcqp_ipm_get_max_res_eq(struct s_tree_ocp_qcqp_ipm_ws *ws, float *res_eq); // void s_tree_ocp_qcqp_ipm_get_max_res_ineq(struct s_tree_ocp_qcqp_ipm_ws *ws, float *res_ineq); // void s_tree_ocp_qcqp_ipm_get_max_res_comp(struct s_tree_ocp_qcqp_ipm_ws *ws, float *res_comp); // void s_tree_ocp_qcqp_ipm_get_stat(struct s_tree_ocp_qcqp_ipm_ws *ws, float **stat); // void s_tree_ocp_qcqp_ipm_get_stat_m(struct s_tree_ocp_qcqp_ipm_ws *ws, int *stat_m); // void s_tree_ocp_qcqp_init_var(struct s_tree_ocp_qcqp *qp, struct s_tree_ocp_qcqp_sol *qp_sol, struct s_tree_ocp_qcqp_ipm_arg *arg, struct s_tree_ocp_qcqp_ipm_ws *ws); // void s_tree_ocp_qcqp_ipm_solve(struct s_tree_ocp_qcqp *qp, struct s_tree_ocp_qcqp_sol *qp_sol, struct s_tree_ocp_qcqp_ipm_arg *arg, struct s_tree_ocp_qcqp_ipm_ws *ws); #ifdef __cplusplus } // #extern "C" #endif #endif // HPIPM_S_TREE_OCP_QCQP_IPM_H_
{ "content_hash": "45688b5ed5ea7d139ae9b0c3ec2fd4d0", "timestamp": "", "source": "github", "line_count": 159, "max_line_length": 167, "avg_line_length": 43.64150943396226, "alnum_prop": 0.722582504683672, "repo_name": "commaai/openpilot", "id": "69d65914c527c4be21da5d14668c1a65e3c299a4", "size": "10338", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_ipm.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "604924" }, { "name": "C++", "bytes": "1125553" }, { "name": "Cython", "bytes": "50503" }, { "name": "Dockerfile", "bytes": "1239" }, { "name": "Emacs Lisp", "bytes": "124" }, { "name": "HTML", "bytes": "11493" }, { "name": "Kaitai Struct", "bytes": "8093" }, { "name": "MATLAB", "bytes": "35190" }, { "name": "Makefile", "bytes": "14018" }, { "name": "Python", "bytes": "2386885" }, { "name": "QML", "bytes": "1132" }, { "name": "Shell", "bytes": "32876" } ], "symlink_target": "" }
layout: book number: 11 title: SQL Arrays --- This chapter shows how we can map Scala sequence types to SQL `ARRAY` types, for vendors that support it. Note that although SQL array mappings are part of the JDBC specification, their behavior is vendor-specific and requires an add-on library; the code in this chapter requires `doobie-postgres`. ### Setting Up Again we set up a transactor and pull in YOLO mode. We also need an import to get PostgreSQL-specific type mappings. ```scala import doobie.imports._ import doobie.postgres.imports._ import cats._, cats.data._, cats.implicits._ import fs2.interop.cats._ val xa = DriverManagerTransactor[IOLite]( "org.postgresql.Driver", "jdbc:postgresql:world", "postgres", "" ) val y = xa.yolo; import y._ ``` ### Reading and Writing Arrays Let's create a new table with an SQL array column. Note that this is likely to work only for PostgreSQL; the syntax for arrays differs significantly from vendor to vendor. ```scala val drop = sql"DROP TABLE IF EXISTS person".update.quick val create = sql""" CREATE TABLE person ( id SERIAL, name VARCHAR NOT NULL UNIQUE, pets VARCHAR[] NOT NULL ) """.update.quick ``` ```scala scala> (drop *> create).unsafePerformIO 0 row(s) updated 0 row(s) updated ``` **doobie** maps SQL array columns to `Array`, `List`, and `Vector` by default. No special handling is required, other than importing the vendor-specific array support above. ```scala case class Person(id: Long, name: String, pets: List[String]) def insert(name: String, pets: List[String]): ConnectionIO[Person] = { sql"insert into person (name, pets) values ($name, $pets)" .update.withUniqueGeneratedKeys("id", "name", "pets") } ``` Insert works fine, as does reading the result. No surprises. ```scala scala> insert("Bob", List("Nixon", "Slappy")).quick.unsafePerformIO Person(1,Bob,List(Nixon, Slappy)) scala> insert("Alice", Nil).quick.unsafePerformIO Person(2,Alice,List()) ``` ### Lamentations of `NULL` **doobie** maps nullable columns via `Option`, so `null` is never observed in programs that use the high-level API, and the typechecking feature discussed earlier will find mismatches. So this means if you have a nullable SQL `varchar[]` then you will be chided grimly if you don't map it as `Option[List[String]]` (or some other supported sequence type). However there is another axis of variation here: the *array cells* themselves may contain null values. And the query checker can't save you here because this is not reflected in the metadata provided by PostgreSQL or H2, and probably not by anyone. So there are actually four ways to map an array, and you should carefully consider which is appropriate for your schema. In the first two cases reading a `NULL` cell would result in a `NullableCellRead` exception. ```scala scala> sql"select array['foo','bar','baz']".query[List[String]].quick.unsafePerformIO List(foo, bar, baz) scala> sql"select array['foo','bar','baz']".query[Option[List[String]]].quick.unsafePerformIO Some(List(foo, bar, baz)) scala> sql"select array['foo',NULL,'baz']".query[List[Option[String]]].quick.unsafePerformIO List(Some(foo), None, Some(baz)) scala> sql"select array['foo',NULL,'baz']".query[Option[List[Option[String]]]].quick.unsafePerformIO Some(List(Some(foo), None, Some(baz))) ```
{ "content_hash": "cabef96498893a70c008408d3e9f27cf", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 355, "avg_line_length": 38.17045454545455, "alnum_prop": 0.7299791604644239, "repo_name": "tpolecat/tpolecat.github.io", "id": "3fd317871d73bf78897e75e1f25a68b34ab2e102", "size": "3363", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_doobie-cats-0.4.2/11-Arrays.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "72020" }, { "name": "HTML", "bytes": "1529544" }, { "name": "JavaScript", "bytes": "416954" }, { "name": "PHP", "bytes": "1742" }, { "name": "Ruby", "bytes": "3312" } ], "symlink_target": "" }
using Akka.Persistence; using System; namespace AkkaEventStore.Actors { public abstract class PersistentStateActor : PersistentActor { public abstract IActorState State { get; set; } protected override bool ReceiveCommand(object message) { if (message as string == "peek") Console.WriteLine(State); return true; } } }
{ "content_hash": "ccbff4998600f7749248ad9c0d90b61f", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 70, "avg_line_length": 25.3125, "alnum_prop": 0.6172839506172839, "repo_name": "vladkosarev/Akka.net-EventStorePersistence", "id": "e80ed599ced789dac74f35d65878c2a3a8abbf18", "size": "407", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/AkkaEventStore/Actors/PersistentStateActor.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "21344" }, { "name": "F#", "bytes": "4718" } ], "symlink_target": "" }
package java.util.regex; import def.js.Array; import def.js.JSON; import def.js.RegExp; import def.js.SyntaxError; import jsweet.util.Lang; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; import static def.js.Globals.undefined; import static jsweet.util.Lang.*; public class Pattern implements Serializable { public static final int CASE_INSENSITIVE = 2; public static final int MULTILINE = 8; public static final int UNICODE_CASE = 64; public static final int UNICODE_CHARACTER_CLASS = 256; final RegExp regexp; final int _flags; final Map<String, Integer> namedGroupsNames; private Pattern(RegExp regexp, int _flags, Map<String, Integer> namedGroupsNames) { this.regexp = regexp; this._flags = _flags; this.namedGroupsNames = namedGroupsNames; } private static class GroupNameRemover implements Function<def.js.String[], def.js.String> { private final Map<String, Integer> namedGroupsNames; private int count = 0; private boolean inBrackets = false; private GroupNameRemover(Map<String, Integer> namedGroupsNames) { this.namedGroupsNames = namedGroupsNames; } @Override public def.js.String apply(def.js.String[] args) { // argument list: // 0 == whole recognized text // 1 == open bracket escapes // 2 == close bracket escapes // 3 == open parenthesis escapes // 4 == non capturing block // 5 == named group name if (inBrackets || args[2] != undefined) { // only close bracket saves out from this state inBrackets = args[2] == undefined || args[2].length == 1; // keep in brackets if not close or escaped return args[0]; } if (args[1] != undefined) { inBrackets = args[1].length == 0; // open bracket without escape return args[0]; } if (args[3] != undefined && args[3].length != 0) { // escaped open parenthesis, not a block return args[0]; } if (args[4] == undefined) { // not a non capturing block (aka capturing block), count it count += 1; } if (args[5] != undefined) { // capturing block with name namedGroupsNames.put(string(args[5]), count); args[0] = args[0].replace(new RegExp("\\?<[^>]+>"), ""); } return args[0]; } } public static Pattern compile(String regexp) { return compile(regexp, 0); } public static Pattern compile(String regexpString, int flags) { String jsFlags = "g"; if ((flags & MULTILINE) > 0) { jsFlags += "m"; } if ((flags & CASE_INSENSITIVE) > 0) { jsFlags += "i"; } if ((flags & UNICODE_CHARACTER_CLASS) > 0) { jsFlags += "u"; } if ((flags & UNICODE_CASE) > 0) { jsFlags += "ui"; } // formatting regexp to acquire some information (name and indices) // this should not be to change anything about the original regex Map<String, Integer> namedGroupsNames = new HashMap<>(); GroupNameRemover groupNameRemover = new GroupNameRemover(namedGroupsNames); Supplier<def.js.String> mapper = Lang.<Supplier<def.js.String>> any((Function<def.js.String[], def.js.String>) ((def.js.String ... args) -> { if (!Array.isArray(args) || args[2] == undefined || args[2].length == 0) { return args[1]; } def.js.String regexp = args[args.length - 1]; int startIndexOfMatched = Integer.parseInt(string(args[args.length - 2])); int endIndexOfMatched = startIndexOfMatched + args[0].length; boolean hasOpenBracket = (startIndexOfMatched > 0 && "(".equals(string(regexp.charAt(startIndexOfMatched-1)))) || (startIndexOfMatched > 2 && "(?:".equals(string(regexp.substr(startIndexOfMatched - 3, 3)))); boolean hasCloseBracket = regexp.length > endIndexOfMatched && ")".equals(string(regexp.charAt(endIndexOfMatched))); if (hasOpenBracket && hasCloseBracket) { return string(string(args[1]) + args[2]); } return string(args[1] + "(?:" + args[2] + ")"); })); regexpString = string(string(regexpString) .replace(new RegExp("" + "(?:\\\\\\\\)*(\\\\?)\\[\\^?\\]?|" + "(?:\\\\\\\\)*(\\\\?)\\]|" + "(?:\\\\\\\\)*(\\\\?)\\((?:" + "(\\?\\:)|" + "\\?<([^>]+)>)?", "g"), Lang.<Supplier<def.js.String>> any((Function<def.js.String[], def.js.String>) ((def.js.String ... args) -> groupNameRemover.apply(args)))) // add non-capturing groups to all string .replace(new RegExp("" + "(" + // previous group suffix ($1) "\\?\\:|" + // open bracket modifier (?: "(?:" + // close bracket modifiers "[*+?]|" + // * + ? "\\{[^\\}]+\\}" + // {3, 4} ")*" + ")" + "((?:" + // main grouped characters ($2) "[^\\\\()|]|" + // any not \\ () | character "\\\\.|" + // escaped characters "\\[\\^?\\]\\]|" + // []] and [^]] special brackets "\\[\\^?(?:" + // brackets "[^\\\\\\]]|" + // not escape or closing character "\\\\.|" + // escaped characters ")+\\]" + ")*)", "g"), mapper)); try { return new Pattern(new RegExp(regexpString, jsFlags), flags, namedGroupsNames); } catch (SyntaxError e) { throw new PatternSyntaxException(e, regexpString); } } public int flags() { return _flags; } public Matcher matcher(CharSequence sequence) { return new Matcher(this, sequence.toString()); } public static boolean matches(String regex, CharSequence input) { return compile(regex).matcher(input).matches(); } public String pattern() { return regexp.source; } public static String quote(String s) { return JSON.stringify(s); } public String[] split(CharSequence input, int limit) { return any(string(input.toString()).split(regexp, limit).toArray()); } public String[] split(CharSequence input) { return split(input, 0); } public Stream<String> splitAsStream(CharSequence input) { return Arrays.stream(split(input)); } @Override public String toString() { return pattern(); } }
{ "content_hash": "3832b3d99857d37ee3568072a0bc974b", "timestamp": "", "source": "github", "line_count": 196, "max_line_length": 136, "avg_line_length": 38, "alnum_prop": 0.5021482277121375, "repo_name": "j4ts/j4ts", "id": "74ec57b20afe16ed42a3674902eb1b8ce88cd8cd", "size": "7448", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/java/util/regex/Pattern.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "277" }, { "name": "Java", "bytes": "777206" } ], "symlink_target": "" }
var gulp = require('gulp'); var gutil = require('gulp-util'); var bower = require('bower'); var concat = require('gulp-concat'); var sass = require('gulp-sass'); var minifyCss = require('gulp-minify-css'); var rename = require('gulp-rename'); var sh = require('shelljs'); var karma = require('gulp-karma'); var jshint = require('gulp-jshint'); var paths = { sass: ['./scss/**/*.scss'], js: ['./www/js/**/*.js', './test/spec/**/*.js'] }; gulp.task('default', ['sass', 'test']); gulp.task('jshinter', function() { gulp.src(paths.js) .pipe(jshint('.jshintrc')) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('sass', function(done) { gulp.src('./scss/ionic.app.scss') .pipe(sass()) .pipe(gulp.dest('./www/css/')) .pipe(minifyCss({ keepSpecialComments: 0 })) .pipe(rename({ extname: '.min.css' })) .pipe(gulp.dest('./www/css/')) .on('end', done); }); gulp.task('watch', function() { gulp.watch(paths.sass, ['sass']); gulp.watch(paths.js, ['jshinter']); }); gulp.task('install', ['git-check'], function() { return bower.commands.install() .on('log', function(data) { gutil.log('bower', gutil.colors.cyan(data.id), data.message); }); }); gulp.task('git-check', function(done) { if (!sh.which('git')) { console.log( ' ' + gutil.colors.red('Git is not installed.'), '\n Git, the version control system, is required to download Ionic.', '\n Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.', '\n Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.' ); process.exit(1); } done(); }); gulp.task('test', function() { // Be sure to return the stream // NOTE: Using the fake './foobar' so as to run the files // listed in karma.conf.js INSTEAD of what was passed to // gulp.src ! return gulp.src('./foobar') .pipe(karma({ configFile: 'karma.conf.js', action: 'run' })) .on('error', function(err) { // Make sure failed tests cause gulp to exit non-zero console.log(err); this.emit('end'); //instead of erroring the stream, end it }); }); gulp.task('autotest', function() { return gulp.watch(['www/js/**/*.js', 'test/spec/*.js'], ['test']); });
{ "content_hash": "356bc0b287cc492a5749720517c10d27", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 91, "avg_line_length": 28.4, "alnum_prop": 0.5924295774647887, "repo_name": "lafent/ionic-generic-directory", "id": "dab2809223972f843792626a869e0242e0afa71d", "size": "2272", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gulpfile.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "668810" }, { "name": "JavaScript", "bytes": "2468756" } ], "symlink_target": "" }
require "portus/auth_from_token" class ApplicationController < ActionController::Base include ::Portus::Checks before_action :check_requirements include ::Portus::AuthFromToken before_action :authenticate_user_from_authentication_token! before_action :authenticate_user! before_action :force_update_profile! before_action :force_registry_config! include Headers protect_from_forgery with: :exception, prepend: true add_flash_types :float include Pundit rescue_from Pundit::NotAuthorizedError, with: :deny_access respond_to :html, :json # Two things can happen when signing in. # 1. The current user has no email: this happens on LDAP registration. In # this case, the user will be asked to submit an email. # 2. If the sign-in action was triggered trying to access a specific page # go back to it # 3. Or go to the root url. def after_sign_in_path_for(resource) current_user.email? ? super : edit_user_registration_path end def after_sign_out_path_for(_resource) new_user_session_path end protected # Authenticate the user:token as provided in the "PORTUS-AUTH" header. def authenticate_user_from_authentication_token! auth = request.headers["PORTUS-AUTH"].presence return if auth.nil? username, password = auth.split(":") user = User.find_by(username: username) sign_in(user, store: false) if user&.application_token_valid?(password) end # Redirect users to their profile page if they haven't set up their email # account (this happens when signing up through LDAP suppor). def force_update_profile! return unless current_user && !current_user.email? return if protected_controllers? redirect_to edit_user_registration_path end # Redirect admin users to the registries#new page if no registry has been # setup yet. def force_registry_config! return unless current_user&.admin? return if Registry.any? return if protected_controllers?("admin/registries") redirect_to new_admin_registry_path end # Returns true if the current controller is a "protected" controller. A # protected controller is either the auth/registrations, auth/sessions or # either of the supplied controllers. # # Use this method to avoid infinite redirect loops in before_action filters. def protected_controllers?(*controllers) controller = params[:controller] return true if controller == "auth/registrations" || controller == "auth/sessions" controllers.each { |c| return true if c == controller } false end # Render the 401 page. def deny_access @status = 401 respond_to do |format| format.html { render template: "errors/401", status: @status, layout: "errors" } format.all { render body: nil, status: @status } end end end
{ "content_hash": "e1df2f19d39a16120917f93b347262a1", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 86, "avg_line_length": 31, "alnum_prop": 0.71712158808933, "repo_name": "mssola/Portus", "id": "4a789fd5852d097de5dce9bbaff892ec2a35dc7a", "size": "2852", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/controllers/application_controller.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "23374" }, { "name": "Dockerfile", "bytes": "3250" }, { "name": "HTML", "bytes": "70298" }, { "name": "JavaScript", "bytes": "61504" }, { "name": "Ruby", "bytes": "1098643" }, { "name": "Shell", "bytes": "31990" }, { "name": "Vue", "bytes": "202211" } ], "symlink_target": "" }
#ifndef VP9_ENCODER_VP9_AQ_COMPLEXITY_H_ #define VP9_ENCODER_VP9_AQ_COMPLEXITY_H_ #ifdef __cplusplus extern "C" { #endif struct VP9_COMP; struct macroblock; // Select a segment for the current SB64. void vp9_select_in_frame_q_segment(struct VP9_COMP *cpi, struct macroblock *x, BLOCK_SIZE bs, int mi_row, int mi_col, int output_enabled, int projected_rate); // This function sets up a set of segments with delta Q values around // the baseline frame quantizer. void vp9_setup_in_frame_q_adj(struct VP9_COMP *cpi); #ifdef __cplusplus } // extern "C" #endif #endif // VP9_ENCODER_VP9_AQ_COMPLEXITY_H_
{ "content_hash": "6f7ae34d3c42d52df73715951cada3f9", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 78, "avg_line_length": 25.535714285714285, "alnum_prop": 0.6223776223776224, "repo_name": "mxOBS/deb-pkg_trusty_chromium-browser", "id": "3f885e450f928eebf6c784364f07d924231b48db", "size": "1125", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "third_party/libvpx/source/libvpx/vp9/encoder/vp9_aq_complexity.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "8402" }, { "name": "Assembly", "bytes": "230130" }, { "name": "Batchfile", "bytes": "34966" }, { "name": "C", "bytes": "12435900" }, { "name": "C++", "bytes": "264378706" }, { "name": "CMake", "bytes": "27829" }, { "name": "CSS", "bytes": "795726" }, { "name": "Dart", "bytes": "74976" }, { "name": "Emacs Lisp", "bytes": "2360" }, { "name": "Go", "bytes": "31783" }, { "name": "Groff", "bytes": "5283" }, { "name": "HTML", "bytes": "19491230" }, { "name": "Java", "bytes": "7637875" }, { "name": "JavaScript", "bytes": "12723911" }, { "name": "LLVM", "bytes": "1169" }, { "name": "Logos", "bytes": "6893" }, { "name": "Lua", "bytes": "14392" }, { "name": "Makefile", "bytes": "208315" }, { "name": "Objective-C", "bytes": "1460032" }, { "name": "Objective-C++", "bytes": "7760068" }, { "name": "PLpgSQL", "bytes": "175360" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "427212" }, { "name": "Python", "bytes": "11447382" }, { "name": "Ragel in Ruby Host", "bytes": "104846" }, { "name": "Scheme", "bytes": "10604" }, { "name": "Shell", "bytes": "1208350" }, { "name": "Standard ML", "bytes": "4965" }, { "name": "nesC", "bytes": "18335" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Application.Models.Pages { public class Page { public int Id { get; set; } public string Title { get; set; } public string ShortDescription { get; set; } public string Content { get; set; } public DateTime DateCreated { get; set; } public DateTime DateModified { get; set; } public string ApplicationUserId { get; set; } public virtual ApplicationUser Author { get; set; } } }
{ "content_hash": "a36e9d64a92b202b256641f042f5f5e6", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 59, "avg_line_length": 29.05, "alnum_prop": 0.6506024096385542, "repo_name": "nzhul/metaltrade", "id": "d984e7d8ef01e319554b31cdadfc3989b4d6498f", "size": "583", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Application.Models/Pages/Page.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "106" }, { "name": "C#", "bytes": "152604" }, { "name": "CSS", "bytes": "63970" }, { "name": "HTML", "bytes": "535989" }, { "name": "JavaScript", "bytes": "1436771" }, { "name": "Makefile", "bytes": "478" } ], "symlink_target": "" }
(function e(t, n, r) { function s(o, u) { if (!n[o]) { if (!t[o]) { var a = typeof require == "function" && require; if (!u && a) return a(o, !0); if (i) return i(o, !0); var f = new Error("Cannot find module '" + o + "'"); throw f.code = "MODULE_NOT_FOUND", f } var l = n[o] = { exports: {} }; t[o][0].call(l.exports, function(e) { var n = t[o][1][e]; return s(n ? n : e) }, l, l.exports, e, t, n, r) } return n[o].exports } var i = typeof require == "function" && require; for (var o = 0; o < r.length; o++) s(r[o]); return s })({ 1: [function(require, module, exports) { var Cosmic = require("./index"); window.Cosmic = Cosmic }, { "./index": 2 }], 2: [function(require, module, exports) { require("es6-promise").polyfill(); require("isomorphic-fetch"); var _ = require("lodash"); var superagent = require("superagent"); var FormData = require("form-data"); var api_url = "https://api.cosmicjs.com"; var api_version = "v1"; module.exports = { getBucket: function(config, callback) { var endpoint = api_url + "/" + api_version + "/" + config.bucket.slug + "/?read_key=" + config.bucket.read_key; fetch(endpoint).then(function(response) { if (response.status >= 400) { var err = { message: "There was an error with this request." }; return callback(err, false) } return response.json() }).then(function(response) { return callback(false, response) }) }, getObjects: function(config, callback) { var endpoint = api_url + "/" + api_version + "/" + config.bucket.slug + "/objects?read_key=" + config.bucket.read_key; fetch(endpoint).then(function(response) { if (response.status >= 400) { var err = { message: "There was an error with this request." }; return callback(err, false) } return response.json() }).then(function(response) { var cosmic = {}; var objects = response.objects; cosmic.objects = {}; cosmic.objects.all = objects; cosmic.objects.type = _.groupBy(objects, "type_slug"); cosmic.object = _.map(objects, keyMetafields); cosmic.object = _.keyBy(cosmic.object, "slug"); return callback(false, cosmic) }) }, getObjectType: function(config, object, callback) { var endpoint = api_url + "/" + api_version + "/" + config.bucket.slug + "/object-type/" + object.type_slug + "?read_key=" + config.bucket.read_key; if (object.limit) endpoint += "&limit=" + object.limit; if (object.skip) endpoint += "&skip=" + object.skip; fetch(endpoint).then(function(response) { if (response.status >= 400) { var err = { message: "There was an error with this request." }; return callback(err, false) } return response.json() }).then(function(response) { var cosmic = {}; var objects = response.objects; cosmic.objects = {}; cosmic.objects.all = objects; cosmic.object = _.map(objects, keyMetafields); cosmic.object = _.keyBy(cosmic.object, "slug"); cosmic.total = response.total; return callback(false, cosmic) }) }, getObject: function(config, object, callback) { var endpoint = api_url + "/" + api_version + "/" + config.bucket.slug + "/object/" + object.slug + "?read_key=" + config.bucket.read_key; if (object._id) { endpoint = api_url + "/" + api_version + "/" + config.bucket.slug + "/object-by-id/" + object._id + "?read_key=" + config.bucket.read_key } fetch(endpoint).then(function(response) { if (response.status >= 400) { var err = { message: "There was an error with this request." }; return callback(err, false) } return response.json() }).then(function(response) { var cosmic = {}; var object = response.object; var metafields = object.metafields; if (metafields) { object.metafield = _.keyBy(metafields, "key") } cosmic.object = object; return callback(false, cosmic) }) }, getMedia: function(config, callback) { var endpoint = api_url + "/" + api_version + "/" + config.bucket.slug + "/media?read_key=" + config.bucket.read_key; fetch(endpoint).then(function(response) { if (response.status >= 400) { var err = { message: "There was an error with this request." }; return callback(err, false) } return response.json() }).then(function(response) { return callback(false, response) }) }, addObject: function(config, object, callback) { var endpoint = api_url + "/" + api_version + "/" + config.bucket.slug + "/add-object"; fetch(endpoint, { method: "post", headers: { "Content-type": "application/json" }, body: JSON.stringify(object) }).then(function(response) { if (response.status >= 400) { var err = { message: "There was an error with this request." }; return callback(err, false) } return response.json() }).then(function(response) { return callback(false, response) }) }, editObject: function(config, object, callback) { var endpoint = api_url + "/" + api_version + "/" + config.bucket.slug + "/edit-object"; fetch(endpoint, { method: "put", headers: { "Content-type": "application/json" }, body: JSON.stringify(object) }).then(function(response) { if (response.status >= 400) { var err = { message: "There was an error with this request." }; return callback(err, false) } return response.json() }).then(function(response) { return callback(false, response) }) }, deleteObject: function(config, object, callback) { var endpoint = api_url + "/" + api_version + "/" + config.bucket.slug + "/delete-object?write_key="+object.write_key+"&_id="+object._id; fetch(endpoint, { method: "post", headers: { "Content-type": "application/json" } }).then(function(response) { if (response.status >= 400) { var err = { message: "There was an error with this request." }; return callback(err, false) } return response.json() }).then(function(response) { return callback(false, response) }) }, addMedia: function(config, params, callback) { var endpoint = api_url + "/" + api_version + "/" + config.bucket.slug + "/media"; var form = new FormData; if (config.bucket.write_key) form.append("write_key", config.bucket.write_key); form.append("media", params.media); if (params.folder) form.append("folder", params.folder); superagent.post(endpoint).send(form).end(function(err, response) { if (response.status >= 400) { var err = { message: "There was an error with this request." }; return callback(err, false) } return callback(false, response) }) } }; function keyMetafields(object) { var metafields = object.metafields; if (metafields) { object.metafield = _.keyBy(metafields, "key") } return object } }, { "es6-promise": 4, "form-data": 5, "isomorphic-fetch": 6, lodash: 7, superagent: 8 }], 3: [function(require, module, exports) { if (typeof module !== "undefined") { module.exports = Emitter } function Emitter(obj) { if (obj) return mixin(obj) } function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key] } return obj } Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn) { this._callbacks = this._callbacks || {}; (this._callbacks["$" + event] = this._callbacks["$" + event] || []).push(fn); return this }; Emitter.prototype.once = function(event, fn) { function on() { this.off(event, on); fn.apply(this, arguments) } on.fn = fn; this.on(event, on); return this }; Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn) { this._callbacks = this._callbacks || {}; if (0 == arguments.length) { this._callbacks = {}; return this } var callbacks = this._callbacks["$" + event]; if (!callbacks) return this; if (1 == arguments.length) { delete this._callbacks["$" + event]; return this } var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break } } return this }; Emitter.prototype.emit = function(event) { this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1), callbacks = this._callbacks["$" + event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args) } } return this }; Emitter.prototype.listeners = function(event) { this._callbacks = this._callbacks || {}; return this._callbacks["$" + event] || [] }; Emitter.prototype.hasListeners = function(event) { return !!this.listeners(event).length } }, {}], 4: [function(require, module, exports) { (function(process, global) { (function(global, factory) { typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : global.ES6Promise = factory() })(this, function() { "use strict"; function objectOrFunction(x) { return typeof x === "function" || typeof x === "object" && x !== null } function isFunction(x) { return typeof x === "function" } var _isArray = undefined; if (!Array.isArray) { _isArray = function(x) { return Object.prototype.toString.call(x) === "[object Array]" } } else { _isArray = Array.isArray } var isArray = _isArray; var len = 0; var vertxNext = undefined; var customSchedulerFn = undefined; var asap = function asap(callback, arg) { queue[len] = callback; queue[len + 1] = arg; len += 2; if (len === 2) { if (customSchedulerFn) { customSchedulerFn(flush) } else { scheduleFlush() } } }; function setScheduler(scheduleFn) { customSchedulerFn = scheduleFn } function setAsap(asapFn) { asap = asapFn } var browserWindow = typeof window !== "undefined" ? window : undefined; var browserGlobal = browserWindow || {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var isNode = typeof self === "undefined" && typeof process !== "undefined" && {}.toString.call(process) === "[object process]"; var isWorker = typeof Uint8ClampedArray !== "undefined" && typeof importScripts !== "undefined" && typeof MessageChannel !== "undefined"; function useNextTick() { return function() { return process.nextTick(flush) } } function useVertxTimer() { return function() { vertxNext(flush) } } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(""); observer.observe(node, { characterData: true }); return function() { node.data = iterations = ++iterations % 2 } } function useMessageChannel() { var channel = new MessageChannel; channel.port1.onmessage = flush; return function() { return channel.port2.postMessage(0) } } function useSetTimeout() { var globalSetTimeout = setTimeout; return function() { return globalSetTimeout(flush, 1) } } var queue = new Array(1e3); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue[i]; var arg = queue[i + 1]; callback(arg); queue[i] = undefined; queue[i + 1] = undefined } len = 0 } function attemptVertx() { try { var r = require; var vertx = r("vertx"); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer() } catch (e) { return useSetTimeout() } } var scheduleFlush = undefined; if (isNode) { scheduleFlush = useNextTick() } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver() } else if (isWorker) { scheduleFlush = useMessageChannel() } else if (browserWindow === undefined && typeof require === "function") { scheduleFlush = attemptVertx() } else { scheduleFlush = useSetTimeout() } function then(onFulfillment, onRejection) { var _arguments = arguments; var parent = this; var child = new this.constructor(noop); if (child[PROMISE_ID] === undefined) { makePromise(child) } var _state = parent._state; if (_state) { (function() { var callback = _arguments[_state - 1]; asap(function() { return invokeCallback(_state, child, callback, parent._result) }) })() } else { subscribe(parent, child, onFulfillment, onRejection) } return child } function resolve(object) { var Constructor = this; if (object && typeof object === "object" && object.constructor === Constructor) { return object } var promise = new Constructor(noop); _resolve(promise, object); return promise } var PROMISE_ID = Math.random().toString(36).substring(16); function noop() {} var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; var GET_THEN_ERROR = new ErrorObject; function selfFulfillment() { return new TypeError("You cannot resolve a promise with itself") } function cannotReturnOwn() { return new TypeError("A promises callback cannot return that same promise.") } function getThen(promise) { try { return promise.then } catch (error) { GET_THEN_ERROR.error = error; return GET_THEN_ERROR } } function tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler) } catch (e) { return e } } function handleForeignThenable(promise, thenable, then) { asap(function(promise) { var sealed = false; var error = tryThen(then, thenable, function(value) { if (sealed) { return } sealed = true; if (thenable !== value) { _resolve(promise, value) } else { fulfill(promise, value) } }, function(reason) { if (sealed) { return } sealed = true; _reject(promise, reason) }, "Settle: " + (promise._label || " unknown promise")); if (!sealed && error) { sealed = true; _reject(promise, error) } }, promise) } function handleOwnThenable(promise, thenable) { if (thenable._state === FULFILLED) { fulfill(promise, thenable._result) } else if (thenable._state === REJECTED) { _reject(promise, thenable._result) } else { subscribe(thenable, undefined, function(value) { return _resolve(promise, value) }, function(reason) { return _reject(promise, reason) }) } } function handleMaybeThenable(promise, maybeThenable, then$$) { if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) { handleOwnThenable(promise, maybeThenable) } else { if (then$$ === GET_THEN_ERROR) { _reject(promise, GET_THEN_ERROR.error) } else if (then$$ === undefined) { fulfill(promise, maybeThenable) } else if (isFunction(then$$)) { handleForeignThenable(promise, maybeThenable, then$$) } else { fulfill(promise, maybeThenable) } } } function _resolve(promise, value) { if (promise === value) { _reject(promise, selfFulfillment()) } else if (objectOrFunction(value)) { handleMaybeThenable(promise, value, getThen(value)) } else { fulfill(promise, value) } } function publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result) } publish(promise) } function fulfill(promise, value) { if (promise._state !== PENDING) { return } promise._result = value; promise._state = FULFILLED; if (promise._subscribers.length !== 0) { asap(publish, promise) } } function _reject(promise, reason) { if (promise._state !== PENDING) { return } promise._state = REJECTED; promise._result = reason; asap(publishRejection, promise) } function subscribe(parent, child, onFulfillment, onRejection) { var _subscribers = parent._subscribers; var length = _subscribers.length; parent._onerror = null; _subscribers[length] = child; _subscribers[length + FULFILLED] = onFulfillment; _subscribers[length + REJECTED] = onRejection; if (length === 0 && parent._state) { asap(publish, parent) } } function publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return } var child = undefined, callback = undefined, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokeCallback(settled, child, callback, detail) } else { callback(detail) } } promise._subscribers.length = 0 } function ErrorObject() { this.error = null } var TRY_CATCH_ERROR = new ErrorObject; function tryCatch(callback, detail) { try { return callback(detail) } catch (e) { TRY_CATCH_ERROR.error = e; return TRY_CATCH_ERROR } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value = undefined, error = undefined, succeeded = undefined, failed = undefined; if (hasCallback) { value = tryCatch(callback, detail); if (value === TRY_CATCH_ERROR) { failed = true; error = value.error; value = null } else { succeeded = true } if (promise === value) { _reject(promise, cannotReturnOwn()); return } } else { value = detail; succeeded = true } if (promise._state !== PENDING) {} else if (hasCallback && succeeded) { _resolve(promise, value) } else if (failed) { _reject(promise, error) } else if (settled === FULFILLED) { fulfill(promise, value) } else if (settled === REJECTED) { _reject(promise, value) } } function initializePromise(promise, resolver) { try { resolver(function resolvePromise(value) { _resolve(promise, value) }, function rejectPromise(reason) { _reject(promise, reason) }) } catch (e) { _reject(promise, e) } } var id = 0; function nextId() { return id++ } function makePromise(promise) { promise[PROMISE_ID] = id++; promise._state = undefined; promise._result = undefined; promise._subscribers = [] } function Enumerator(Constructor, input) { this._instanceConstructor = Constructor; this.promise = new Constructor(noop); if (!this.promise[PROMISE_ID]) { makePromise(this.promise) } if (isArray(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._result = new Array(this.length); if (this.length === 0) { fulfill(this.promise, this._result) } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { fulfill(this.promise, this._result) } } } else { _reject(this.promise, validationError()) } } function validationError() { return new Error("Array Methods must be provided an Array") } Enumerator.prototype._enumerate = function() { var length = this.length; var _input = this._input; for (var i = 0; this._state === PENDING && i < length; i++) { this._eachEntry(_input[i], i) } }; Enumerator.prototype._eachEntry = function(entry, i) { var c = this._instanceConstructor; var resolve$$ = c.resolve; if (resolve$$ === resolve) { var _then = getThen(entry); if (_then === then && entry._state !== PENDING) { this._settledAt(entry._state, i, entry._result) } else if (typeof _then !== "function") { this._remaining--; this._result[i] = entry } else if (c === Promise) { var promise = new c(noop); handleMaybeThenable(promise, entry, _then); this._willSettleAt(promise, i) } else { this._willSettleAt(new c(function(resolve$$) { return resolve$$(entry) }), i) } } else { this._willSettleAt(resolve$$(entry), i) } }; Enumerator.prototype._settledAt = function(state, i, value) { var promise = this.promise; if (promise._state === PENDING) { this._remaining--; if (state === REJECTED) { _reject(promise, value) } else { this._result[i] = value } } if (this._remaining === 0) { fulfill(promise, this._result) } }; Enumerator.prototype._willSettleAt = function(promise, i) { var enumerator = this; subscribe(promise, undefined, function(value) { return enumerator._settledAt(FULFILLED, i, value) }, function(reason) { return enumerator._settledAt(REJECTED, i, reason) }) }; function all(entries) { return new Enumerator(this, entries).promise } function race(entries) { var Constructor = this; if (!isArray(entries)) { return new Constructor(function(_, reject) { return reject(new TypeError("You must pass an array to race.")) }) } else { return new Constructor(function(resolve, reject) { var length = entries.length; for (var i = 0; i < length; i++) { Constructor.resolve(entries[i]).then(resolve, reject) } }) } } function reject(reason) { var Constructor = this; var promise = new Constructor(noop); _reject(promise, reason); return promise } function needsResolver() { throw new TypeError("You must pass a resolver function as the first argument to the promise constructor") } function needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.") } function Promise(resolver) { this[PROMISE_ID] = nextId(); this._result = this._state = undefined; this._subscribers = []; if (noop !== resolver) { typeof resolver !== "function" && needsResolver(); this instanceof Promise ? initializePromise(this, resolver) : needsNew() } } Promise.all = all; Promise.race = race; Promise.resolve = resolve; Promise.reject = reject; Promise._setScheduler = setScheduler; Promise._setAsap = setAsap; Promise._asap = asap; Promise.prototype = { constructor: Promise, then: then, "catch": function _catch(onRejection) { return this.then(null, onRejection) } }; function polyfill() { var local = undefined; if (typeof global !== "undefined") { local = global } else if (typeof self !== "undefined") { local = self } else { try { local = Function("return this")() } catch (e) { throw new Error("polyfill failed because global object is unavailable in this environment") } } var P = local.Promise; if (P) { var promiseToString = null; try { promiseToString = Object.prototype.toString.call(P.resolve()) } catch (e) {} if (promiseToString === "[object Promise]" && !P.cast) { return } } local.Promise = Promise } polyfill(); Promise.polyfill = polyfill; Promise.Promise = Promise; return Promise }) }).call(this, require("_process"), typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) }, { _process: 16 }], 5: [function(require, module, exports) { module.exports = typeof self == "object" ? self.FormData : window.FormData }, {}], 6: [function(require, module, exports) { require("whatwg-fetch"); module.exports = self.fetch.bind(self) }, { "whatwg-fetch": 15 }], 7: [function(require, module, exports) { (function(global) { (function() { var undefined; var VERSION = "4.17.4"; var LARGE_ARRAY_SIZE = 200; var CORE_ERROR_TEXT = "Unsupported core-js use. Try https://npms.io/search?q=ponyfill.", FUNC_ERROR_TEXT = "Expected a function"; var HASH_UNDEFINED = "__lodash_hash_undefined__"; var MAX_MEMOIZE_SIZE = 500; var PLACEHOLDER = "__lodash_placeholder__"; var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = "..."; var HOT_COUNT = 800, HOT_SPAN = 16; var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e308, NAN = 0 / 0; var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; var wrapFlags = [ ["ary", WRAP_ARY_FLAG], ["bind", WRAP_BIND_FLAG], ["bindKey", WRAP_BIND_KEY_FLAG], ["curry", WRAP_CURRY_FLAG], ["curryRight", WRAP_CURRY_RIGHT_FLAG], ["flip", WRAP_FLIP_FLAG], ["partial", WRAP_PARTIAL_FLAG], ["partialRight", WRAP_PARTIAL_RIGHT_FLAG], ["rearg", WRAP_REARG_FLAG] ]; var argsTag = "[object Arguments]", arrayTag = "[object Array]", asyncTag = "[object AsyncFunction]", boolTag = "[object Boolean]", dateTag = "[object Date]", domExcTag = "[object DOMException]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", nullTag = "[object Null]", objectTag = "[object Object]", promiseTag = "[object Promise]", proxyTag = "[object Proxy]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", undefinedTag = "[object Undefined]", weakMapTag = "[object WeakMap]", weakSetTag = "[object WeakSet]"; var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]"; var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); var reTrim = /^\s+|\s+$/g, reTrimStart = /^\s+/, reTrimEnd = /\s+$/; var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; var reEscapeChar = /\\(\\)?/g; var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; var reFlags = /\w*$/; var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; var reIsBinary = /^0b[01]+$/i; var reIsHostCtor = /^\[object .+?Constructor\]$/; var reIsOctal = /^0o[0-7]+$/i; var reIsUint = /^(?:0|[1-9]\d*)$/; var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; var reNoMatch = /($^)/; var reUnescapedString = /['\n\r\u2028\u2029\\]/g; var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f", reComboHalfMarksRange = "\\ufe20-\\ufe2f", rsComboSymbolsRange = "\\u20d0-\\u20ff", rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = "\\u2700-\\u27bf", rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff", rsMathOpRange = "\\xac\\xb1\\xd7\\xf7", rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf", rsPunctuationRange = "\\u2000-\\u206f", rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde", rsVarRange = "\\ufe0e\\ufe0f", rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; var rsApos = "['’]", rsAstral = "[" + rsAstralRange + "]", rsBreak = "[" + rsBreakRange + "]", rsCombo = "[" + rsComboRange + "]", rsDigits = "\\d+", rsDingbat = "[" + rsDingbatRange + "]", rsLower = "[" + rsLowerRange + "]", rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsUpper = "[" + rsUpperRange + "]", rsZWJ = "\\u200d"; var rsMiscLower = "(?:" + rsLower + "|" + rsMisc + ")", rsMiscUpper = "(?:" + rsUpper + "|" + rsMisc + ")", rsOptContrLower = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?", rsOptContrUpper = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange + "]?", rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*", rsOrdLower = "\\d*(?:(?:1st|2nd|3rd|(?![123])\\dth)\\b)", rsOrdUpper = "\\d*(?:(?:1ST|2ND|3RD|(?![123])\\dTH)\\b)", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq, rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")"; var reApos = RegExp(rsApos, "g"); var reComboMark = RegExp(rsCombo, "g"); var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g"); var reUnicodeWord = RegExp([rsUpper + "?" + rsLower + "+" + rsOptContrLower + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")", rsMiscUpper + "+" + rsOptContrUpper + "(?=" + [rsBreak, rsUpper + rsMiscLower, "$"].join("|") + ")", rsUpper + "?" + rsMiscLower + "+" + rsOptContrLower, rsUpper + "+" + rsOptContrUpper, rsOrdUpper, rsOrdLower, rsDigits, rsEmoji].join("|"), "g"); var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + "]"); var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; var contextProps = ["Array", "Buffer", "DataView", "Date", "Error", "Float32Array", "Float64Array", "Function", "Int8Array", "Int16Array", "Int32Array", "Map", "Math", "Object", "Promise", "RegExp", "Set", "String", "Symbol", "TypeError", "Uint8Array", "Uint8ClampedArray", "Uint16Array", "Uint32Array", "WeakMap", "_", "clearTimeout", "isFinite", "parseInt", "setTimeout"]; var templateCounter = -1; var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; var deburredLetters = { "À": "A", "Á": "A", "Â": "A", "Ã": "A", "Ä": "A", "Å": "A", "à": "a", "á": "a", "â": "a", "ã": "a", "ä": "a", "å": "a", "Ç": "C", "ç": "c", "Ð": "D", "ð": "d", "È": "E", "É": "E", "Ê": "E", "Ë": "E", "è": "e", "é": "e", "ê": "e", "ë": "e", "Ì": "I", "Í": "I", "Î": "I", "Ï": "I", "ì": "i", "í": "i", "î": "i", "ï": "i", "Ñ": "N", "ñ": "n", "Ò": "O", "Ó": "O", "Ô": "O", "Õ": "O", "Ö": "O", "Ø": "O", "ò": "o", "ó": "o", "ô": "o", "õ": "o", "ö": "o", "ø": "o", "Ù": "U", "Ú": "U", "Û": "U", "Ü": "U", "ù": "u", "ú": "u", "û": "u", "ü": "u", "Ý": "Y", "ý": "y", "ÿ": "y", "Æ": "Ae", "æ": "ae", "Þ": "Th", "þ": "th", "ß": "ss", "Ā": "A", "Ă": "A", "Ą": "A", "ā": "a", "ă": "a", "ą": "a", "Ć": "C", "Ĉ": "C", "Ċ": "C", "Č": "C", "ć": "c", "ĉ": "c", "ċ": "c", "č": "c", "Ď": "D", "Đ": "D", "ď": "d", "đ": "d", "Ē": "E", "Ĕ": "E", "Ė": "E", "Ę": "E", "Ě": "E", "ē": "e", "ĕ": "e", "ė": "e", "ę": "e", "ě": "e", "Ĝ": "G", "Ğ": "G", "Ġ": "G", "Ģ": "G", "ĝ": "g", "ğ": "g", "ġ": "g", "ģ": "g", "Ĥ": "H", "Ħ": "H", "ĥ": "h", "ħ": "h", "Ĩ": "I", "Ī": "I", "Ĭ": "I", "Į": "I", "İ": "I", "ĩ": "i", "ī": "i", "ĭ": "i", "į": "i", "ı": "i", "Ĵ": "J", "ĵ": "j", "Ķ": "K", "ķ": "k", "ĸ": "k", "Ĺ": "L", "Ļ": "L", "Ľ": "L", "Ŀ": "L", "Ł": "L", "ĺ": "l", "ļ": "l", "ľ": "l", "ŀ": "l", "ł": "l", "Ń": "N", "Ņ": "N", "Ň": "N", "Ŋ": "N", "ń": "n", "ņ": "n", "ň": "n", "ŋ": "n", "Ō": "O", "Ŏ": "O", "Ő": "O", "ō": "o", "ŏ": "o", "ő": "o", "Ŕ": "R", "Ŗ": "R", "Ř": "R", "ŕ": "r", "ŗ": "r", "ř": "r", "Ś": "S", "Ŝ": "S", "Ş": "S", "Š": "S", "ś": "s", "ŝ": "s", "ş": "s", "š": "s", "Ţ": "T", "Ť": "T", "Ŧ": "T", "ţ": "t", "ť": "t", "ŧ": "t", "Ũ": "U", "Ū": "U", "Ŭ": "U", "Ů": "U", "Ű": "U", "Ų": "U", "ũ": "u", "ū": "u", "ŭ": "u", "ů": "u", "ű": "u", "ų": "u", "Ŵ": "W", "ŵ": "w", "Ŷ": "Y", "ŷ": "y", "Ÿ": "Y", "Ź": "Z", "Ż": "Z", "Ž": "Z", "ź": "z", "ż": "z", "ž": "z", "IJ": "IJ", "ij": "ij", "Œ": "Oe", "œ": "oe", "ʼn": "'n", "ſ": "s" }; var htmlEscapes = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }; var htmlUnescapes = { "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": '"', "&#39;": "'" }; var stringEscapes = { "\\": "\\", "'": "'", "\n": "n", "\r": "r", "\u2028": "u2028", "\u2029": "u2029" }; var freeParseFloat = parseFloat, freeParseInt = parseInt; var freeGlobal = typeof global == "object" && global && global.Object === Object && global; var freeSelf = typeof self == "object" && self && self.Object === Object && self; var root = freeGlobal || freeSelf || Function("return this")(); var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports; var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module; var moduleExports = freeModule && freeModule.exports === freeExports; var freeProcess = moduleExports && freeGlobal.process; var nodeUtil = function() { try { return freeProcess && freeProcess.binding && freeProcess.binding("util") } catch (e) {} }(); var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; function addMapEntry(map, pair) { map.set(pair[0], pair[1]); return map } function addSetEntry(set, value) { set.add(value); return set } function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]) } return func.apply(thisArg, args) } function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array) } return accumulator } function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break } } return array } function arrayEachRight(array, iteratee) { var length = array == null ? 0 : array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break } } return array } function arrayEvery(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false } } return true } function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value } } return result } function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1 } function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true } } return false } function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array) } return result } function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index] } return array } function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index] } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array) } return accumulator } function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[--length] } while (length--) { accumulator = iteratee(accumulator, array[length], length, array) } return accumulator } function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true } } return false } var asciiSize = baseProperty("length"); function asciiToArray(string) { return string.split("") } function asciiWords(string) { return string.match(reAsciiWord) || [] } function baseFindKey(collection, predicate, eachFunc) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = key; return false } }); return result } function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while (fromRight ? index-- : ++index < length) { if (predicate(array[index], index, array)) { return index } } return -1 } function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex) } function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index } } return -1 } function baseIsNaN(value) { return value !== value } function baseMean(array, iteratee) { var length = array == null ? 0 : array.length; return length ? baseSum(array, iteratee) / length : NAN } function baseProperty(key) { return function(object) { return object == null ? undefined : object[key] } } function basePropertyOf(object) { return function(key) { return object == null ? undefined : object[key] } } function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection) }); return accumulator } function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value } return array } function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : result + current } } return result } function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index) } return result } function baseToPairs(object, props) { return arrayMap(props, function(key) { return [key, object[key]] }) } function baseUnary(func) { return function(value) { return func(value) } } function baseValues(object, props) { return arrayMap(props, function(key) { return object[key] }) } function cacheHas(cache, key) { return cache.has(key) } function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index } function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index } function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result } } return result } var deburrLetter = basePropertyOf(deburredLetters); var escapeHtmlChar = basePropertyOf(htmlEscapes); function escapeStringChar(chr) { return "\\" + stringEscapes[chr] } function getValue(object, key) { return object == null ? undefined : object[key] } function hasUnicode(string) { return reHasUnicode.test(string) } function hasUnicodeWord(string) { return reHasUnicodeWord.test(string) } function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { result.push(data.value) } return result } function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value] }); return result } function overArg(func, transform) { return function(arg) { return func(transform(arg)) } } function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index } } return result } function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value }); return result } function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = [value, value] }); return result } function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index } } return -1 } function strictLastIndexOf(array, value, fromIndex) { var index = fromIndex + 1; while (index--) { if (array[index] === value) { return index } } return index } function stringSize(string) { return hasUnicode(string) ? unicodeSize(string) : asciiSize(string) } function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string) } var unescapeHtmlChar = basePropertyOf(htmlUnescapes); function unicodeSize(string) { var result = reUnicode.lastIndex = 0; while (reUnicode.test(string)) { ++result } return result } function unicodeToArray(string) { return string.match(reUnicode) || [] } function unicodeWords(string) { return string.match(reUnicodeWord) || [] } var runInContext = function runInContext(context) { context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; var coreJsData = context["__core-js_shared__"]; var funcToString = funcProto.toString; var hasOwnProperty = objectProto.hasOwnProperty; var idCounter = 0; var maskSrcKey = function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); return uid ? "Symbol(src)_1." + uid : "" }(); var nativeObjectToString = objectProto.toString; var objectCtorString = funcToString.call(Object); var oldDash = root._; var reIsNative = RegExp("^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"); var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, symIterator = Symbol ? Symbol.iterator : undefined, symToStringTag = Symbol ? Symbol.toStringTag : undefined; var defineProperty = function() { try { var func = getNative(Object, "defineProperty"); func({}, "", {}); return func } catch (e) {} }(); var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; var DataView = getNative(context, "DataView"), Map = getNative(context, "Map"), Promise = getNative(context, "Promise"), Set = getNative(context, "Set"), WeakMap = getNative(context, "WeakMap"), nativeCreate = getNative(Object, "create"); var metaMap = WeakMap && new WeakMap; var realNames = {}; var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value } if (hasOwnProperty.call(value, "__wrapped__")) { return wrapperClone(value) } } return new LodashWrapper(value) } var baseCreate = function() { function object() {} return function(proto) { if (!isObject(proto)) { return {} } if (objectCreate) { return objectCreate(proto) } object.prototype = proto; var result = new object; object.prototype = undefined; return result } }(); function baseLodash() {} function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined } lodash.templateSettings = { escape: reEscape, evaluate: reEvaluate, interpolate: reInterpolate, variable: "", imports: { _: lodash } }; lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = [] } function lazyClone() { var result = new LazyWrapper(this.__wrapped__); result.__actions__ = copyArray(this.__actions__); result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = copyArray(this.__iteratees__); result.__takeCount__ = this.__takeCount__; result.__views__ = copyArray(this.__views__); return result } function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); result.__dir__ = -1; result.__filtered__ = true } else { result = this.clone(); result.__dir__ *= -1 } return result } function lazyValue() { var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : start - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); if (!isArr || !isRight && arrLength == length && takeCount == length) { return baseWrapperValue(array, this.__actions__) } var result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer } else { break outer } } } result[resIndex++] = value } return result } LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]) } } function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0 } function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result } function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result } return hasOwnProperty.call(data, key) ? data[key] : undefined } function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key) } function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED : value; return this } Hash.prototype.clear = hashClear; Hash.prototype["delete"] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]) } } function listCacheClear() { this.__data__ = []; this.size = 0 } function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop() } else { splice.call(data, index, 1) }--this.size; return true } function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1] } function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1 } function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]) } else { data[index][1] = value } return this } ListCache.prototype.clear = listCacheClear; ListCache.prototype["delete"] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]) } } function mapCacheClear() { this.size = 0; this.__data__ = { hash: new Hash, map: new(Map || ListCache), string: new Hash } } function mapCacheDelete(key) { var result = getMapData(this, key)["delete"](key); this.size -= result ? 1 : 0; return result } function mapCacheGet(key) { return getMapData(this, key).get(key) } function mapCacheHas(key) { return getMapData(this, key).has(key) } function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this } MapCache.prototype.clear = mapCacheClear; MapCache.prototype["delete"] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]) } } function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this } function setCacheHas(value) { return this.__data__.has(value) } SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size } function stackClear() { this.__data__ = new ListCache; this.size = 0 } function stackDelete(key) { var data = this.__data__, result = data["delete"](key); this.size = data.size; return result } function stackGet(key) { return this.__data__.get(key) } function stackHas(key) { return this.__data__.has(key) } function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || pairs.length < LARGE_ARRAY_SIZE - 1) { pairs.push([key, value]); this.size = ++data.size; return this } data = this.__data__ = new MapCache(pairs) } data.set(key, value); this.size = data.size; return this } Stack.prototype.clear = stackClear; Stack.prototype["delete"] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == "length" || isBuff && (key == "offset" || key == "parent") || isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || isIndex(key, length)))) { result.push(key) } } return result } function arraySample(array) { var length = array.length; return length ? array[baseRandom(0, length - 1)] : undefined } function arraySampleSize(array, n) { return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)) } function arrayShuffle(array) { return shuffleSelf(copyArray(array)) } function assignMergeValue(object, key, value) { if (value !== undefined && !eq(object[key], value) || value === undefined && !(key in object)) { baseAssignValue(object, key, value) } } function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || value === undefined && !(key in object)) { baseAssignValue(object, key, value) } } function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length } } return -1 } function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection) }); return accumulator } function baseAssign(object, source) { return object && copyObject(source, keys(source), object) } function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object) } function baseAssignValue(object, key, value) { if (key == "__proto__" && defineProperty) { defineProperty(object, key, { configurable: true, enumerable: true, value: value, writable: true }) } else { object[key] = value } } function baseAt(object, paths) { var index = -1, length = paths.length, result = Array(length), skip = object == null; while (++index < length) { result[index] = skip ? undefined : get(object, paths[index]) } return result } function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper } if (lower !== undefined) { number = number >= lower ? number : lower } } return number } function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value) } if (result !== undefined) { return result } if (!isObject(value)) { return value } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result) } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep) } if (tag == objectTag || tag == argsTag || isFunc && !object) { result = isFlat || isFunc ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)) } } else { if (!cloneableTags[tag]) { return object ? value : {} } result = initCloneByTag(value, tag, baseClone, isDeep) } } stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked } stack.set(value, result); var keysFunc = isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys; var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key] } assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)) }); return result } function baseConforms(source) { var props = keys(source); return function(object) { return baseConformsTo(object, source, props) } } function baseConformsTo(object, source, props) { var length = props.length; if (object == null) { return !length } object = Object(object); while (length--) { var key = props[length], predicate = source[key], value = object[key]; if (value === undefined && !(key in object) || !predicate(value)) { return false } } return true } function baseDelay(func, wait, args) { if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT) } return setTimeout(function() { func.apply(undefined, args) }, wait) } function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)) } if (comparator) { includes = arrayIncludesWith; isCommon = false } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values) } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = comparator || value !== 0 ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer } } result.push(value) } else if (!includes(values, computed, comparator)) { result.push(value) } } return result } var baseEach = createBaseEach(baseForOwn); var baseEachRight = createBaseEach(baseForOwnRight, true); function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { result = !!predicate(value, index, collection); return result }); return result } function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { var value = array[index], current = iteratee(value); if (current != null && (computed === undefined ? current === current && !isSymbol(current) : comparator(current, computed))) { var computed = current, result = value } } return result } function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); if (start < 0) { start = -start > length ? 0 : length + start } end = end === undefined || end > length ? length : toInteger(end); if (end < 0) { end += length } end = start > end ? 0 : toLength(end); while (start < end) { array[start++] = value } return array } function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value) } }); return result } function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { baseFlatten(value, depth - 1, predicate, isStrict, result) } else { arrayPush(result, value) } } else if (!isStrict) { result[result.length] = value } } return result } var baseFor = createBaseFor(); var baseForRight = createBaseFor(true); function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys) } function baseForOwnRight(object, iteratee) { return object && baseForRight(object, iteratee, keys) } function baseFunctions(object, props) { return arrayFilter(props, function(key) { return isFunction(object[key]) }) } function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])] } return index && index == length ? object : undefined } function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)) } function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag } return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value) } function baseGt(value, other) { return value > other } function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key) } function baseHasIn(object, key) { return object != null && key in Object(object) } function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end) } function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)) } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || length >= 120 && array.length >= 120) ? new SetCache(othIndex && array) : undefined } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = comparator || value !== 0 ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator))) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator))) { continue outer } } if (seen) { seen.push(computed) } result.push(value) } } return result } function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object) }); return accumulator } function baseInvoke(object, path, args) { path = castPath(path, object); object = parent(object, path); var func = object == null ? object : object[toKey(last(path))]; return func == null ? undefined : apply(func, object, args) } function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag } function baseIsArrayBuffer(value) { return isObjectLike(value) && baseGetTag(value) == arrayBufferTag } function baseIsDate(value) { return isObjectLike(value) && baseGetTag(value) == dateTag } function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true } if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) { return value !== value && other !== other } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack) } function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false } objIsArr = true; objIsObj = false } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack) } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty.call(other, "__wrapped__"); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack) } } if (!isSameTag) { return false } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack) } function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag } function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length } object = Object(object); while (index--) { var data = matchData[index]; if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) { return false } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack) } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result)) { return false } } } return true } function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)) } function baseIsRegExp(value) { return isObjectLike(value) && baseGetTag(value) == regexpTag } function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag } function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)] } function baseIteratee(value) { if (typeof value == "function") { return value } if (value == null) { return identity } if (typeof value == "object") { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value) } return property(value) } function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object) } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != "constructor") { result.push(key) } } return result } function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object) } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == "constructor" && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key) } } return result } function baseLt(value, other) { return value < other } function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection) }); return result } function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]) } return function(object) { return object === source || baseIsMatch(object, source, matchData) } } function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue) } return function(object) { var objValue = get(object, path); return objValue === undefined && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG) } } function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return } baseFor(source, function(srcValue, key) { if (isObject(srcValue)) { stack || (stack = new Stack); baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack) } else { var newValue = customizer ? customizer(object[key], srcValue, key + "", object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue } assignMergeValue(object, key, newValue) } }, keysIn) } function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = object[key], srcValue = source[key], stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return } var newValue = customizer ? customizer(objValue, srcValue, key + "", object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue) } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true) } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true) } else { newValue = [] } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue) } else if (!isObject(objValue) || srcIndex && isFunction(objValue)) { newValue = initCloneObject(srcValue) } } else { isCommon = false } } if (isCommon) { stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack["delete"](srcValue) } assignMergeValue(object, key, newValue) } function baseNth(array, n) { var length = array.length; if (!length) { return } n += n < 0 ? length : 0; return isIndex(n, length) ? array[n] : undefined } function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value) }); return { criteria: criteria, index: ++index, value: value } }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders) }) } function basePick(object, paths) { return basePickBy(object, paths, function(value, path) { return hasIn(object, path) }) } function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, castPath(path, object), value) } } return result } function basePropertyDeep(path) { return function(object) { return baseGet(object, path) } } function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (array === values) { values = copyArray(values) } if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)) } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1) } splice.call(array, fromIndex, 1) } } return array } function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1) } else { baseUnset(array, index) } } } return array } function baseRandom(lower, upper) { return lower + nativeFloor(nativeRandom() * (upper - lower + 1)) } function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step } return result } function baseRepeat(string, n) { var result = ""; if (!string || n < 1 || n > MAX_SAFE_INTEGER) { return result } do { if (n % 2) { result += string } n = nativeFloor(n / 2); if (n) { string += string } } while (n); return result } function baseRest(func, start) { return setToString(overRest(func, start, identity), func + "") } function baseSample(collection) { return arraySample(values(collection)) } function baseSampleSize(collection, n) { var array = values(collection); return shuffleSelf(array, baseClamp(n, 0, array.length)) } function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object } path = castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {} } } assignValue(nested, key, newValue); nested = nested[key] } return object } var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func }; var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, "toString", { configurable: true, enumerable: false, value: constant(string), writable: true }) }; function baseShuffle(collection) { return shuffleSelf(values(collection)) } function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : length + start } end = end > length ? length : end; if (end < 0) { end += length } length = start > end ? 0 : end - start >>> 0; start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start] } return result } function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result }); return !!result } function baseSortedIndex(array, value, retHighest) { var low = 0, high = array == null ? low : array.length; if (typeof value == "number" && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = low + high >>> 1, computed = array[mid]; if (computed !== null && !isSymbol(computed) && (retHighest ? computed <= value : computed < value)) { low = mid + 1 } else { high = mid } } return high } return baseSortedIndexBy(array, value, identity, retHighest) } function baseSortedIndexBy(array, value, iteratee, retHighest) { value = iteratee(value); var low = 0, high = array == null ? 0 : array.length, valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined; while (low < high) { var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = computed !== undefined, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); if (valIsNaN) { var setLow = retHighest || othIsReflexive } else if (valIsUndefined) { setLow = othIsReflexive && (retHighest || othIsDefined) } else if (valIsNull) { setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull) } else if (valIsSymbol) { setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol) } else if (othIsNull || othIsSymbol) { setLow = false } else { setLow = retHighest ? computed <= value : computed < value } if (setLow) { low = mid + 1 } else { high = mid } } return nativeMin(high, MAX_ARRAY_INDEX) } function baseSortedUniq(array, iteratee) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (!index || !eq(computed, seen)) { var seen = computed; result[resIndex++] = value === 0 ? 0 : value } } return result } function baseToNumber(value) { if (typeof value == "number") { return value } if (isSymbol(value)) { return NAN } return +value } function baseToString(value) { if (typeof value == "string") { return value } if (isArray(value)) { return arrayMap(value, baseToString) + "" } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : "" } var result = value + ""; return result == "0" && 1 / value == -INFINITY ? "-0" : result } function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set) } isCommon = false; includes = cacheHas; seen = new SetCache } else { seen = iteratee ? [] : result } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = comparator || value !== 0 ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer } } if (iteratee) { seen.push(computed) } result.push(value) } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed) } result.push(value) } } return result } function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); return object == null || delete object[toKey(last(path))] } function baseUpdate(object, path, updater, customizer) { return baseSet(object, path, updater(baseGet(object, path)), customizer) } function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, fromRight ? 0 : index, fromRight ? index + 1 : length) : baseSlice(array, fromRight ? index + 1 : 0, fromRight ? length : index) } function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value() } return arrayReduce(actions, function(result, action) { return action.func.apply(action.thisArg, arrayPush([result], action.args)) }, result) } function baseXor(arrays, iteratee, comparator) { var length = arrays.length; if (length < 2) { return length ? baseUniq(arrays[0]) : [] } var index = -1, result = Array(length); while (++index < length) { var array = arrays[index], othIndex = -1; while (++othIndex < length) { if (othIndex != index) { result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator) } } } return baseUniq(baseFlatten(result, 1), iteratee, comparator) } function baseZipObject(props, values, assignFunc) { var index = -1, length = props.length, valsLength = values.length, result = {}; while (++index < length) { var value = index < valsLength ? values[index] : undefined; assignFunc(result, props[index], value) } return result } function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : [] } function castFunction(value) { return typeof value == "function" ? value : identity } function castPath(value, object) { if (isArray(value)) { return value } return isKey(value, object) ? [value] : stringToPath(toString(value)) } var castRest = baseRest; function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return !start && end >= length ? array : baseSlice(array, start, end) } var clearTimeout = ctxClearTimeout || function(id) { return root.clearTimeout(id) }; function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice() } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result } function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result } function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength) } function cloneMap(map, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map); return arrayReduce(array, addMapEntry, new map.constructor) } function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result } function cloneSet(set, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set); return arrayReduce(array, addSetEntry, new set.constructor) } function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {} } function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length) } function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) { return 1 } if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) { return -1 } } return 0 } function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result } var order = orders[index]; return result * (order == "desc" ? -1 : 1) } } return object.index - other.index } function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex] } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex] } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++] } return result } function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex] } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex] } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++] } } return result } function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index] } return array } function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key] } if (isNew) { baseAssignValue(object, key, newValue) } else { assignValue(object, key, newValue) } } return object } function copySymbols(source, object) { return copyObject(source, getSymbols(source), object) } function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object) } function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee, 2), accumulator) } } function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1 } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer) } } return object }) } function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee) } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while (fromRight ? index-- : ++index < length) { if (iteratee(iterable[index], index, iterable) === false) { break } } return collection } } function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break } } return object } } function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = this && this !== root && this instanceof wrapper ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments) } return wrapper } function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string.slice(1); return chr[methodName]() + trailing } } function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string).replace(reApos, "")), callback, "") } } function createCtor(Ctor) { return function() { var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]) } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); return isObject(result) ? result : thisBinding } } function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index] } var holders = length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length) } var fn = this && this !== root && this instanceof wrapper ? Ctor : func; return apply(fn, this, args) } return wrapper } function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = getIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable) } } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined } } function createFlow(fromRight) { return flatRest(function(funcs) { var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse() } while (index--) { var func = funcs[index]; if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT) } if (prereq && !wrapper && getFuncName(func) == "wrapper") { var wrapper = new LodashWrapper([], true) } } index = wrapper ? index : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == "wrapper" ? getData(func) : undefined; if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]) } else { wrapper = func.length == 1 && isLaziable(func) ? wrapper[funcName]() : wrapper.thru(func) } } return function() { var args = arguments, value = args[0]; if (wrapper && args.length == 1 && isArray(value)) { return wrapper.plant(value).value() } var index = 0, result = length ? funcs[index].apply(this, args) : value; while (++index < length) { result = funcs[index].call(this, result) } return result } }) } function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index] } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder) } if (partials) { args = composeArgs(args, partials, holders, isCurried) } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried) } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length) } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos) } else if (isFlip && length > 1) { args.reverse() } if (isAry && ary < length) { args.length = ary } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn) } return fn.apply(thisBinding, args) } return wrapper } function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}) } } function createMathOperation(operator, defaultValue) { return function(value, other) { var result; if (value === undefined && other === undefined) { return defaultValue } if (value !== undefined) { result = value } if (other !== undefined) { if (result === undefined) { return other } if (typeof value == "string" || typeof other == "string") { value = baseToString(value); other = baseToString(other) } else { value = baseToNumber(value); other = baseToNumber(other) } result = operator(value, other) } return result } } function createOver(arrayFunc) { return flatRest(function(iteratees) { iteratees = arrayMap(iteratees, baseUnary(getIteratee())); return baseRest(function(args) { var thisArg = this; return arrayFunc(iteratees, function(iteratee) { return apply(iteratee, thisArg, args) }) }) }) } function createPadding(length, chars) { chars = chars === undefined ? " " : baseToString(chars); var charsLength = chars.length; if (charsLength < 2) { return charsLength ? baseRepeat(chars, length) : chars } var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join("") : result.slice(0, length) } function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = this && this !== root && this instanceof wrapper ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex] } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex] } return apply(fn, isBind ? thisArg : this, args) } return wrapper } function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != "number" && isIterateeCall(start, end, step)) { end = step = undefined } start = toFinite(start); if (end === undefined) { end = start; start = 0 } else { end = toFinite(end) } step = step === undefined ? start < end ? 1 : -1 : toFinite(step); return baseRange(start, end, step, fromRight) } } function createRelationalOperation(operator) { return function(value, other) { if (!(typeof value == "string" && typeof other == "string")) { value = toNumber(value); other = toNumber(other) } return operator(value, other) } } function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG; bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG) } var newData = [func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData) } result.placeholder = placeholder; return setWrapToString(result, func, bitmask) } function createRound(methodName) { var func = Math[methodName]; return function(number, precision) { number = toNumber(number); precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); if (precision) { var pair = (toString(number) + "e").split("e"), value = func(pair[0] + "e" + (+pair[1] + precision)); pair = (toString(value) + "e").split("e"); return +(pair[0] + "e" + (+pair[1] - precision)) } return func(number) } } var createSet = !(Set && 1 / setToArray(new Set([, -0]))[1] == INFINITY) ? noop : function(values) { return new Set(values) }; function createToPairs(keysFunc) { return function(object) { var tag = getTag(object); if (tag == mapTag) { return mapToArray(object) } if (tag == setTag) { return setToPairs(object) } return baseToPairs(object, keysFunc(object)) } } function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT) } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined } var data = isBindKey ? undefined : getData(func); var newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity]; if (data) { mergeData(newData, data) } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? isBindKey ? 0 : func.length : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG) } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg) } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity) } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials) } else { result = createHybrid.apply(undefined, newData) } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask) } function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key)) { return srcValue } return objValue } function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { stack.set(srcValue, objValue); baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); stack["delete"](srcValue) } return objValue } function customOmitClone(value) { return isPlainObject(value) ? undefined : value } function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false } var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other } var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack) } if (compared !== undefined) { if (compared) { continue } result = false; break } if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex) } })) { result = false; break } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { result = false; break } } stack["delete"](array); stack["delete"](other); return result } function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { return false } object = object.buffer; other = other.buffer; case arrayBufferTag: if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false } return true; case boolTag: case dateTag: case numberTag: return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: return object == other + ""; case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false } var stacked = stack.get(object); if (stacked) { return stacked == other } bitmask |= COMPARE_UNORDERED_FLAG; stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack["delete"](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other) } } return false } function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false } } var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack) } if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { result = false; break } skipCtor || (skipCtor = key == "constructor") } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) { result = false } } stack["delete"](object); stack["delete"](other); return result } function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + "") } function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols) } function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn) } var getData = !metaMap ? noop : function(func) { return metaMap.get(func) }; function getFuncName(func) { var result = func.name + "", array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name } } return result } function getHolder(func) { var object = hasOwnProperty.call(lodash, "placeholder") ? lodash : func; return object.placeholder } function getIteratee() { var result = lodash.iteratee || iteratee; result = result === iteratee ? baseIteratee : result; return arguments.length ? result(arguments[0], arguments[1]) : result } function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map } function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)] } return result } function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined } function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag } else { delete value[symToStringTag] } } return result } var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return [] } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol) }) }; var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object) } return result }; var getTag = baseGetTag; if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map) != mapTag || Promise && getTag(Promise.resolve()) != promiseTag || Set && getTag(new Set) != setTag || WeakMap && getTag(new WeakMap) != weakMapTag) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ""; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag } } return result } } function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case "drop": start += size; break; case "dropRight": end -= size; break; case "take": end = nativeMin(end, start + size); break; case "takeRight": start = nativeMax(start, end - size); break } } return { start: start, end: end } } function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : [] } function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break } object = object[key] } if (result || ++index != length) { return result } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)) } function initCloneArray(array) { var length = array.length, result = array.constructor(length); if (length && typeof array[0] == "string" && hasOwnProperty.call(array, "index")) { result.index = array.index; result.input = array.input } return result } function initCloneObject(object) { return typeof object.constructor == "function" && !isPrototype(object) ? baseCreate(getPrototype(object)) : {} } function initCloneByTag(object, tag, cloneFunc, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return cloneMap(object, isDeep, cloneFunc); case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return cloneSet(object, isDeep, cloneFunc); case symbolTag: return cloneSymbol(object) } } function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? "& " : "") + details[lastIndex]; details = details.join(length > 2 ? ", " : " "); return source.replace(reWrapComment, "{\n/* [wrapped with " + details + "] */\n") } function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]) } function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length) } function isIterateeCall(value, index, object) { if (!isObject(object)) { return false } var type = typeof index; if (type == "number" ? isArrayLike(object) && isIndex(index, object.length) : type == "string" && index in object) { return eq(object[index], value) } return false } function isKey(value, object) { if (isArray(value)) { return false } var type = typeof value; if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol(value)) { return true } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object) } function isKeyable(value) { var type = typeof value; return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null } function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != "function" || !(funcName in LazyWrapper.prototype)) { return false } if (func === other) { return true } var data = getData(other); return !!data && func === data[0] } function isMasked(func) { return !!maskSrcKey && maskSrcKey in func } var isMaskable = coreJsData ? isFunction : stubFalse; function isPrototype(value) { var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; return value === proto } function isStrictComparable(value) { return value === value && !isObject(value) } function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false } return object[key] === srcValue && (srcValue !== undefined || key in Object(object)); } } function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear() } return key }); var cache = result.cache; return result } function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_CURRY_FLAG || srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_REARG_FLAG && data[7].length <= source[8] || srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG) && source[7].length <= source[8] && bitmask == WRAP_CURRY_FLAG; if (!(isCommon || isCombo)) { return data } if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG } var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4] } value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6] } value = source[7]; if (value) { data[7] = value } if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]) } if (data[9] == null) { data[9] = source[9] } data[0] = source[0]; data[1] = newBitmask; return data } function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key) } } return result } function objectToString(value) { return nativeObjectToString.call(value) } function overRest(func, start, transform) { start = nativeMax(start === undefined ? func.length - 1 : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index] } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index] } otherArgs[start] = transform(array); return apply(func, this, otherArgs) } } function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)) } function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined } return array } var setData = shortOut(baseSetData); var setTimeout = ctxSetTimeout || function(func, wait) { return root.setTimeout(func, wait) }; var setToString = shortOut(baseSetToString); function setWrapToString(wrapper, reference, bitmask) { var source = reference + ""; return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))) } function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0] } } else { count = 0 } return func.apply(undefined, arguments) } } function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; size = size === undefined ? length : size; while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value } array.length = size; return array } var stringToPath = memoizeCapped(function(string) { var result = []; if (reLeadingDot.test(string)) { result.push("") } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, "$1") : number || match) }); return result }); function toKey(value) { if (typeof value == "string" || isSymbol(value)) { return value } var result = value + ""; return result == "0" && 1 / value == -INFINITY ? "-0" : result } function toSource(func) { if (func != null) { try { return funcToString.call(func) } catch (e) {} try { return func + "" } catch (e) {} } return "" } function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = "_." + pair[0]; if (bitmask & pair[1] && !arrayIncludes(details, value)) { details.push(value) } }); return details.sort() } function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone() } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result } function chunk(array, size, guard) { if (guard ? isIterateeCall(array, size, guard) : size === undefined) { size = 1 } else { size = nativeMax(toInteger(size), 0) } var length = array == null ? 0 : array.length; if (!length || size < 1) { return [] } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = baseSlice(array, index, index += size) } return result } function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value } } return result } function concat() { var length = arguments.length; if (!length) { return [] } var args = Array(length - 1), array = arguments[0], index = length; while (index--) { args[index - 1] = arguments[index] } return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)) } var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : [] }); var differenceBy = baseRest(function(array, values) { var iteratee = last(values); if (isArrayLikeObject(iteratee)) { iteratee = undefined } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) : [] }); var differenceWith = baseRest(function(array, values) { var comparator = last(values); if (isArrayLikeObject(comparator)) { comparator = undefined } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : [] }); function drop(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return [] } n = guard || n === undefined ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length) } function dropRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return [] } n = guard || n === undefined ? 1 : toInteger(n); n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n) } function dropRightWhile(array, predicate) { return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true, true) : [] } function dropWhile(array, predicate) { return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true) : [] } function fill(array, value, start, end) { var length = array == null ? 0 : array.length; if (!length) { return [] } if (start && typeof start != "number" && isIterateeCall(array, value, start)) { start = 0; end = length } return baseFill(array, value, start, end) } function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1 } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0) } return baseFindIndex(array, getIteratee(predicate, 3), index) } function findLastIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1 } var index = length - 1; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1) } return baseFindIndex(array, getIteratee(predicate, 3), index, true) } function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : [] } function flattenDeep(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, INFINITY) : [] } function flattenDepth(array, depth) { var length = array == null ? 0 : array.length; if (!length) { return [] } depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(array, depth) } function fromPairs(pairs) { var index = -1, length = pairs == null ? 0 : pairs.length, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1] } return result } function head(array) { return array && array.length ? array[0] : undefined } function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1 } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0) } return baseIndexOf(array, value, index) } function initial(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 0, -1) : [] } var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped) : [] }); var intersectionBy = baseRest(function(arrays) { var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (iteratee === last(mapped)) { iteratee = undefined } else { mapped.pop() } return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, getIteratee(iteratee, 2)) : [] }); var intersectionWith = baseRest(function(arrays) { var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); comparator = typeof comparator == "function" ? comparator : undefined; if (comparator) { mapped.pop() } return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, undefined, comparator) : [] }); function join(array, separator) { return array == null ? "" : nativeJoin.call(array, separator) } function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined } function lastIndexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1 } var index = length; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1) } return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true) } function nth(array, n) { return array && array.length ? baseNth(array, toInteger(n)) : undefined } var pull = baseRest(pullAll); function pullAll(array, values) { return array && array.length && values && values.length ? basePullAll(array, values) : array } function pullAllBy(array, values, iteratee) { return array && array.length && values && values.length ? basePullAll(array, values, getIteratee(iteratee, 2)) : array } function pullAllWith(array, values, comparator) { return array && array.length && values && values.length ? basePullAll(array, values, undefined, comparator) : array } var pullAt = flatRest(function(array, indexes) { var length = array == null ? 0 : array.length, result = baseAt(array, indexes); basePullAt(array, arrayMap(indexes, function(index) { return isIndex(index, length) ? +index : index }).sort(compareAscending)); return result }); function remove(array, predicate) { var result = []; if (!(array && array.length)) { return result } var index = -1, indexes = [], length = array.length; predicate = getIteratee(predicate, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index) } } basePullAt(array, indexes); return result } function reverse(array) { return array == null ? array : nativeReverse.call(array) } function slice(array, start, end) { var length = array == null ? 0 : array.length; if (!length) { return [] } if (end && typeof end != "number" && isIterateeCall(array, start, end)) { start = 0; end = length } else { start = start == null ? 0 : toInteger(start); end = end === undefined ? length : toInteger(end) } return baseSlice(array, start, end) } function sortedIndex(array, value) { return baseSortedIndex(array, value) } function sortedIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)) } function sortedIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value); if (index < length && eq(array[index], value)) { return index } } return -1 } function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true) } function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true) } function sortedLastIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value, true) - 1; if (eq(array[index], value)) { return index } } return -1 } function sortedUniq(array) { return array && array.length ? baseSortedUniq(array) : [] } function sortedUniqBy(array, iteratee) { return array && array.length ? baseSortedUniq(array, getIteratee(iteratee, 2)) : [] } function tail(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 1, length) : [] } function take(array, n, guard) { if (!(array && array.length)) { return [] } n = guard || n === undefined ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n) } function takeRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return [] } n = guard || n === undefined ? 1 : toInteger(n); n = length - n; return baseSlice(array, n < 0 ? 0 : n, length) } function takeRightWhile(array, predicate) { return array && array.length ? baseWhile(array, getIteratee(predicate, 3), false, true) : [] } function takeWhile(array, predicate) { return array && array.length ? baseWhile(array, getIteratee(predicate, 3)) : [] } var union = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)) }); var unionBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) }); var unionWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == "function" ? comparator : undefined; return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator) }); function uniq(array) { return array && array.length ? baseUniq(array) : [] } function uniqBy(array, iteratee) { return array && array.length ? baseUniq(array, getIteratee(iteratee, 2)) : [] } function uniqWith(array, comparator) { comparator = typeof comparator == "function" ? comparator : undefined; return array && array.length ? baseUniq(array, undefined, comparator) : [] } function unzip(array) { if (!(array && array.length)) { return [] } var length = 0; array = arrayFilter(array, function(group) { if (isArrayLikeObject(group)) { length = nativeMax(group.length, length); return true } }); return baseTimes(length, function(index) { return arrayMap(array, baseProperty(index)) }) } function unzipWith(array, iteratee) { if (!(array && array.length)) { return [] } var result = unzip(array); if (iteratee == null) { return result } return arrayMap(result, function(group) { return apply(iteratee, undefined, group) }) } var without = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : [] }); var xor = baseRest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)) }); var xorBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined } return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)) }); var xorWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == "function" ? comparator : undefined; return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator) }); var zip = baseRest(unzip); function zipObject(props, values) { return baseZipObject(props || [], values || [], assignValue) } function zipObjectDeep(props, values) { return baseZipObject(props || [], values || [], baseSet) } var zipWith = baseRest(function(arrays) { var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined; iteratee = typeof iteratee == "function" ? (arrays.pop(), iteratee) : undefined; return unzipWith(arrays, iteratee) }); function chain(value) { var result = lodash(value); result.__chain__ = true; return result } function tap(value, interceptor) { interceptor(value); return value } function thru(value, interceptor) { return interceptor(value) } var wrapperAt = flatRest(function(paths) { var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { return baseAt(object, paths) }; if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { return this.thru(interceptor) } value = value.slice(start, +start + (length ? 1 : 0)); value.__actions__.push({ func: thru, args: [interceptor], thisArg: undefined }); return new LodashWrapper(value, this.__chain__).thru(function(array) { if (length && !array.length) { array.push(undefined) } return array }) }); function wrapperChain() { return chain(this) } function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__) } function wrapperNext() { if (this.__values__ === undefined) { this.__values__ = toArray(this.value()) } var done = this.__index__ >= this.__values__.length, value = done ? undefined : this.__values__[this.__index__++]; return { done: done, value: value } } function wrapperToIterator() { return this } function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); clone.__index__ = 0; clone.__values__ = undefined; if (result) { previous.__wrapped__ = clone } else { result = clone } var previous = clone; parent = parent.__wrapped__ } previous.__wrapped__ = value; return result } function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { var wrapped = value; if (this.__actions__.length) { wrapped = new LazyWrapper(this) } wrapped = wrapped.reverse(); wrapped.__actions__.push({ func: thru, args: [reverse], thisArg: undefined }); return new LodashWrapper(wrapped, this.__chain__) } return this.thru(reverse) } function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__) } var countBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { ++result[key] } else { baseAssignValue(result, key, 1) } }); function every(collection, predicate, guard) { var func = isArray(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined } return func(collection, getIteratee(predicate, 3)) } function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)) } var find = createFind(findIndex); var findLast = createFind(findLastIndex); function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1) } function flatMapDeep(collection, iteratee) { return baseFlatten(map(collection, iteratee), INFINITY) } function flatMapDepth(collection, iteratee, depth) { depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(map(collection, iteratee), depth) } function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee, 3)) } function forEachRight(collection, iteratee) { var func = isArray(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee, 3)) } var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value) } else { baseAssignValue(result, key, [value]) } }); function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0) } return isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1 } var invokeMap = baseRest(function(collection, path, args) { var index = -1, isFunc = typeof path == "function", result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value) { result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args) }); return result }); var keyBy = createAggregator(function(result, value, key) { baseAssignValue(result, key, value) }); function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee, 3)) } function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return [] } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees] } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders] } return baseOrderBy(collection, iteratees, orders) } var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value) }, function() { return [ [], [] ] }); function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach) } function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight) } function reject(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, negate(getIteratee(predicate, 3))) } function sample(collection) { var func = isArray(collection) ? arraySample : baseSample; return func(collection) } function sampleSize(collection, n, guard) { if (guard ? isIterateeCall(collection, n, guard) : n === undefined) { n = 1 } else { n = toInteger(n) } var func = isArray(collection) ? arraySampleSize : baseSampleSize; return func(collection, n) } function shuffle(collection) { var func = isArray(collection) ? arrayShuffle : baseShuffle; return func(collection) } function size(collection) { if (collection == null) { return 0 } if (isArrayLike(collection)) { return isString(collection) ? stringSize(collection) : collection.length } var tag = getTag(collection); if (tag == mapTag || tag == setTag) { return collection.size } return baseKeys(collection).length } function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined } return func(collection, getIteratee(predicate, 3)) } var sortBy = baseRest(function(collection, iteratees) { if (collection == null) { return [] } var length = iteratees.length; if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = [] } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]] } return baseOrderBy(collection, baseFlatten(iteratees, 1), []) }); var now = ctxNow || function() { return root.Date.now() }; function after(n, func) { if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT) } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments) } } } function ary(func, n, guard) { n = guard ? undefined : n; n = func && n == null ? func.length : n; return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n) } function before(n, func) { var result; if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT) } n = toInteger(n); return function() { if (--n > 0) { result = func.apply(this, arguments) } if (n <= 1) { func = undefined } return result } } var bind = baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG } return createWrap(func, bitmask, thisArg, partials, holders) }); var bindKey = baseRest(function(object, key, partials) { var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bindKey)); bitmask |= WRAP_PARTIAL_FLAG } return createWrap(key, bitmask, object, partials, holders) }); function curry(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curry.placeholder; return result } function curryRight(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curryRight.placeholder; return result } function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT) } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = "maxWait" in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = "trailing" in options ? !!options.trailing : trailing } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result } function leadingEdge(time) { lastInvokeTime = time; timerId = setTimeout(timerExpired, wait); return leading ? invokeFunc(time) : result } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result = wait - timeSinceLastCall; return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time) } timerId = setTimeout(timerExpired, remainingWait(time)) } function trailingEdge(time) { timerId = undefined; if (trailing && lastArgs) { return invokeFunc(time) } lastArgs = lastThis = undefined; return result } function cancel() { if (timerId !== undefined) { clearTimeout(timerId) } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined } function flush() { return timerId === undefined ? result : trailingEdge(now()) } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime) } if (maxing) { timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime) } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait) } return result } debounced.cancel = cancel; debounced.flush = flush; return debounced } var defer = baseRest(function(func, args) { return baseDelay(func, 1, args) }); var delay = baseRest(function(func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args) }); function flip(func) { return createWrap(func, WRAP_FLIP_FLAG) } function memoize(func, resolver) { if (typeof func != "function" || resolver != null && typeof resolver != "function") { throw new TypeError(FUNC_ERROR_TEXT) } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key) } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result }; memoized.cache = new(memoize.Cache || MapCache); return memoized } memoize.Cache = MapCache; function negate(predicate) { if (typeof predicate != "function") { throw new TypeError(FUNC_ERROR_TEXT) } return function() { var args = arguments; switch (args.length) { case 0: return !predicate.call(this); case 1: return !predicate.call(this, args[0]); case 2: return !predicate.call(this, args[0], args[1]); case 3: return !predicate.call(this, args[0], args[1], args[2]) } return !predicate.apply(this, args) } } function once(func) { return before(2, func) } var overArgs = castRest(function(func, transforms) { transforms = transforms.length == 1 && isArray(transforms[0]) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); var funcsLength = transforms.length; return baseRest(function(args) { var index = -1, length = nativeMin(args.length, funcsLength); while (++index < length) { args[index] = transforms[index].call(this, args[index]) } return apply(func, this, args) }) }); var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders) }); var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders) }); var rearg = flatRest(function(func, indexes) { return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes) }); function rest(func, start) { if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT) } start = start === undefined ? start : toInteger(start); return baseRest(func, start) } function spread(func, start) { if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT) } start = start == null ? 0 : nativeMax(toInteger(start), 0); return baseRest(function(args) { var array = args[start], otherArgs = castSlice(args, 0, start); if (array) { arrayPush(otherArgs, array) } return apply(func, this, otherArgs) }) } function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT) } if (isObject(options)) { leading = "leading" in options ? !!options.leading : leading; trailing = "trailing" in options ? !!options.trailing : trailing } return debounce(func, wait, { leading: leading, maxWait: wait, trailing: trailing }) } function unary(func) { return ary(func, 1) } function wrap(value, wrapper) { return partial(castFunction(wrapper), value) } function castArray() { if (!arguments.length) { return [] } var value = arguments[0]; return isArray(value) ? value : [value] } function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG) } function cloneWith(value, customizer) { customizer = typeof customizer == "function" ? customizer : undefined; return baseClone(value, CLONE_SYMBOLS_FLAG, customizer) } function cloneDeep(value) { return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG) } function cloneDeepWith(value, customizer) { customizer = typeof customizer == "function" ? customizer : undefined; return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer) } function conformsTo(object, source) { return source == null || baseConformsTo(object, source, keys(source)) } function eq(value, other) { return value === other || value !== value && other !== other } var gt = createRelationalOperation(baseGt); var gte = createRelationalOperation(function(value, other) { return value >= other }); var isArguments = baseIsArguments(function() { return arguments }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee") }; var isArray = Array.isArray; var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value) } function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value) } function isBoolean(value) { return value === true || value === false || isObjectLike(value) && baseGetTag(value) == boolTag } var isBuffer = nativeIsBuffer || stubFalse; var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; function isElement(value) { return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value) } function isEmpty(value) { if (value == null) { return true } if (isArrayLike(value) && (isArray(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size } if (isPrototype(value)) { return !baseKeys(value).length } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false } } return true } function isEqual(value, other) { return baseIsEqual(value, other) } function isEqualWith(value, other, customizer) { customizer = typeof customizer == "function" ? customizer : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result } function isError(value) { if (!isObjectLike(value)) { return false } var tag = baseGetTag(value); return tag == errorTag || tag == domExcTag || typeof value.message == "string" && typeof value.name == "string" && !isPlainObject(value) } function isFinite(value) { return typeof value == "number" && nativeIsFinite(value) } function isFunction(value) { if (!isObject(value)) { return false } var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag } function isInteger(value) { return typeof value == "number" && value == toInteger(value) } function isLength(value) { return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER } function isObject(value) { var type = typeof value; return value != null && (type == "object" || type == "function") } function isObjectLike(value) { return value != null && typeof value == "object" } var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; function isMatch(object, source) { return object === source || baseIsMatch(object, source, getMatchData(source)) } function isMatchWith(object, source, customizer) { customizer = typeof customizer == "function" ? customizer : undefined; return baseIsMatch(object, source, getMatchData(source), customizer) } function isNaN(value) { return isNumber(value) && value != +value } function isNative(value) { if (isMaskable(value)) { throw new Error(CORE_ERROR_TEXT) } return baseIsNative(value) } function isNull(value) { return value === null } function isNil(value) { return value == null } function isNumber(value) { return typeof value == "number" || isObjectLike(value) && baseGetTag(value) == numberTag } function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false } var proto = getPrototype(value); if (proto === null) { return true } var Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor; return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString } var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; function isSafeInteger(value) { return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER } var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; function isString(value) { return typeof value == "string" || !isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag } function isSymbol(value) { return typeof value == "symbol" || isObjectLike(value) && baseGetTag(value) == symbolTag; } var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; function isUndefined(value) { return value === undefined } function isWeakMap(value) { return isObjectLike(value) && getTag(value) == weakMapTag } function isWeakSet(value) { return isObjectLike(value) && baseGetTag(value) == weakSetTag } var lt = createRelationalOperation(baseLt); var lte = createRelationalOperation(function(value, other) { return value <= other }); function toArray(value) { if (!value) { return [] } if (isArrayLike(value)) { return isString(value) ? stringToArray(value) : copyArray(value) } if (symIterator && value[symIterator]) { return iteratorToArray(value[symIterator]()) } var tag = getTag(value), func = tag == mapTag ? mapToArray : tag == setTag ? setToArray : values; return func(value) } function toFinite(value) { if (!value) { return value === 0 ? value : 0 } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = value < 0 ? -1 : 1; return sign * MAX_INTEGER } return value === value ? value : 0 } function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? remainder ? result - remainder : result : 0 } function toLength(value) { return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0 } function toNumber(value) { if (typeof value == "number") { return value } if (isSymbol(value)) { return NAN } if (isObject(value)) { var other = typeof value.valueOf == "function" ? value.valueOf() : value; value = isObject(other) ? other + "" : other } if (typeof value != "string") { return value === 0 ? value : +value } value = value.replace(reTrim, ""); var isBinary = reIsBinary.test(value); return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value } function toPlainObject(value) { return copyObject(value, keysIn(value)) } function toSafeInteger(value) { return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : value === 0 ? value : 0 } function toString(value) { return value == null ? "" : baseToString(value) } var assign = createAssigner(function(object, source) { if (isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return } for (var key in source) { if (hasOwnProperty.call(source, key)) { assignValue(object, key, source[key]) } } }); var assignIn = createAssigner(function(object, source) { copyObject(source, keysIn(source), object) }); var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer) }); var assignWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer) }); var at = flatRest(baseAt); function create(prototype, properties) { var result = baseCreate(prototype); return properties == null ? result : baseAssign(result, properties) } var defaults = baseRest(function(args) { args.push(undefined, customDefaultsAssignIn); return apply(assignInWith, undefined, args) }); var defaultsDeep = baseRest(function(args) { args.push(undefined, customDefaultsMerge); return apply(mergeWith, undefined, args) }); function findKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwn) } function findLastKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight) } function forIn(object, iteratee) { return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn) } function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn) } function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)) } function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, getIteratee(iteratee, 3)) } function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)) } function functionsIn(object) { return object == null ? [] : baseFunctions(object, keysIn(object)) } function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result } function has(object, path) { return object != null && hasPath(object, path, baseHas) } function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn) } var invert = createInverter(function(result, value, key) { result[value] = key }, constant(identity)); var invertBy = createInverter(function(result, value, key) { if (hasOwnProperty.call(result, value)) { result[value].push(key) } else { result[value] = [key] } }, getIteratee); var invoke = baseRest(baseInvoke); function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object) } function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object) } function mapKeys(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, iteratee(value, key, object), value) }); return result } function mapValues(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, key, iteratee(value, key, object)) }); return result } var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex) }); var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer) }); var omit = flatRest(function(object, paths) { var result = {}; if (object == null) { return result } var isDeep = false; paths = arrayMap(paths, function(path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path }); copyObject(object, getAllKeysIn(object), result); if (isDeep) { result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone) } var length = paths.length; while (length--) { baseUnset(result, paths[length]) } return result }); function omitBy(object, predicate) { return pickBy(object, negate(getIteratee(predicate))) } var pick = flatRest(function(object, paths) { return object == null ? {} : basePick(object, paths) }); function pickBy(object, predicate) { if (object == null) { return {} } var props = arrayMap(getAllKeysIn(object), function(prop) { return [prop] }); predicate = getIteratee(predicate); return basePickBy(object, props, function(value, path) { return predicate(value, path[0]) }) } function result(object, path, defaultValue) { path = castPath(path, object); var index = -1, length = path.length; if (!length) { length = 1; object = undefined } while (++index < length) { var value = object == null ? undefined : object[toKey(path[index])]; if (value === undefined) { index = length; value = defaultValue } object = isFunction(value) ? value.call(object) : value } return object } function set(object, path, value) { return object == null ? object : baseSet(object, path, value) } function setWith(object, path, value, customizer) { customizer = typeof customizer == "function" ? customizer : undefined; return object == null ? object : baseSet(object, path, value, customizer) } var toPairs = createToPairs(keys); var toPairsIn = createToPairs(keysIn); function transform(object, iteratee, accumulator) { var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); if (accumulator == null) { var Ctor = object && object.constructor; if (isArrLike) { accumulator = isArr ? new Ctor : [] } else if (isObject(object)) { accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {} } else { accumulator = {} } }(isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object) }); return accumulator } function unset(object, path) { return object == null ? true : baseUnset(object, path) } function update(object, path, updater) { return object == null ? object : baseUpdate(object, path, castFunction(updater)) } function updateWith(object, path, updater, customizer) { customizer = typeof customizer == "function" ? customizer : undefined; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer) } function values(object) { return object == null ? [] : baseValues(object, keys(object)) } function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)) } function clamp(number, lower, upper) { if (upper === undefined) { upper = lower; lower = undefined } if (upper !== undefined) { upper = toNumber(upper); upper = upper === upper ? upper : 0 } if (lower !== undefined) { lower = toNumber(lower); lower = lower === lower ? lower : 0 } return baseClamp(toNumber(number), lower, upper) } function inRange(number, start, end) { start = toFinite(start); if (end === undefined) { end = start; start = 0 } else { end = toFinite(end) } number = toNumber(number); return baseInRange(number, start, end) } function random(lower, upper, floating) { if (floating && typeof floating != "boolean" && isIterateeCall(lower, upper, floating)) { upper = floating = undefined } if (floating === undefined) { if (typeof upper == "boolean") { floating = upper; upper = undefined } else if (typeof lower == "boolean") { floating = lower; lower = undefined } } if (lower === undefined && upper === undefined) { lower = 0; upper = 1 } else { lower = toFinite(lower); if (upper === undefined) { upper = lower; lower = 0 } else { upper = toFinite(upper) } } if (lower > upper) { var temp = lower; lower = upper; upper = temp } if (floating || lower % 1 || upper % 1) { var rand = nativeRandom(); return nativeMin(lower + rand * (upper - lower + freeParseFloat("1e-" + ((rand + "").length - 1))), upper) } return baseRandom(lower, upper) } var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word) }); function capitalize(string) { return upperFirst(toString(string).toLowerCase()) } function deburr(string) { string = toString(string); return string && string.replace(reLatin, deburrLetter).replace(reComboMark, "") } function endsWith(string, target, position) { string = toString(string); target = baseToString(target); var length = string.length; position = position === undefined ? length : baseClamp(toInteger(position), 0, length); var end = position; position -= target.length; return position >= 0 && string.slice(position, end) == target } function escape(string) { string = toString(string); return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string } function escapeRegExp(string) { string = toString(string); return string && reHasRegExpChar.test(string) ? string.replace(reRegExpChar, "\\$&") : string } var kebabCase = createCompounder(function(result, word, index) { return result + (index ? "-" : "") + word.toLowerCase() }); var lowerCase = createCompounder(function(result, word, index) { return result + (index ? " " : "") + word.toLowerCase() }); var lowerFirst = createCaseFirst("toLowerCase"); function pad(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; if (!length || strLength >= length) { return string } var mid = (length - strLength) / 2; return createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars) } function padEnd(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return length && strLength < length ? string + createPadding(length - strLength, chars) : string } function padStart(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return length && strLength < length ? createPadding(length - strLength, chars) + string : string } function parseInt(string, radix, guard) { if (guard || radix == null) { radix = 0 } else if (radix) { radix = +radix } return nativeParseInt(toString(string).replace(reTrimStart, ""), radix || 0) } function repeat(string, n, guard) { if (guard ? isIterateeCall(string, n, guard) : n === undefined) { n = 1 } else { n = toInteger(n) } return baseRepeat(toString(string), n) } function replace() { var args = arguments, string = toString(args[0]); return args.length < 3 ? string : string.replace(args[1], args[2]) } var snakeCase = createCompounder(function(result, word, index) { return result + (index ? "_" : "") + word.toLowerCase() }); function split(string, separator, limit) { if (limit && typeof limit != "number" && isIterateeCall(string, separator, limit)) { separator = limit = undefined } limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; if (!limit) { return [] } string = toString(string); if (string && (typeof separator == "string" || separator != null && !isRegExp(separator))) { separator = baseToString(separator); if (!separator && hasUnicode(string)) { return castSlice(stringToArray(string), 0, limit) } } return string.split(separator, limit) } var startCase = createCompounder(function(result, word, index) { return result + (index ? " " : "") + upperFirst(word) }); function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target } function template(string, options, guard) { var settings = lodash.templateSettings; if (guard && isIterateeCall(string, options, guard)) { options = undefined } string = toString(string); options = assignInWith({}, options, settings, customDefaultsAssignIn); var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; var reDelimiters = RegExp((options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$", "g"); var sourceURL = "//# sourceURL=" + ("sourceURL" in options ? options.sourceURL : "lodash.templateSources[" + ++templateCounter + "]") + "\n"; string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'" } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '" } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'" } index = offset + match.length; return match }); source += "';\n"; var variable = options.variable; if (!variable) { source = "with (obj) {\n" + source + "\n}\n" } source = (isEvaluating ? source.replace(reEmptyStringLeading, "") : source).replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;"); source = "function(" + (variable || "obj") + ") {\n" + (variable ? "" : "obj || (obj = {});\n") + "var __t, __p = ''" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? ", __j = Array.prototype.join;\n" + "function print() { __p += __j.call(arguments, '') }\n" : ";\n") + source + "return __p\n}"; var result = attempt(function() { return Function(importsKeys, sourceURL + "return " + source).apply(undefined, importsValues) }); result.source = source; if (isError(result)) { throw result } return result } function toLower(value) { return toString(value).toLowerCase() } function toUpper(value) { return toString(value).toUpperCase() } function trim(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim, "") } if (!string || !(chars = baseToString(chars))) { return string } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join("") } function trimEnd(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimEnd, "") } if (!string || !(chars = baseToString(chars))) { return string } var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; return castSlice(strSymbols, 0, end).join("") } function trimStart(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimStart, "") } if (!string || !(chars = baseToString(chars))) { return string } var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars)); return castSlice(strSymbols, start).join("") } function truncate(string, options) { var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; if (isObject(options)) { var separator = "separator" in options ? options.separator : separator; length = "length" in options ? toInteger(options.length) : length; omission = "omission" in options ? baseToString(options.omission) : omission } string = toString(string); var strLength = string.length; if (hasUnicode(string)) { var strSymbols = stringToArray(string); strLength = strSymbols.length } if (length >= strLength) { return string } var end = length - stringSize(omission); if (end < 1) { return omission } var result = strSymbols ? castSlice(strSymbols, 0, end).join("") : string.slice(0, end); if (separator === undefined) { return result + omission } if (strSymbols) { end += result.length - end } if (isRegExp(separator)) { if (string.slice(end).search(separator)) { var match, substring = result; if (!separator.global) { separator = RegExp(separator.source, toString(reFlags.exec(separator)) + "g") } separator.lastIndex = 0; while (match = separator.exec(substring)) { var newEnd = match.index } result = result.slice(0, newEnd === undefined ? end : newEnd) } } else if (string.indexOf(baseToString(separator), end) != end) { var index = result.lastIndexOf(separator); if (index > -1) { result = result.slice(0, index) } } return result + omission } function unescape(string) { string = toString(string); return string && reHasEscapedHtml.test(string) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string } var upperCase = createCompounder(function(result, word, index) { return result + (index ? " " : "") + word.toUpperCase() }); var upperFirst = createCaseFirst("toUpperCase"); function words(string, pattern, guard) { string = toString(string); pattern = guard ? undefined : pattern; if (pattern === undefined) { return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string) } return string.match(pattern) || [] } var attempt = baseRest(function(func, args) { try { return apply(func, undefined, args) } catch (e) { return isError(e) ? e : new Error(e) } }); var bindAll = flatRest(function(object, methodNames) { arrayEach(methodNames, function(key) { key = toKey(key); baseAssignValue(object, key, bind(object[key], object)) }); return object }); function cond(pairs) { var length = pairs == null ? 0 : pairs.length, toIteratee = getIteratee(); pairs = !length ? [] : arrayMap(pairs, function(pair) { if (typeof pair[1] != "function") { throw new TypeError(FUNC_ERROR_TEXT) } return [toIteratee(pair[0]), pair[1]] }); return baseRest(function(args) { var index = -1; while (++index < length) { var pair = pairs[index]; if (apply(pair[0], this, args)) { return apply(pair[1], this, args) } } }) } function conforms(source) { return baseConforms(baseClone(source, CLONE_DEEP_FLAG)) } function constant(value) { return function() { return value } } function defaultTo(value, defaultValue) { return value == null || value !== value ? defaultValue : value } var flow = createFlow(); var flowRight = createFlow(true); function identity(value) { return value } function iteratee(func) { return baseIteratee(typeof func == "function" ? func : baseClone(func, CLONE_DEEP_FLAG)) } function matches(source) { return baseMatches(baseClone(source, CLONE_DEEP_FLAG)) } function matchesProperty(path, srcValue) { return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG)) } var method = baseRest(function(path, args) { return function(object) { return baseInvoke(object, path, args) } }); var methodOf = baseRest(function(object, args) { return function(path) { return baseInvoke(object, path, args) } }); function mixin(object, source, options) { var props = keys(source), methodNames = baseFunctions(source, props); if (options == null && !(isObject(source) && (methodNames.length || !props.length))) { options = source; source = object; object = this; methodNames = baseFunctions(source, keys(source)) } var chain = !(isObject(options) && "chain" in options) || !!options.chain, isFunc = isFunction(object); arrayEach(methodNames, function(methodName) { var func = source[methodName]; object[methodName] = func; if (isFunc) { object.prototype[methodName] = function() { var chainAll = this.__chain__; if (chain || chainAll) { var result = object(this.__wrapped__), actions = result.__actions__ = copyArray(this.__actions__); actions.push({ func: func, args: arguments, thisArg: object }); result.__chain__ = chainAll; return result } return func.apply(object, arrayPush([this.value()], arguments)) } } }); return object } function noConflict() { if (root._ === this) { root._ = oldDash } return this } function noop() {} function nthArg(n) { n = toInteger(n); return baseRest(function(args) { return baseNth(args, n) }) } var over = createOver(arrayMap); var overEvery = createOver(arrayEvery); var overSome = createOver(arraySome); function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path) } function propertyOf(object) { return function(path) { return object == null ? undefined : baseGet(object, path) } } var range = createRange(); var rangeRight = createRange(true); function stubArray() { return [] } function stubFalse() { return false } function stubObject() { return {} } function stubString() { return "" } function stubTrue() { return true } function times(n, iteratee) { n = toInteger(n); if (n < 1 || n > MAX_SAFE_INTEGER) { return [] } var index = MAX_ARRAY_LENGTH, length = nativeMin(n, MAX_ARRAY_LENGTH); iteratee = getIteratee(iteratee); n -= MAX_ARRAY_LENGTH; var result = baseTimes(length, iteratee); while (++index < n) { iteratee(index) } return result } function toPath(value) { if (isArray(value)) { return arrayMap(value, toKey) } return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))) } function uniqueId(prefix) { var id = ++idCounter; return toString(prefix) + id } var add = createMathOperation(function(augend, addend) { return augend + addend }, 0); var ceil = createRound("ceil"); var divide = createMathOperation(function(dividend, divisor) { return dividend / divisor }, 1); var floor = createRound("floor"); function max(array) { return array && array.length ? baseExtremum(array, identity, baseGt) : undefined } function maxBy(array, iteratee) { return array && array.length ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) : undefined } function mean(array) { return baseMean(array, identity) } function meanBy(array, iteratee) { return baseMean(array, getIteratee(iteratee, 2)) } function min(array) { return array && array.length ? baseExtremum(array, identity, baseLt) : undefined } function minBy(array, iteratee) { return array && array.length ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) : undefined } var multiply = createMathOperation(function(multiplier, multiplicand) { return multiplier * multiplicand }, 1); var round = createRound("round"); var subtract = createMathOperation(function(minuend, subtrahend) { return minuend - subtrahend }, 0); function sum(array) { return array && array.length ? baseSum(array, identity) : 0 } function sumBy(array, iteratee) { return array && array.length ? baseSum(array, getIteratee(iteratee, 2)) : 0 } lodash.after = after; lodash.ary = ary; lodash.assign = assign; lodash.assignIn = assignIn; lodash.assignInWith = assignInWith; lodash.assignWith = assignWith; lodash.at = at; lodash.before = before; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.castArray = castArray; lodash.chain = chain; lodash.chunk = chunk; lodash.compact = compact; lodash.concat = concat; lodash.cond = cond; lodash.conforms = conforms; lodash.constant = constant; lodash.countBy = countBy; lodash.create = create; lodash.curry = curry; lodash.curryRight = curryRight; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defaultsDeep = defaultsDeep; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.differenceBy = differenceBy; lodash.differenceWith = differenceWith; lodash.drop = drop; lodash.dropRight = dropRight; lodash.dropRightWhile = dropRightWhile; lodash.dropWhile = dropWhile; lodash.fill = fill; lodash.filter = filter; lodash.flatMap = flatMap; lodash.flatMapDeep = flatMapDeep; lodash.flatMapDepth = flatMapDepth; lodash.flatten = flatten; lodash.flattenDeep = flattenDeep; lodash.flattenDepth = flattenDepth; lodash.flip = flip; lodash.flow = flow; lodash.flowRight = flowRight; lodash.fromPairs = fromPairs; lodash.functions = functions; lodash.functionsIn = functionsIn; lodash.groupBy = groupBy; lodash.initial = initial; lodash.intersection = intersection; lodash.intersectionBy = intersectionBy; lodash.intersectionWith = intersectionWith; lodash.invert = invert; lodash.invertBy = invertBy; lodash.invokeMap = invokeMap; lodash.iteratee = iteratee; lodash.keyBy = keyBy; lodash.keys = keys; lodash.keysIn = keysIn; lodash.map = map; lodash.mapKeys = mapKeys; lodash.mapValues = mapValues; lodash.matches = matches; lodash.matchesProperty = matchesProperty; lodash.memoize = memoize; lodash.merge = merge; lodash.mergeWith = mergeWith; lodash.method = method; lodash.methodOf = methodOf; lodash.mixin = mixin; lodash.negate = negate; lodash.nthArg = nthArg; lodash.omit = omit; lodash.omitBy = omitBy; lodash.once = once; lodash.orderBy = orderBy; lodash.over = over; lodash.overArgs = overArgs; lodash.overEvery = overEvery; lodash.overSome = overSome; lodash.partial = partial; lodash.partialRight = partialRight; lodash.partition = partition; lodash.pick = pick; lodash.pickBy = pickBy; lodash.property = property; lodash.propertyOf = propertyOf; lodash.pull = pull; lodash.pullAll = pullAll; lodash.pullAllBy = pullAllBy; lodash.pullAllWith = pullAllWith; lodash.pullAt = pullAt; lodash.range = range; lodash.rangeRight = rangeRight; lodash.rearg = rearg; lodash.reject = reject; lodash.remove = remove; lodash.rest = rest; lodash.reverse = reverse; lodash.sampleSize = sampleSize; lodash.set = set; lodash.setWith = setWith; lodash.shuffle = shuffle; lodash.slice = slice; lodash.sortBy = sortBy; lodash.sortedUniq = sortedUniq; lodash.sortedUniqBy = sortedUniqBy; lodash.split = split; lodash.spread = spread; lodash.tail = tail; lodash.take = take; lodash.takeRight = takeRight; lodash.takeRightWhile = takeRightWhile; lodash.takeWhile = takeWhile; lodash.tap = tap; lodash.throttle = throttle; lodash.thru = thru; lodash.toArray = toArray; lodash.toPairs = toPairs; lodash.toPairsIn = toPairsIn; lodash.toPath = toPath; lodash.toPlainObject = toPlainObject; lodash.transform = transform; lodash.unary = unary; lodash.union = union; lodash.unionBy = unionBy; lodash.unionWith = unionWith; lodash.uniq = uniq; lodash.uniqBy = uniqBy; lodash.uniqWith = uniqWith; lodash.unset = unset; lodash.unzip = unzip; lodash.unzipWith = unzipWith; lodash.update = update; lodash.updateWith = updateWith; lodash.values = values; lodash.valuesIn = valuesIn; lodash.without = without; lodash.words = words; lodash.wrap = wrap; lodash.xor = xor; lodash.xorBy = xorBy; lodash.xorWith = xorWith; lodash.zip = zip; lodash.zipObject = zipObject; lodash.zipObjectDeep = zipObjectDeep; lodash.zipWith = zipWith; lodash.entries = toPairs; lodash.entriesIn = toPairsIn; lodash.extend = assignIn; lodash.extendWith = assignInWith; mixin(lodash, lodash); lodash.add = add; lodash.attempt = attempt; lodash.camelCase = camelCase; lodash.capitalize = capitalize; lodash.ceil = ceil; lodash.clamp = clamp; lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.cloneDeepWith = cloneDeepWith; lodash.cloneWith = cloneWith; lodash.conformsTo = conformsTo; lodash.deburr = deburr; lodash.defaultTo = defaultTo; lodash.divide = divide; lodash.endsWith = endsWith; lodash.eq = eq; lodash.escape = escape; lodash.escapeRegExp = escapeRegExp; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.findLast = findLast; lodash.findLastIndex = findLastIndex; lodash.findLastKey = findLastKey; lodash.floor = floor; lodash.forEach = forEach; lodash.forEachRight = forEachRight; lodash.forIn = forIn; lodash.forInRight = forInRight; lodash.forOwn = forOwn; lodash.forOwnRight = forOwnRight; lodash.get = get; lodash.gt = gt; lodash.gte = gte; lodash.has = has; lodash.hasIn = hasIn; lodash.head = head; lodash.identity = identity; lodash.includes = includes; lodash.indexOf = indexOf; lodash.inRange = inRange; lodash.invoke = invoke; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isArrayBuffer = isArrayBuffer; lodash.isArrayLike = isArrayLike; lodash.isArrayLikeObject = isArrayLikeObject; lodash.isBoolean = isBoolean; lodash.isBuffer = isBuffer; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isEqualWith = isEqualWith; lodash.isError = isError; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isInteger = isInteger; lodash.isLength = isLength; lodash.isMap = isMap; lodash.isMatch = isMatch; lodash.isMatchWith = isMatchWith; lodash.isNaN = isNaN; lodash.isNative = isNative; lodash.isNil = isNil; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isObjectLike = isObjectLike; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isSafeInteger = isSafeInteger; lodash.isSet = isSet; lodash.isString = isString; lodash.isSymbol = isSymbol; lodash.isTypedArray = isTypedArray; lodash.isUndefined = isUndefined; lodash.isWeakMap = isWeakMap; lodash.isWeakSet = isWeakSet; lodash.join = join; lodash.kebabCase = kebabCase; lodash.last = last; lodash.lastIndexOf = lastIndexOf; lodash.lowerCase = lowerCase; lodash.lowerFirst = lowerFirst; lodash.lt = lt; lodash.lte = lte; lodash.max = max; lodash.maxBy = maxBy; lodash.mean = mean; lodash.meanBy = meanBy; lodash.min = min; lodash.minBy = minBy; lodash.stubArray = stubArray; lodash.stubFalse = stubFalse; lodash.stubObject = stubObject; lodash.stubString = stubString; lodash.stubTrue = stubTrue; lodash.multiply = multiply; lodash.nth = nth; lodash.noConflict = noConflict; lodash.noop = noop; lodash.now = now; lodash.pad = pad; lodash.padEnd = padEnd; lodash.padStart = padStart; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.repeat = repeat; lodash.replace = replace; lodash.result = result; lodash.round = round; lodash.runInContext = runInContext; lodash.sample = sample; lodash.size = size; lodash.snakeCase = snakeCase; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.sortedIndexBy = sortedIndexBy; lodash.sortedIndexOf = sortedIndexOf; lodash.sortedLastIndex = sortedLastIndex; lodash.sortedLastIndexBy = sortedLastIndexBy; lodash.sortedLastIndexOf = sortedLastIndexOf; lodash.startCase = startCase; lodash.startsWith = startsWith; lodash.subtract = subtract; lodash.sum = sum; lodash.sumBy = sumBy; lodash.template = template; lodash.times = times; lodash.toFinite = toFinite; lodash.toInteger = toInteger; lodash.toLength = toLength; lodash.toLower = toLower; lodash.toNumber = toNumber; lodash.toSafeInteger = toSafeInteger; lodash.toString = toString; lodash.toUpper = toUpper; lodash.trim = trim; lodash.trimEnd = trimEnd; lodash.trimStart = trimStart; lodash.truncate = truncate; lodash.unescape = unescape; lodash.uniqueId = uniqueId; lodash.upperCase = upperCase; lodash.upperFirst = upperFirst; lodash.each = forEach; lodash.eachRight = forEachRight; lodash.first = head; mixin(lodash, function() { var source = {}; baseForOwn(lodash, function(func, methodName) { if (!hasOwnProperty.call(lodash.prototype, methodName)) { source[methodName] = func } }); return source }(), { chain: false }); lodash.VERSION = VERSION; arrayEach(["bind", "bindKey", "curry", "curryRight", "partial", "partialRight"], function(methodName) { lodash[methodName].placeholder = lodash }); arrayEach(["drop", "take"], function(methodName, index) { LazyWrapper.prototype[methodName] = function(n) { n = n === undefined ? 1 : nativeMax(toInteger(n), 0); var result = this.__filtered__ && !index ? new LazyWrapper(this) : this.clone(); if (result.__filtered__) { result.__takeCount__ = nativeMin(n, result.__takeCount__) } else { result.__views__.push({ size: nativeMin(n, MAX_ARRAY_LENGTH), type: methodName + (result.__dir__ < 0 ? "Right" : "") }) } return result }; LazyWrapper.prototype[methodName + "Right"] = function(n) { return this.reverse()[methodName](n).reverse() } }); arrayEach(["filter", "map", "takeWhile"], function(methodName, index) { var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; LazyWrapper.prototype[methodName] = function(iteratee) { var result = this.clone(); result.__iteratees__.push({ iteratee: getIteratee(iteratee, 3), type: type }); result.__filtered__ = result.__filtered__ || isFilter; return result } }); arrayEach(["head", "last"], function(methodName, index) { var takeName = "take" + (index ? "Right" : ""); LazyWrapper.prototype[methodName] = function() { return this[takeName](1).value()[0] } }); arrayEach(["initial", "tail"], function(methodName, index) { var dropName = "drop" + (index ? "" : "Right"); LazyWrapper.prototype[methodName] = function() { return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1) } }); LazyWrapper.prototype.compact = function() { return this.filter(identity) }; LazyWrapper.prototype.find = function(predicate) { return this.filter(predicate).head() }; LazyWrapper.prototype.findLast = function(predicate) { return this.reverse().find(predicate) }; LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { if (typeof path == "function") { return new LazyWrapper(this) } return this.map(function(value) { return baseInvoke(value, path, args) }) }); LazyWrapper.prototype.reject = function(predicate) { return this.filter(negate(getIteratee(predicate))) }; LazyWrapper.prototype.slice = function(start, end) { start = toInteger(start); var result = this; if (result.__filtered__ && (start > 0 || end < 0)) { return new LazyWrapper(result) } if (start < 0) { result = result.takeRight(-start) } else if (start) { result = result.drop(start) } if (end !== undefined) { end = toInteger(end); result = end < 0 ? result.dropRight(-end) : result.take(end - start) } return result }; LazyWrapper.prototype.takeRightWhile = function(predicate) { return this.reverse().takeWhile(predicate).reverse() }; LazyWrapper.prototype.toArray = function() { return this.take(MAX_ARRAY_LENGTH) }; baseForOwn(LazyWrapper.prototype, function(func, methodName) { var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? "take" + (methodName == "last" ? "Right" : "") : methodName], retUnwrapped = isTaker || /^find/.test(methodName); if (!lodashFunc) { return; } lodash.prototype[methodName] = function() { var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value); var interceptor = function(value) { var result = lodashFunc.apply(lodash, arrayPush([value], args)); return isTaker && chainAll ? result[0] : result }; if (useLazy && checkIteratee && typeof iteratee == "function" && iteratee.length != 1) { isLazy = useLazy = false } var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; if (!retUnwrapped && useLazy) { value = onlyLazy ? value : new LazyWrapper(this); var result = func.apply(value, args); result.__actions__.push({ func: thru, args: [interceptor], thisArg: undefined }); return new LodashWrapper(result, chainAll) } if (isUnwrapped && onlyLazy) { return func.apply(this, args) } result = this.thru(interceptor); return isUnwrapped ? isTaker ? result.value()[0] : result.value() : result } }); arrayEach(["pop", "push", "shift", "sort", "splice", "unshift"], function(methodName) { var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? "tap" : "thru", retUnwrapped = /^(?:pop|shift)$/.test(methodName); lodash.prototype[methodName] = function() { var args = arguments; if (retUnwrapped && !this.__chain__) { var value = this.value(); return func.apply(isArray(value) ? value : [], args) } return this[chainName](function(value) { return func.apply(isArray(value) ? value : [], args) }) } }); baseForOwn(LazyWrapper.prototype, function(func, methodName) { var lodashFunc = lodash[methodName]; if (lodashFunc) { var key = lodashFunc.name + "", names = realNames[key] || (realNames[key] = []); names.push({ name: methodName, func: lodashFunc }) } }); realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{ name: "wrapper", func: undefined }]; LazyWrapper.prototype.clone = lazyClone; LazyWrapper.prototype.reverse = lazyReverse; LazyWrapper.prototype.value = lazyValue; lodash.prototype.at = wrapperAt; lodash.prototype.chain = wrapperChain; lodash.prototype.commit = wrapperCommit; lodash.prototype.next = wrapperNext; lodash.prototype.plant = wrapperPlant; lodash.prototype.reverse = wrapperReverse; lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; lodash.prototype.first = lodash.prototype.head; if (symIterator) { lodash.prototype[symIterator] = wrapperToIterator } return lodash }; var _ = runInContext(); if (typeof define == "function" && typeof define.amd == "object" && define.amd) { root._ = _; define(function() { return _ }) } else if (freeModule) { (freeModule.exports = _)._ = _; freeExports._ = _ } else { root._ = _ } }).call(this) }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) }, {}], 8: [function(require, module, exports) { var root; if (typeof window !== "undefined") { root = window } else if (typeof self !== "undefined") { root = self } else { console.warn("Using browser-only version of superagent in non-browser environment"); root = this } var Emitter = require("component-emitter"); var RequestBase = require("./request-base"); var isObject = require("./is-object"); var isFunction = require("./is-function"); var ResponseBase = require("./response-base"); var shouldRetry = require("./should-retry"); function noop() {} var request = exports = module.exports = function(method, url) { if ("function" == typeof url) { return new exports.Request("GET", method).end(url) } if (1 == arguments.length) { return new exports.Request("GET", method) } return new exports.Request(method, url) }; exports.Request = Request; request.getXHR = function() { if (root.XMLHttpRequest && (!root.location || "file:" != root.location.protocol || !root.ActiveXObject)) { return new XMLHttpRequest } else { try { return new ActiveXObject("Microsoft.XMLHTTP") } catch (e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch (e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch (e) {} try { return new ActiveXObject("Msxml2.XMLHTTP") } catch (e) {} } throw Error("Browser-only verison of superagent could not find XHR") }; var trim = "".trim ? function(s) { return s.trim() } : function(s) { return s.replace(/(^\s*|\s*$)/g, "") }; function serialize(obj) { if (!isObject(obj)) return obj; var pairs = []; for (var key in obj) { pushEncodedKeyValuePair(pairs, key, obj[key]) } return pairs.join("&") } function pushEncodedKeyValuePair(pairs, key, val) { if (val != null) { if (Array.isArray(val)) { val.forEach(function(v) { pushEncodedKeyValuePair(pairs, key, v) }) } else if (isObject(val)) { for (var subkey in val) { pushEncodedKeyValuePair(pairs, key + "[" + subkey + "]", val[subkey]) } } else { pairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(val)) } } else if (val === null) { pairs.push(encodeURIComponent(key)) } } request.serializeObject = serialize; function parseString(str) { var obj = {}; var pairs = str.split("&"); var pair; var pos; for (var i = 0, len = pairs.length; i < len; ++i) { pair = pairs[i]; pos = pair.indexOf("="); if (pos == -1) { obj[decodeURIComponent(pair)] = "" } else { obj[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1)) } } return obj } request.parseString = parseString; request.types = { html: "text/html", json: "application/json", xml: "application/xml", urlencoded: "application/x-www-form-urlencoded", form: "application/x-www-form-urlencoded", "form-data": "application/x-www-form-urlencoded" }; request.serialize = { "application/x-www-form-urlencoded": serialize, "application/json": JSON.stringify }; request.parse = { "application/x-www-form-urlencoded": parseString, "application/json": JSON.parse }; function parseHeader(str) { var lines = str.split(/\r?\n/); var fields = {}; var index; var line; var field; var val; lines.pop(); for (var i = 0, len = lines.length; i < len; ++i) { line = lines[i]; index = line.indexOf(":"); field = line.slice(0, index).toLowerCase(); val = trim(line.slice(index + 1)); fields[field] = val } return fields } function isJSON(mime) { return /[\/+]json\b/.test(mime) } function Response(req) { this.req = req; this.xhr = this.req.xhr; this.text = this.req.method != "HEAD" && (this.xhr.responseType === "" || this.xhr.responseType === "text") || typeof this.xhr.responseType === "undefined" ? this.xhr.responseText : null; this.statusText = this.req.xhr.statusText; var status = this.xhr.status; if (status === 1223) { status = 204 } this._setStatusProperties(status); this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); this.header["content-type"] = this.xhr.getResponseHeader("content-type"); this._setHeaderProperties(this.header); if (null === this.text && req._responseType) { this.body = this.xhr.response } else { this.body = this.req.method != "HEAD" ? this._parseBody(this.text ? this.text : this.xhr.response) : null } } ResponseBase(Response.prototype); Response.prototype._parseBody = function(str) { var parse = request.parse[this.type]; if (this.req._parser) { return this.req._parser(this, str) } if (!parse && isJSON(this.type)) { parse = request.parse["application/json"] } return parse && str && (str.length || str instanceof Object) ? parse(str) : null }; Response.prototype.toError = function() { var req = this.req; var method = req.method; var url = req.url; var msg = "cannot " + method + " " + url + " (" + this.status + ")"; var err = new Error(msg); err.status = this.status; err.method = method; err.url = url; return err }; request.Response = Response; function Request(method, url) { var self = this; this._query = this._query || []; this.method = method; this.url = url; this.header = {}; this._header = {}; this.on("end", function() { var err = null; var res = null; try { res = new Response(self) } catch (e) { err = new Error("Parser is unable to parse the response"); err.parse = true; err.original = e; if (self.xhr) { err.rawResponse = typeof self.xhr.responseType == "undefined" ? self.xhr.responseText : self.xhr.response; err.status = self.xhr.status ? self.xhr.status : null; err.statusCode = err.status } else { err.rawResponse = null; err.status = null } return self.callback(err) } self.emit("response", res); var new_err; try { if (!self._isResponseOK(res)) { new_err = new Error(res.statusText || "Unsuccessful HTTP response"); new_err.original = err; new_err.response = res; new_err.status = res.status } } catch (e) { new_err = e } if (new_err) { self.callback(new_err, res) } else { self.callback(null, res) } }) } Emitter(Request.prototype); RequestBase(Request.prototype); Request.prototype.type = function(type) { this.set("Content-Type", request.types[type] || type); return this }; Request.prototype.accept = function(type) { this.set("Accept", request.types[type] || type); return this }; Request.prototype.auth = function(user, pass, options) { if (typeof pass === "object" && pass !== null) { options = pass } if (!options) { options = { type: "function" === typeof btoa ? "basic" : "auto" } } switch (options.type) { case "basic": this.set("Authorization", "Basic " + btoa(user + ":" + pass)); break; case "auto": this.username = user; this.password = pass; break; case "bearer": this.set("Authorization", "Bearer " + user); break } return this }; Request.prototype.query = function(val) { if ("string" != typeof val) val = serialize(val); if (val) this._query.push(val); return this }; Request.prototype.attach = function(field, file, options) { if (file) { if (this._data) { throw Error("superagent can't mix .send() and .attach()") } this._getFormData().append(field, file, options || file.name) } return this }; Request.prototype._getFormData = function() { if (!this._formData) { this._formData = new root.FormData } return this._formData }; Request.prototype.callback = function(err, res) { if (this._maxRetries && this._retries++ < this._maxRetries && shouldRetry(err, res)) { return this._retry() } var fn = this._callback; this.clearTimeout(); if (err) { if (this._maxRetries) err.retries = this._retries - 1; this.emit("error", err) } fn(err, res) }; Request.prototype.crossDomainError = function() { var err = new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc."); err.crossDomain = true; err.status = this.status; err.method = this.method; err.url = this.url; this.callback(err) }; Request.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function() { console.warn("This is not supported in browser version of superagent"); return this }; Request.prototype.pipe = Request.prototype.write = function() { throw Error("Streaming is not supported in browser version of superagent") }; Request.prototype._appendQueryString = function() { var query = this._query.join("&"); if (query) { this.url += (this.url.indexOf("?") >= 0 ? "&" : "?") + query } if (this._sort) { var index = this.url.indexOf("?"); if (index >= 0) { var queryArr = this.url.substring(index + 1).split("&"); if (isFunction(this._sort)) { queryArr.sort(this._sort) } else { queryArr.sort() } this.url = this.url.substring(0, index) + "?" + queryArr.join("&") } } }; Request.prototype._isHost = function _isHost(obj) { return obj && "object" === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== "[object Object]" }; Request.prototype.end = function(fn) { if (this._endCalled) { console.warn("Warning: .end() was called twice. This is not supported in superagent") } this._endCalled = true; this._callback = fn || noop; this._appendQueryString(); return this._end() }; Request.prototype._end = function() { var self = this; var xhr = this.xhr = request.getXHR(); var data = this._formData || this._data; this._setTimeouts(); xhr.onreadystatechange = function() { var readyState = xhr.readyState; if (readyState >= 2 && self._responseTimeoutTimer) { clearTimeout(self._responseTimeoutTimer) } if (4 != readyState) { return } var status; try { status = xhr.status } catch (e) { status = 0 } if (!status) { if (self.timedout || self._aborted) return; return self.crossDomainError() } self.emit("end") }; var handleProgress = function(direction, e) { if (e.total > 0) { e.percent = e.loaded / e.total * 100 } e.direction = direction; self.emit("progress", e) }; if (this.hasListeners("progress")) { try { xhr.onprogress = handleProgress.bind(null, "download"); if (xhr.upload) { xhr.upload.onprogress = handleProgress.bind(null, "upload") } } catch (e) {} } try { if (this.username && this.password) { xhr.open(this.method, this.url, true, this.username, this.password) } else { xhr.open(this.method, this.url, true) } } catch (err) { return this.callback(err) } if (this._withCredentials) xhr.withCredentials = true; if (!this._formData && "GET" != this.method && "HEAD" != this.method && "string" != typeof data && !this._isHost(data)) { var contentType = this._header["content-type"]; var serialize = this._serializer || request.serialize[contentType ? contentType.split(";")[0] : ""]; if (!serialize && isJSON(contentType)) { serialize = request.serialize["application/json"] } if (serialize) data = serialize(data) } for (var field in this.header) { if (null == this.header[field]) continue; if (this.header.hasOwnProperty(field)) xhr.setRequestHeader(field, this.header[field]) } if (this._responseType) { xhr.responseType = this._responseType } this.emit("request", this); xhr.send(typeof data !== "undefined" ? data : null); return this }; request.get = function(url, data, fn) { var req = request("GET", url); if ("function" == typeof data) fn = data, data = null; if (data) req.query(data); if (fn) req.end(fn); return req }; request.head = function(url, data, fn) { var req = request("HEAD", url); if ("function" == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req }; request.options = function(url, data, fn) { var req = request("OPTIONS", url); if ("function" == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req }; function del(url, data, fn) { var req = request("DELETE", url); if ("function" == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req } request["del"] = del; request["delete"] = del; request.patch = function(url, data, fn) { var req = request("PATCH", url); if ("function" == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req }; request.post = function(url, data, fn) { var req = request("POST", url); if ("function" == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req }; request.put = function(url, data, fn) { var req = request("PUT", url); if ("function" == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req } }, { "./is-function": 9, "./is-object": 10, "./request-base": 11, "./response-base": 12, "./should-retry": 13, "component-emitter": 3 }], 9: [function(require, module, exports) { var isObject = require("./is-object"); function isFunction(fn) { var tag = isObject(fn) ? Object.prototype.toString.call(fn) : ""; return tag === "[object Function]" } module.exports = isFunction }, { "./is-object": 10 }], 10: [function(require, module, exports) { function isObject(obj) { return null !== obj && "object" === typeof obj } module.exports = isObject }, {}], 11: [function(require, module, exports) { var isObject = require("./is-object"); module.exports = RequestBase; function RequestBase(obj) { if (obj) return mixin(obj) } function mixin(obj) { for (var key in RequestBase.prototype) { obj[key] = RequestBase.prototype[key] } return obj } RequestBase.prototype.clearTimeout = function _clearTimeout() { clearTimeout(this._timer); clearTimeout(this._responseTimeoutTimer); delete this._timer; delete this._responseTimeoutTimer; return this }; RequestBase.prototype.parse = function parse(fn) { this._parser = fn; return this }; RequestBase.prototype.responseType = function(val) { this._responseType = val; return this }; RequestBase.prototype.serialize = function serialize(fn) { this._serializer = fn; return this }; RequestBase.prototype.timeout = function timeout(options) { if (!options || "object" !== typeof options) { this._timeout = options; this._responseTimeout = 0; return this } for (var option in options) { switch (option) { case "deadline": this._timeout = options.deadline; break; case "response": this._responseTimeout = options.response; break; default: console.warn("Unknown timeout option", option) } } return this }; RequestBase.prototype.retry = function retry(count) { if (arguments.length === 0 || count === true) count = 1; if (count <= 0) count = 0; this._maxRetries = count; this._retries = 0; return this }; RequestBase.prototype._retry = function() { this.clearTimeout(); if (this.req) { this.req = null; this.req = this.request() } this._aborted = false; this.timedout = false; return this._end() }; RequestBase.prototype.then = function then(resolve, reject) { if (!this._fullfilledPromise) { var self = this; if (this._endCalled) { console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises") } this._fullfilledPromise = new Promise(function(innerResolve, innerReject) { self.end(function(err, res) { if (err) innerReject(err); else innerResolve(res) }) }) } return this._fullfilledPromise.then(resolve, reject) }; RequestBase.prototype.catch = function(cb) { return this.then(undefined, cb) }; RequestBase.prototype.use = function use(fn) { fn(this); return this }; RequestBase.prototype.ok = function(cb) { if ("function" !== typeof cb) throw Error("Callback required"); this._okCallback = cb; return this }; RequestBase.prototype._isResponseOK = function(res) { if (!res) { return false } if (this._okCallback) { return this._okCallback(res) } return res.status >= 200 && res.status < 300 }; RequestBase.prototype.get = function(field) { return this._header[field.toLowerCase()] }; RequestBase.prototype.getHeader = RequestBase.prototype.get; RequestBase.prototype.set = function(field, val) { if (isObject(field)) { for (var key in field) { this.set(key, field[key]) } return this } this._header[field.toLowerCase()] = val; this.header[field] = val; return this }; RequestBase.prototype.unset = function(field) { delete this._header[field.toLowerCase()]; delete this.header[field]; return this }; RequestBase.prototype.field = function(name, val) { if (null === name || undefined === name) { throw new Error(".field(name, val) name can not be empty") } if (this._data) { console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()") } if (isObject(name)) { for (var key in name) { this.field(key, name[key]) } return this } if (Array.isArray(val)) { for (var i in val) { this.field(name, val[i]) } return this } if (null === val || undefined === val) { throw new Error(".field(name, val) val can not be empty") } if ("boolean" === typeof val) { val = "" + val } this._getFormData().append(name, val); return this }; RequestBase.prototype.abort = function() { if (this._aborted) { return this } this._aborted = true; this.xhr && this.xhr.abort(); this.req && this.req.abort(); this.clearTimeout(); this.emit("abort"); return this }; RequestBase.prototype.withCredentials = function(on) { if (on == undefined) on = true; this._withCredentials = on; return this }; RequestBase.prototype.redirects = function(n) { this._maxRedirects = n; return this }; RequestBase.prototype.toJSON = function() { return { method: this.method, url: this.url, data: this._data, headers: this._header } }; RequestBase.prototype.send = function(data) { var isObj = isObject(data); var type = this._header["content-type"]; if (this._formData) { console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()") } if (isObj && !this._data) { if (Array.isArray(data)) { this._data = [] } else if (!this._isHost(data)) { this._data = {} } } else if (data && this._data && this._isHost(this._data)) { throw Error("Can't merge these send calls") } if (isObj && isObject(this._data)) { for (var key in data) { this._data[key] = data[key] } } else if ("string" == typeof data) { if (!type) this.type("form"); type = this._header["content-type"]; if ("application/x-www-form-urlencoded" == type) { this._data = this._data ? this._data + "&" + data : data } else { this._data = (this._data || "") + data } } else { this._data = data } if (!isObj || this._isHost(data)) { return this } if (!type) this.type("json"); return this }; RequestBase.prototype.sortQuery = function(sort) { this._sort = typeof sort === "undefined" ? true : sort; return this }; RequestBase.prototype._timeoutError = function(reason, timeout, errno) { if (this._aborted) { return } var err = new Error(reason + timeout + "ms exceeded"); err.timeout = timeout; err.code = "ECONNABORTED"; err.errno = errno; this.timedout = true; this.abort(); this.callback(err) }; RequestBase.prototype._setTimeouts = function() { var self = this; if (this._timeout && !this._timer) { this._timer = setTimeout(function() { self._timeoutError("Timeout of ", self._timeout, "ETIME") }, this._timeout) } if (this._responseTimeout && !this._responseTimeoutTimer) { this._responseTimeoutTimer = setTimeout(function() { self._timeoutError("Response timeout of ", self._responseTimeout, "ETIMEDOUT") }, this._responseTimeout) } } }, { "./is-object": 10 }], 12: [function(require, module, exports) { var utils = require("./utils"); module.exports = ResponseBase; function ResponseBase(obj) { if (obj) return mixin(obj) } function mixin(obj) { for (var key in ResponseBase.prototype) { obj[key] = ResponseBase.prototype[key] } return obj } ResponseBase.prototype.get = function(field) { return this.header[field.toLowerCase()] }; ResponseBase.prototype._setHeaderProperties = function(header) { var ct = header["content-type"] || ""; this.type = utils.type(ct); var params = utils.params(ct); for (var key in params) this[key] = params[key]; this.links = {}; try { if (header.link) { this.links = utils.parseLinks(header.link) } } catch (err) {} }; ResponseBase.prototype._setStatusProperties = function(status) { var type = status / 100 | 0; this.status = this.statusCode = status; this.statusType = type; this.info = 1 == type; this.ok = 2 == type; this.redirect = 3 == type; this.clientError = 4 == type; this.serverError = 5 == type; this.error = 4 == type || 5 == type ? this.toError() : false; this.accepted = 202 == status; this.noContent = 204 == status; this.badRequest = 400 == status; this.unauthorized = 401 == status; this.notAcceptable = 406 == status; this.forbidden = 403 == status; this.notFound = 404 == status } }, { "./utils": 14 }], 13: [function(require, module, exports) { var ERROR_CODES = ["ECONNRESET", "ETIMEDOUT", "EADDRINFO", "ESOCKETTIMEDOUT"]; module.exports = function shouldRetry(err, res) { if (err && err.code && ~ERROR_CODES.indexOf(err.code)) return true; if (res && res.status && res.status >= 500) return true; if (err && "timeout" in err && err.code == "ECONNABORTED") return true; if (err && "crossDomain" in err) return true; return false } }, {}], 14: [function(require, module, exports) { exports.type = function(str) { return str.split(/ *; */).shift() }; exports.params = function(str) { return str.split(/ *; */).reduce(function(obj, str) { var parts = str.split(/ *= */); var key = parts.shift(); var val = parts.shift(); if (key && val) obj[key] = val; return obj }, {}) }; exports.parseLinks = function(str) { return str.split(/ *, */).reduce(function(obj, str) { var parts = str.split(/ *; */); var url = parts[0].slice(1, -1); var rel = parts[1].split(/ *= */)[1].slice(1, -1); obj[rel] = url; return obj }, {}) }; exports.cleanHeader = function(header, shouldStripCookie) { delete header["content-type"]; delete header["content-length"]; delete header["transfer-encoding"]; delete header["host"]; if (shouldStripCookie) { delete header["cookie"] } return header } }, {}], 15: [function(require, module, exports) { (function(self) { "use strict"; if (self.fetch) { return } var support = { searchParams: "URLSearchParams" in self, iterable: "Symbol" in self && "iterator" in Symbol, blob: "FileReader" in self && "Blob" in self && function() { try { new Blob; return true } catch (e) { return false } }(), formData: "FormData" in self, arrayBuffer: "ArrayBuffer" in self }; if (support.arrayBuffer) { var viewClasses = ["[object Int8Array]", "[object Uint8Array]", "[object Uint8ClampedArray]", "[object Int16Array]", "[object Uint16Array]", "[object Int32Array]", "[object Uint32Array]", "[object Float32Array]", "[object Float64Array]"]; var isDataView = function(obj) { return obj && DataView.prototype.isPrototypeOf(obj) }; var isArrayBufferView = ArrayBuffer.isView || function(obj) { return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 } } function normalizeName(name) { if (typeof name !== "string") { name = String(name) } if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) { throw new TypeError("Invalid character in header field name") } return name.toLowerCase() } function normalizeValue(value) { if (typeof value !== "string") { value = String(value) } return value } function iteratorFor(items) { var iterator = { next: function() { var value = items.shift(); return { done: value === undefined, value: value } } }; if (support.iterable) { iterator[Symbol.iterator] = function() { return iterator } } return iterator } function Headers(headers) { this.map = {}; if (headers instanceof Headers) { headers.forEach(function(value, name) { this.append(name, value) }, this) } else if (Array.isArray(headers)) { headers.forEach(function(header) { this.append(header[0], header[1]) }, this) } else if (headers) { Object.getOwnPropertyNames(headers).forEach(function(name) { this.append(name, headers[name]) }, this) } } Headers.prototype.append = function(name, value) { name = normalizeName(name); value = normalizeValue(value); var oldValue = this.map[name]; this.map[name] = oldValue ? oldValue + "," + value : value }; Headers.prototype["delete"] = function(name) { delete this.map[normalizeName(name)] }; Headers.prototype.get = function(name) { name = normalizeName(name); return this.has(name) ? this.map[name] : null }; Headers.prototype.has = function(name) { return this.map.hasOwnProperty(normalizeName(name)) }; Headers.prototype.set = function(name, value) { this.map[normalizeName(name)] = normalizeValue(value) }; Headers.prototype.forEach = function(callback, thisArg) { for (var name in this.map) { if (this.map.hasOwnProperty(name)) { callback.call(thisArg, this.map[name], name, this) } } }; Headers.prototype.keys = function() { var items = []; this.forEach(function(value, name) { items.push(name) }); return iteratorFor(items) }; Headers.prototype.values = function() { var items = []; this.forEach(function(value) { items.push(value) }); return iteratorFor(items) }; Headers.prototype.entries = function() { var items = []; this.forEach(function(value, name) { items.push([name, value]) }); return iteratorFor(items) }; if (support.iterable) { Headers.prototype[Symbol.iterator] = Headers.prototype.entries } function consumed(body) { if (body.bodyUsed) { return Promise.reject(new TypeError("Already read")) } body.bodyUsed = true } function fileReaderReady(reader) { return new Promise(function(resolve, reject) { reader.onload = function() { resolve(reader.result) }; reader.onerror = function() { reject(reader.error) } }) } function readBlobAsArrayBuffer(blob) { var reader = new FileReader; var promise = fileReaderReady(reader); reader.readAsArrayBuffer(blob); return promise } function readBlobAsText(blob) { var reader = new FileReader; var promise = fileReaderReady(reader); reader.readAsText(blob); return promise } function readArrayBufferAsText(buf) { var view = new Uint8Array(buf); var chars = new Array(view.length); for (var i = 0; i < view.length; i++) { chars[i] = String.fromCharCode(view[i]) } return chars.join("") } function bufferClone(buf) { if (buf.slice) { return buf.slice(0) } else { var view = new Uint8Array(buf.byteLength); view.set(new Uint8Array(buf)); return view.buffer } } function Body() { this.bodyUsed = false; this._initBody = function(body) { this._bodyInit = body; if (!body) { this._bodyText = "" } else if (typeof body === "string") { this._bodyText = body } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { this._bodyBlob = body } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { this._bodyFormData = body } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { this._bodyText = body.toString() } else if (support.arrayBuffer && support.blob && isDataView(body)) { this._bodyArrayBuffer = bufferClone(body.buffer); this._bodyInit = new Blob([this._bodyArrayBuffer]) } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { this._bodyArrayBuffer = bufferClone(body) } else { throw new Error("unsupported BodyInit type") } if (!this.headers.get("content-type")) { if (typeof body === "string") { this.headers.set("content-type", "text/plain;charset=UTF-8") } else if (this._bodyBlob && this._bodyBlob.type) { this.headers.set("content-type", this._bodyBlob.type) } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8") } } }; if (support.blob) { this.blob = function() { var rejected = consumed(this); if (rejected) { return rejected } if (this._bodyBlob) { return Promise.resolve(this._bodyBlob) } else if (this._bodyArrayBuffer) { return Promise.resolve(new Blob([this._bodyArrayBuffer])) } else if (this._bodyFormData) { throw new Error("could not read FormData body as blob") } else { return Promise.resolve(new Blob([this._bodyText])) } }; this.arrayBuffer = function() { if (this._bodyArrayBuffer) { return consumed(this) || Promise.resolve(this._bodyArrayBuffer) } else { return this.blob().then(readBlobAsArrayBuffer) } } } this.text = function() { var rejected = consumed(this); if (rejected) { return rejected } if (this._bodyBlob) { return readBlobAsText(this._bodyBlob) } else if (this._bodyArrayBuffer) { return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)) } else if (this._bodyFormData) { throw new Error("could not read FormData body as text") } else { return Promise.resolve(this._bodyText) } }; if (support.formData) { this.formData = function() { return this.text().then(decode) } } this.json = function() { return this.text().then(JSON.parse) }; return this } var methods = ["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"]; function normalizeMethod(method) { var upcased = method.toUpperCase(); return methods.indexOf(upcased) > -1 ? upcased : method } function Request(input, options) { options = options || {}; var body = options.body; if (input instanceof Request) { if (input.bodyUsed) { throw new TypeError("Already read") } this.url = input.url; this.credentials = input.credentials; if (!options.headers) { this.headers = new Headers(input.headers) } this.method = input.method; this.mode = input.mode; if (!body && input._bodyInit != null) { body = input._bodyInit; input.bodyUsed = true } } else { this.url = String(input) } this.credentials = options.credentials || this.credentials || "omit"; if (options.headers || !this.headers) { this.headers = new Headers(options.headers) } this.method = normalizeMethod(options.method || this.method || "GET"); this.mode = options.mode || this.mode || null; this.referrer = null; if ((this.method === "GET" || this.method === "HEAD") && body) { throw new TypeError("Body not allowed for GET or HEAD requests") } this._initBody(body) } Request.prototype.clone = function() { return new Request(this, { body: this._bodyInit }) }; function decode(body) { var form = new FormData; body.trim().split("&").forEach(function(bytes) { if (bytes) { var split = bytes.split("="); var name = split.shift().replace(/\+/g, " "); var value = split.join("=").replace(/\+/g, " "); form.append(decodeURIComponent(name), decodeURIComponent(value)) } }); return form } function parseHeaders(rawHeaders) { var headers = new Headers; rawHeaders.split(/\r?\n/).forEach(function(line) { var parts = line.split(":"); var key = parts.shift().trim(); if (key) { var value = parts.join(":").trim(); headers.append(key, value) } }); return headers } Body.call(Request.prototype); function Response(bodyInit, options) { if (!options) { options = {} } this.type = "default"; this.status = "status" in options ? options.status : 200; this.ok = this.status >= 200 && this.status < 300; this.statusText = "statusText" in options ? options.statusText : "OK"; this.headers = new Headers(options.headers); this.url = options.url || ""; this._initBody(bodyInit) } Body.call(Response.prototype); Response.prototype.clone = function() { return new Response(this._bodyInit, { status: this.status, statusText: this.statusText, headers: new Headers(this.headers), url: this.url }) }; Response.error = function() { var response = new Response(null, { status: 0, statusText: "" }); response.type = "error"; return response }; var redirectStatuses = [301, 302, 303, 307, 308]; Response.redirect = function(url, status) { if (redirectStatuses.indexOf(status) === -1) { throw new RangeError("Invalid status code") } return new Response(null, { status: status, headers: { location: url } }) }; self.Headers = Headers; self.Request = Request; self.Response = Response; self.fetch = function(input, init) { return new Promise(function(resolve, reject) { var request = new Request(input, init); var xhr = new XMLHttpRequest; xhr.onload = function() { var options = { status: xhr.status, statusText: xhr.statusText, headers: parseHeaders(xhr.getAllResponseHeaders() || "") }; options.url = "responseURL" in xhr ? xhr.responseURL : options.headers.get("X-Request-URL"); var body = "response" in xhr ? xhr.response : xhr.responseText; resolve(new Response(body, options)) }; xhr.onerror = function() { reject(new TypeError("Network request failed")) }; xhr.ontimeout = function() { reject(new TypeError("Network request failed")) }; xhr.open(request.method, request.url, true); if (request.credentials === "include") { xhr.withCredentials = true } if ("responseType" in xhr && support.blob) { xhr.responseType = "blob" } request.headers.forEach(function(value, name) { xhr.setRequestHeader(name, value) }); xhr.send(typeof request._bodyInit === "undefined" ? null : request._bodyInit) }) }; self.fetch.polyfill = true })(typeof self !== "undefined" ? self : this) }, {}], 16: [function(require, module, exports) { var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue) } else { queueIndex = -1 } if (queue.length) { drainQueue() } } function drainQueue() { if (draining) { return } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while (len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run() } } queueIndex = -1; len = queue.length } currentQueue = null; draining = false; clearTimeout(timeout) } process.nextTick = function(fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i] } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0) } }; function Item(fun, array) { this.fun = fun; this.array = array } Item.prototype.run = function() { this.fun.apply(null, this.array) }; process.title = "browser"; process.browser = true; process.env = {}; process.argv = []; process.version = ""; process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function(name) { throw new Error("process.binding is not supported") }; process.cwd = function() { return "/" }; process.chdir = function(dir) { throw new Error("process.chdir is not supported") }; process.umask = function() { return 0 } }, {}] }, {}, [1]);
{ "content_hash": "1be0e21f35e327528ac40ca4e7716809", "timestamp": "", "source": "github", "line_count": 8455, "max_line_length": 600, "avg_line_length": 30.97705499704317, "alnum_prop": 0.5846108029063308, "repo_name": "edwardzhong/sites", "id": "7b8ec3310b7f39ff7a958a60f8d86ac85e2596ef", "size": "262103", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cosmic-demo/lib/cosmicjs.browser.min.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "11002" }, { "name": "HTML", "bytes": "73299" }, { "name": "JavaScript", "bytes": "24608" } ], "symlink_target": "" }
package org.copperengine.core.audit; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; import java.sql.Types; import java.util.Collection; import java.util.Date; import java.util.List; import org.copperengine.core.batcher.AbstractBatchCommand; import org.copperengine.core.batcher.BatchCommand; import org.copperengine.core.batcher.BatchExecutor; import org.copperengine.core.batcher.CommandCallback; import org.copperengine.core.db.utility.JdbcUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BatchInsertIntoAutoTrail { public static final class Command extends AbstractBatchCommand<Executor, Command> { final AuditTrailEvent data; final boolean isOracle; final String sqlStmt; final List<Method> propertyGetters; public Command(AuditTrailEvent data, boolean isOracle, String sqlStmt, List<Method> propertyGetters, CommandCallback<Command> callback, int timeout) { super(callback, System.currentTimeMillis() + timeout); if (data == null) throw new NullPointerException(); if (sqlStmt == null) throw new NullPointerException(); if (propertyGetters == null) throw new NullPointerException(); this.data = data; this.isOracle = isOracle; this.sqlStmt = sqlStmt; this.propertyGetters = propertyGetters; } @Override public Executor executor() { return Executor.INSTANCE; } } public static final class Executor extends BatchExecutor<Executor, Command> { private static final Executor INSTANCE = new Executor(); private static final Logger logger = LoggerFactory.getLogger(Executor.class); @Override public int maximumBatchSize() { return 50; } @Override public int preferredBatchSize() { return 20; } @SuppressWarnings("resource") @Override public void doExec(final Collection<BatchCommand<Executor, Command>> commands, final Connection con) throws Exception { if (commands.isEmpty()) return; final Command firstCommand = (Command) commands.iterator().next(); final boolean isOracle = firstCommand.isOracle; final String sqlStmt = firstCommand.sqlStmt; final List<Method> propertyGetters = firstCommand.propertyGetters; PreparedStatement preparedStmt = null; try { preparedStmt = con.prepareStatement(sqlStmt); for (BatchCommand<Executor, Command> _cmd : commands) { Command cmd = (Command) _cmd; int idx = 1; AuditTrailEvent data = cmd.data; if (isOracle) { if (data.getSequenceId() == null) { preparedStmt.setNull(idx++, Types.NUMERIC); } else { preparedStmt.setLong(idx++, data.getSequenceId().longValue()); } } else { if (data.getSequenceId() != null) { throw new UnsupportedOperationException("Custom SequenceId currently not supported for this DBMS"); } } for (Method m : propertyGetters) { try { Object value = null; if (m.getDeclaringClass().isAssignableFrom(data.getClass())) { value = m.invoke(data, (Object[]) null); } if (value != null) { if (value instanceof Date) { value = new Timestamp(((Date) value).getTime()); } preparedStmt.setObject(idx++, value, guessJdbcType(m)); } else { preparedStmt.setNull(idx++, guessJdbcType(m)); } } catch (SQLException e) { logger.error("Setting property " + m + " failed", e); throw e; } } preparedStmt.addBatch(); } preparedStmt.executeBatch(); } catch (SQLException e) { logger.error(firstCommand.sqlStmt + " failed", e); throw e; } finally { JdbcUtils.closeStatement(preparedStmt); } } } static int guessJdbcType(Method m) { Class<?> type = m.getReturnType(); if (type == String.class) return Types.VARCHAR; if (type == Integer.class || type == Integer.TYPE) return Types.INTEGER; if (type == Long.class || type == Long.TYPE) return Types.NUMERIC; if (type == Float.class || type == Float.TYPE) return Types.NUMERIC; if (type == Double.class || type == Double.TYPE) return Types.NUMERIC; if (type == Timestamp.class || type == Date.class || type == java.sql.Date.class) return Types.TIMESTAMP; throw new UnsupportedOperationException("no mapping for type " + type); } }
{ "content_hash": "e68546cad95dc690a6051b3ceb9e5de8", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 158, "avg_line_length": 38.34931506849315, "alnum_prop": 0.5393820325058046, "repo_name": "copper-engine/copper-engine", "id": "3027ac4aafa9b5a3a0f9ac691f7423be59585412", "size": "6207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "projects/copper-coreengine/src/main/java/org/copperengine/core/audit/BatchInsertIntoAutoTrail.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "10534" }, { "name": "Java", "bytes": "1975566" }, { "name": "PLSQL", "bytes": "12251" } ], "symlink_target": "" }
package com.akiban.sql.parser; public class OrNode extends BinaryLogicalOperatorNode { /** * Initializer for an OrNode * * @param leftOperand The left operand of the OR * @param rightOperand The right operand of the OR */ public void init(Object leftOperand, Object rightOperand) { super.init(leftOperand, rightOperand, "or"); this.shortCircuitValue = true; } }
{ "content_hash": "fb1e9c4a7ae1eee64d17c3c752b5e943", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 63, "avg_line_length": 24.22222222222222, "alnum_prop": 0.6422018348623854, "repo_name": "youngor/openclouddb", "id": "73b03d05380b9bc9f31f4fdb5fc4d2db726213ca", "size": "1558", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MyCAT/src/main/java/com/akiban/sql/parser/OrNode.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "668381" }, { "name": "Java", "bytes": "11214966" }, { "name": "JavaScript", "bytes": "660124" }, { "name": "Shell", "bytes": "34282" } ], "symlink_target": "" }
import React from "react"; import Grid from "@material-ui/core/Grid"; import Paper from "@material-ui/core/Paper"; import { withStyles, createMuiTheme } from "@material-ui/core/styles"; import Typography from "@material-ui/core/Typography"; import SelectUrlStep from "./select-url-step"; const styleSheet = createMuiTheme("GuttersGrid", theme => ({ root: { flexGrow: 1, backgroundColor: "#1a5099", minHeight: "600px" }, steemBox: { minHeight: "500px" }, footer:{ backgroundColor: '#eff1ef' }, paper: { padding: "1em" } })); class App extends React.Component { render() { const classes = this.props.classes; return ( <Grid container className={classes.root} justify="center"> <Paper className={classes.paper}> <Grid item xs={12} sm={10}> <Grid container justify="center" align="center" direction="column"> <Typography type="display2" gutterBottom> SteemWinner is almost back </Typography> <img style={{marginBottom:'45px', width:'80%'}} src="https://steemitimages.com/0x0/https://steemitimages.com/DQmSVzU4aQ9tB8gxwLyq4VaYFsywooPWJkeVqYkzoTsZHhK/steem-winner-promo.png" alt="SteemWinner" /> </Grid> <Typography type="headline" gutterBottom> Pick randomly one or more winners from the people who commented on your Steem post. </Typography> </Grid> <Grid container className={classes.steemBox}> <Grid item xs={12} sm={10}> <SelectUrlStep /> </Grid> </Grid> <Grid container gutter={24} justify="center" className={classes.footer}> <Grid item xs={3}> <a href="https://github.com/grigio/steemwinner">Source Code</a> on Github </Grid> <Grid item xs={3}> Donate Steem to <a href="https://steemit.com/@luigi-tecnologo">@luigi-tecnologo</a> </Grid> </Grid> </Paper> </Grid> ); } } export default withStyles(styleSheet)(App);
{ "content_hash": "65dbd3469e0ce606afffb1f0bb216b0c", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 183, "avg_line_length": 32.95384615384615, "alnum_prop": 0.5873015873015873, "repo_name": "grigio/steemwinner", "id": "10cfd68ae1da4eaf522a048ca69278d501fc4678", "size": "2142", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/App.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "9546" } ], "symlink_target": "" }
@interface TestDataSource : XJBaseDataSource - (void)getHomeData; @end
{ "content_hash": "8f358f1d8a4f495b2cc7659494fbc3a4", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 44, "avg_line_length": 23.666666666666668, "alnum_prop": 0.8028169014084507, "repo_name": "LiuXiangJing/XJNetworking", "id": "239958e56448aca3e8a07989abc57091b92e7c49", "size": "262", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "XJNetworkingDemo/XJNetworkingDemo/Demo/TestDataSource.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "28644" }, { "name": "Ruby", "bytes": "787" } ], "symlink_target": "" }
package com.salama.easysqlparser.base; import java.util.ArrayList; import java.util.List; public class SqlPart { public enum SqlPartType { //Union Union, //Select ---------- Select, From, Join, Where, GroupBy, Having, OrderBy, Limit, //Insert ---------- Insert, Into, Values, Value, //Update ---------- Update, Set, //Delete ---------- Delete, Truncate, Drop, Create, Using, Others } ; public SqlPartType partType; //public StringBuilder sql = new StringBuilder(); public List<String> tokenList = new ArrayList<String>(); // @Override // public void appendToSql(StringBuilder sql) throws SqlParseException { // sql.append(this.sql); // } public void toSql(StringBuilder sql) { for (int i = 0; i < tokenList.size(); i++) { sql.append(" ").append(tokenList.get(i)); } } @Override public String toString() { StringBuilder sql = new StringBuilder(); toSql(sql); return sql.toString(); } }
{ "content_hash": "8dccbf991d1ecb0951152f2e3c81b632", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 72, "avg_line_length": 22.08, "alnum_prop": 0.5552536231884058, "repo_name": "SalamaSoft/EasySqlParser", "id": "e350f2c803d672ec8c5503916c018dc3f1130c01", "size": "1104", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/EasySqlParser/src/main/java/com/salama/easysqlparser/base/SqlPart.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "60304" } ], "symlink_target": "" }
jest.mock('fs'); jest.mock('path'); const fs = require('fs'); const path = require('path'); const resolveCustomFormatter = require('../resolveCustomFormatter'); describe('resolveCustomFormatter', () => { it('should return absolute path when provided path is a file path', () => { const aRelativePath = 'a/relative/path'; const expected = `/cwd/${aRelativePath}`; path.resolve.mockReturnValue(expected); path.isAbsolute.mockReturnValue(false); fs.existsSync.mockReturnValue(true); const result = resolveCustomFormatter(aRelativePath); expect(result).toEqual(expected); }); it('should return provided path when path is neither absolute nor relative', () => { const aModulePath = '@stylelint/prettier-config/index.js'; fs.existsSync.mockReturnValue(false); const result = resolveCustomFormatter(aModulePath); const realPathModule = jest.requireActual('path'); const expectedPath = realPathModule.join('node_modules', aModulePath); expect(result.endsWith(expectedPath)).toBe(true); }); });
{ "content_hash": "8f24033f4e82180c5e4415ed2dcda923", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 85, "avg_line_length": 30.176470588235293, "alnum_prop": 0.7309941520467836, "repo_name": "stylelint/stylelint", "id": "4e8d2270b1c9f35a9f0d9eb51d9df86313704f1c", "size": "1026", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "lib/__tests__/resolveCustomFormatter.test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15253" }, { "name": "HTML", "bytes": "697" }, { "name": "JavaScript", "bytes": "2806050" }, { "name": "Less", "bytes": "4" }, { "name": "SCSS", "bytes": "2514" }, { "name": "Sass", "bytes": "2" }, { "name": "Shell", "bytes": "314" }, { "name": "TypeScript", "bytes": "4133" } ], "symlink_target": "" }