text
stringlengths
2
1.04M
meta
dict
package com.yahoo.memory; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** * Implementation of {@link WritableMemory} for ByteBuffer, non-native byte order. * * @author Roman Leventov * @author Lee Rhodes */ final class BBNonNativeWritableMemoryImpl extends NonNativeWritableMemoryImpl { private static final int id = MEMORY | NONNATIVE | BYTEBUF; private final Object unsafeObj; private final long nativeBaseOffset; //used to compute cumBaseOffset private final ByteBuffer byteBuf; //holds a reference to a ByteBuffer until we are done with it. private final byte typeId; BBNonNativeWritableMemoryImpl( final Object unsafeObj, final long nativeBaseOffset, final long regionOffset, final long capacityBytes, final int typeId, final ByteBuffer byteBuf) { super(unsafeObj, nativeBaseOffset, regionOffset, capacityBytes); this.unsafeObj = unsafeObj; this.nativeBaseOffset = nativeBaseOffset; this.byteBuf = byteBuf; this.typeId = (byte) (id | (typeId & 0x7)); } @Override BaseWritableMemoryImpl toWritableRegion(final long offsetBytes, final long capacityBytes, final boolean readOnly, final ByteOrder byteOrder) { final int type = typeId | REGION | (readOnly ? READONLY : 0); return Util.isNativeOrder(byteOrder) ? new BBWritableMemoryImpl( unsafeObj, nativeBaseOffset, getRegionOffset(offsetBytes), capacityBytes, type, getByteBuffer()) : new BBNonNativeWritableMemoryImpl( unsafeObj, nativeBaseOffset, getRegionOffset(offsetBytes), capacityBytes, type, getByteBuffer()); } @Override BaseWritableBufferImpl toWritableBuffer(final boolean readOnly, final ByteOrder byteOrder) { final int type = typeId | (readOnly ? READONLY : 0); return Util.isNativeOrder(byteOrder) ? new BBWritableBufferImpl( unsafeObj, nativeBaseOffset, getRegionOffset(), getCapacity(), type, byteBuf, this) : new BBNonNativeWritableBufferImpl( unsafeObj, nativeBaseOffset, getRegionOffset(), getCapacity(), type, byteBuf, this); } @Override public ByteBuffer getByteBuffer() { assertValid(); return byteBuf; } @Override long getNativeBaseOffset() { return nativeBaseOffset; } @Override int getTypeId() { return typeId & 0xff; } @Override Object getUnsafeObject() { assertValid(); return unsafeObj; } }
{ "content_hash": "aa1c1554c0758680f0ae3bfeb8496b0e", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 98, "avg_line_length": 30.24390243902439, "alnum_prop": 0.7036290322580645, "repo_name": "ApacheInfra/incubator-datasketches-memory", "id": "e760cefa9e81b870f388da237f7b66c4c7b83c4e", "size": "2620", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/yahoo/memory/BBNonNativeWritableMemoryImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "637131" } ], "symlink_target": "" }
<th:block xmlns:th="http://www.thymeleaf.org"> <script type="text/javascript"> $(function() { bindPopovers(); }); </script> <h3 class="text-nowrap"><i class="fa fa-flask"></i> Elo K-Factor Tweaks</h3> <p> <th:block th:include="fragments/promotion :: logo"/> has been using the <a href="https://en.wikipedia.org/wiki/Elo_rating_system" target="_blank" rel="noopener noreferrer" class="external">Elo rating</a> system and tennis-customized K-factor function for a long time. <abbr title="Ultimate Tennis Statistics">UTS</abbr> users do appreciate both Elo ratings accuracy and weekly refresh, but most importantly, ratings stability, as the same formula was used for more than 2 years. </p> <h4>The Old Formula</h4> <p> Leveraging original Elo system, <abbr title="Ultimate Tennis Statistics">UTS</abbr> K-factor function incorporates in the ratings opponent strength, meaning wins over quality opponents increase ratings more, while loses from lower ranked players decrease ratings fast. However, UTS is also going further. In order to accommodate to tennis and to reflect the different significance of tennis matches at different tournament levels, different rounds and the difference between best-of-3 and best-of-5, UTS uses highly tennis-customized Elo K-factor function. </p> <p> This formula was good, but was not perfect. It was good to reflect current players' form but also to compare players' strengths across Eras. However, it had one shortcoming: it was not optimized for maximum predictability of tennis matches. It was a little bit overestimating current form, as well as it did not make fast enough progress of the newcomers to the top of the rankings. </p> <h4>The New Formula</h4> <p> <img src="/images/blog/k-factor.png" width="220" height="112" alt="K-factor" style="float: right"/> As UTS features <a href="/inProgressEventsForecasts">Tournament Forecasts</a> that are very much dependent on Elo ratings, it was necessary to optimize K-factor function for maximum predictability. Details on new K-factor function can be found <a href="#" data-toggle="popover" data-trigger="focus" data-placement="auto" data-popover="#eloRatingPopover">here</a>.<br/> The most notable change is a different function for K-factor dependence on the current player rating. Instead of a function with three linear sections, the new unified logistic function allows much smoother and much faster progress of newcomers to the top 50, as well as smother stabilization of the top 50 ratings and players.<br/> </p> <h4>Parameter Tweaking</h4> <p> All K-factor parameters are also tweaked for optimal predictability. Interesting is that the old parameters for tournament level, round, best-of and walkover are still standing and that predictability scoring has shown that they really hold. It is just that these parameters are a little bit tweaked, while it is proven that their existence does influence predictability. Without even single item predictability will be lower, which proves that there really exists a significant difference in importance of wins in different tournament levels, rounds and best-of-3/5 formats, as well as that walkover wins do influence predictability of future matches. </p> <p> New formula increases the prediction rate of Elo ratings by around 0.6%. It may sound a small increase, but when approaching the limit of the inherent randomness of tennis matches outcomes, this is a significant increase. </p> <h4>The 'Big Picture' Differences</h4> <p> All historical Elo ratings are recalculated from scratch, thus <a href="/peakEloRatings">Peak Elo Ratings</a> lists contain new figures. However, in general, you will notice little changes, as the previous function was good, but the new function is a little better as it features maximum predictability in addition. This means it can both better predict match winners when players are of similar strength, but also gives more accurate probabilities when favorites play the outsiders. </p> <p> For the other usages of Elo Ratings on Ultimate Tennis Statistics, new Elo K-factor formula reflects better player strengths across Eras, as at the end of the day, what matters is only predictability. If a function gives more predictability, it better reflects player strengths in the Era, but as average Elo ratings are still constant over time, also across Eras. </p> <footer class="text-right"><i class="fa fa-calendar"></i> 12-03-2018</footer> <th:block th:include="blog/blogComments :: comments('eloKfactorTweaks')"/> <div th:include="fragments/aboutElo :: aboutEloFormula"></div> </th:block>
{ "content_hash": "c1325a22257776f315f3538b9a4bf635", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 372, "avg_line_length": 97.48936170212765, "alnum_prop": 0.7795722391968573, "repo_name": "mcekovic/tennis-crystal-ball", "id": "84558d8baa1fb2b09e278abed2171704ddfe5503", "size": "4582", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tennis-stats/src/main/resources/templates/blog/eloKfactorTweaks.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7334" }, { "name": "Dockerfile", "bytes": "821" }, { "name": "Groovy", "bytes": "233228" }, { "name": "HTML", "bytes": "1190999" }, { "name": "Java", "bytes": "1605063" }, { "name": "JavaScript", "bytes": "36603" }, { "name": "Kotlin", "bytes": "12881" }, { "name": "PLpgSQL", "bytes": "67620" }, { "name": "Shell", "bytes": "681" } ], "symlink_target": "" }
require 'concurrent/concern/logging' require 'concurrent/synchronization' module Concurrent # Provides ability to add and remove handlers to be run at `Kernel#at_exit`, order is undefined. # Each handler is executed at most once. # # @!visibility private class AtExitImplementation < Synchronization::Object include Concern::Logging def initialize(*args) super() synchronize { ns_initialize *args } end # Add a handler to be run at `Kernel#at_exit` # @param [Object] handler_id optionally provide an id, if allready present, handler is replaced # @yield the handler # @return id of the handler def add(handler_id = nil, &handler) id = handler_id || handler.object_id synchronize { @handlers[id] = handler } id end # Delete a handler by handler_id # @return [true, false] def delete(handler_id) !!synchronize { @handlers.delete handler_id } end # Is handler with handler_id rpesent? # @return [true, false] def handler?(handler_id) synchronize { @handlers.key? handler_id } end # @return copy of the handlers def handlers synchronize { @handlers }.clone end # install `Kernel#at_exit` callback to execute added handlers def install synchronize do @installed ||= begin at_exit { runner } true end self end end # Will it run during `Kernel#at_exit` def enabled? synchronize { @enabled } end # Configure if it runs during `Kernel#at_exit` def enabled=(value) synchronize { @enabled = value } end # run the handlers manually # @return ids of the handlers def run handlers, _ = synchronize { handlers, @handlers = @handlers, {} } handlers.each do |_, handler| begin handler.call rescue => error log ERROR, error end end handlers.keys end private def ns_initialize(enabled = true) @handlers = {} @enabled = enabled end def runner run if synchronize { @enabled } end end private_constant :AtExitImplementation # @see AtExitImplementation # @!visibility private AtExit = AtExitImplementation.new.install end
{ "content_hash": "9dc267bf8acff21dec7989b6cd39fbb0", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 99, "avg_line_length": 23.608247422680414, "alnum_prop": 0.625764192139738, "repo_name": "iNecas/concurrent-ruby", "id": "93b298997bdfbdaa1c8714acef5b84387eb11cb6", "size": "2290", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/concurrent/utility/at_exit.rb", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "10156" }, { "name": "CSS", "bytes": "2150" }, { "name": "HTML", "bytes": "640" }, { "name": "Java", "bytes": "24995" }, { "name": "Ruby", "bytes": "868942" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>fcsl-pcm: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.15.1 / fcsl-pcm - 1.2.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> fcsl-pcm <small> 1.2.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-04-01 06:07:12 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-01 06:07:12 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.15.1 Formal proof management system dune 3.0.3 Fast, portable, and opinionated build system ocaml 4.07.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.07.1 Official release 4.07.1 ocaml-config 1 OCaml Switch Configuration ocaml-secondary-compiler 4.08.1-1 OCaml 4.08.1 Secondary Switch Compiler ocamlfind 1.9.1 A library manager for OCaml ocamlfind-secondary 1.9.1 Adds support for ocaml-secondary-compiler to ocamlfind zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;FCSL &lt;fcsl@software.imdea.org&gt;&quot; homepage: &quot;http://software.imdea.org/fcsl/&quot; bug-reports: &quot;https://github.com/imdea-software/fcsl-pcm/issues&quot; dev-repo: &quot;git+https://github.com/imdea-software/fcsl-pcm.git&quot; license: &quot;Apache-2.0&quot; build: [ make &quot;-j%{jobs}%&quot; ] install: [ make &quot;install&quot; ] depends: [ &quot;coq&quot; {(&gt;= &quot;8.10&quot; &amp; &lt; &quot;8.13~&quot;) | (= &quot;dev&quot;)} &quot;coq-mathcomp-ssreflect&quot; {(&gt;= &quot;1.10.0&quot; &amp; &lt; &quot;1.12~&quot;) | (= &quot;dev&quot;)} ] tags: [ &quot;keyword:separation logic&quot; &quot;keyword:partial commutative monoid&quot; &quot;category:Computer Science/Data Types and Data Structures&quot; &quot;logpath:fcsl&quot; &quot;date:2019-11-07&quot; ] authors: [ &quot;Aleksandar Nanevski&quot; ] synopsis: &quot;Partial Commutative Monoids&quot; description: &quot;&quot;&quot; The PCM library provides a formalisation of Partial Commutative Monoids (PCMs), a common algebraic structure used in separation logic for verification of pointer-manipulating sequential and concurrent programs. The library provides lemmas for mechanised and automated reasoning about PCMs in the abstract, but also supports concrete common PCM instances, such as heaps, histories and mutexes. This library relies on extensionality axioms: propositional and functional extentionality.&quot;&quot;&quot; url { src: &quot;https://github.com/imdea-software/fcsl-pcm/archive/v1.2.0.tar.gz&quot; checksum: &quot;sha256=5faabb3660fa7d9fe83d6947621ac34dc20076e28bcd9e87b46edb62154fd4e8&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-fcsl-pcm.1.2.0 coq.8.15.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.15.1). The following dependencies couldn&#39;t be met: - coq-fcsl-pcm -&gt; coq (&lt; 8.13~ &amp; = dev) -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-fcsl-pcm.1.2.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "1fe54ca091fa9b26a8a30a930262b39f", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 159, "avg_line_length": 42.84444444444444, "alnum_prop": 0.5586099585062241, "repo_name": "coq-bench/coq-bench.github.io", "id": "78da7e757ce1e491a2cba7f3941181d63d7813cc", "size": "7737", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.07.1-2.0.6/released/8.15.1/fcsl-pcm/1.2.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
layout: article amp: true amp-mustache: true amp-form: true amp-iframe: true title: "Kitesurfing privat lessons &#128242;+34-696-264729" subtitle: "Kitesurfing courses and lessons" date: 2019-02-27T12:57:10+01:00 modified: 2020-03-11T12:25:00.000Z author: daniel description: "&#128081;Private lessons that focus on you when it comes to kitesurfing. For all who want to get to their goal faster." image: background: 3.jpg background2: 7.webp feature: "flying-friends/Privatlesson_with_Dani_l.jpg" width: 1200px height: 675px teaser: thumb: flying-friends/l_kite-mallorca_055.jpg picnum: 55 snippets: null lang: en "en-url": en/kitesurfing-lessons/privatlessons/ "es-url": es/cursos-de-kitesurf/privado/ "de-url": de/kitekurse/privatstunden/ t: menutxt1: "kitesurfing lessons" link1: "kitesurfing-lessons/" menutxt2: "rental" link2: "renting/" menutxt3: "wind" link3: "wind/" menutxt4: "contact" link4: "contact/" menutxt5: "pictures & videos" link5: "flying-friends/" menutxt6: "Disclaimer" link6: "disclaimer/" menutxt7: "Contact us" link7: "contact-us/" link8: "shop/" menutxt8: shop link9: "outfit/" menutxt9: "Outfit" link20: "kitesurfing-lessons/tryout/" menutxt20: "Tryout" link21: "kitesurfing-lessons/beginner/" menutxt21: "Beginner" link22: "kitesurfing-lessons/advanced/" menutxt22: "Advanced" link23: "kitesurfing-lessons/hydrofoil/" menutxt23: "Hydrofoil" link24: "kitesurfing-lessons/privatlessons/" menutxt24: "Privat lessons" link30: "renting/per-hour-or-day/" menutxt30: "Renting per hour or day" link31: "renting/long-term/" menutxt31: "Long term rent" menutxt100: "Close" teaser: KITESURFING LESSONS --- <h1>Refresher lessons and further education in kitesurfing. (English)</h1> <br> FROM 55.00 Euro per person/hour<br> by more then 4 hours with 10% discount<br><br> <span>Refresher course in kitesurfing: for those who have already had contact with kitesurfing and want to develop further here. Material does not have to be shared with others and is included in the price.</span> <div class="item"> <ul> <li>Improve your previous skills</li> <li>Payable even after completion</li> <li>You continue where you were the last time</li> <li>Our teachers speak English, German, Spanish, Italian, Catalan, Finnish, Dutch</li> </ul> </div> {% include amp-chatlinks.html %} {% include carousel.html %} <span>Please bring: Swimsuit Suncream Sunglasses Drinkwater</span><br> <span><strong>Please note</strong> The start times can shift, depending on the wind. Please ask for confirmation: mobile Daniel +34 696 264 729.</span><br><br><br><br>
{ "content_hash": "17f21590b76fecff43ff3038dc9f4df7", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 133, "avg_line_length": 30.620689655172413, "alnum_prop": 0.725975975975976, "repo_name": "kitesurf/kitesurf.github.io", "id": "638060db7735fcdea78aa97d56602168de5bc090", "size": "2668", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "amp/en/kitesurfing-lessons/privatlessons/index.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "113162" }, { "name": "HTML", "bytes": "250968" }, { "name": "JavaScript", "bytes": "225342" }, { "name": "PHP", "bytes": "1117" }, { "name": "Ruby", "bytes": "311" }, { "name": "SCSS", "bytes": "73878" } ], "symlink_target": "" }
package edu.cmu.cs.stage3.alice.core.question.time; public class DayOfWeekInMonth extends edu.cmu.cs.stage3.alice.core.question.IntegerQuestion { public Object getValue() { java.util.Calendar calendar = new java.util.GregorianCalendar(); java.util.Date date = new java.util.Date(); calendar.setTime( date ); return new Integer( calendar.get( java.util.Calendar.DAY_OF_WEEK_IN_MONTH ) ); } }
{ "content_hash": "9ccdab29bb8c4c34d1b54bef6ed6e676", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 93, "avg_line_length": 34.5, "alnum_prop": 0.7318840579710145, "repo_name": "ai-ku/langvis", "id": "3c2f5b3ea0f61b9c6df06aa17cda30cb1b486e2f", "size": "1435", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/edu/cmu/cs/stage3/alice/core/question/time/DayOfWeekInMonth.java", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "1391" }, { "name": "Haskell", "bytes": "1005" }, { "name": "Java", "bytes": "7426611" }, { "name": "Perl", "bytes": "10563" }, { "name": "Python", "bytes": "1744764" }, { "name": "Ruby", "bytes": "691" }, { "name": "Shell", "bytes": "701" } ], "symlink_target": "" }
<?php namespace Bemoove\AppBundle\Repository; /** * TagRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class TagRepository extends \Doctrine\ORM\EntityRepository { }
{ "content_hash": "e6edf4aa480a5be5b98b1e61d0966775", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 68, "avg_line_length": 18.23076923076923, "alnum_prop": 0.7510548523206751, "repo_name": "XavierGuichet/bemoove", "id": "a9183c78c16fed10258ac216006310e4aa72d282", "size": "237", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Bemoove/AppBundle/Repository/TagRepository.php", "mode": "33188", "license": "mit", "language": [ { "name": "Gherkin", "bytes": "4083" }, { "name": "HTML", "bytes": "57708" }, { "name": "PHP", "bytes": "302637" }, { "name": "Shell", "bytes": "1536" } ], "symlink_target": "" }
package io.prometheus.client.exporter; import com.sun.net.httpserver.Authenticator; import com.sun.net.httpserver.BasicAuthenticator; import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsParameters; import io.prometheus.client.CollectorRegistry; import io.prometheus.client.Gauge; import io.prometheus.client.SampleNameFilter; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import javax.xml.bind.DatatypeConverter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.cert.X509Certificate; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static org.assertj.core.api.Java6Assertions.assertThat; public class TestHTTPServer { CollectorRegistry registry; private final static SSLContext SSL_CONTEXT; private final static HttpsConfigurator HTTPS_CONFIGURATOR; // Code put in a static block due to possible Exceptions static { try { SSL_CONTEXT = createSSLContext( "SSL", "PKCS12", "./src/test/resources/keystore.pkcs12", "changeit"); } catch (GeneralSecurityException e) { throw new RuntimeException("Exception creating SSL_CONTEXT", e); } catch (IOException e) { throw new RuntimeException("Exception creating SSL_CONTEXT", e); } HTTPS_CONFIGURATOR = createHttpsConfigurator(SSL_CONTEXT); } /** * TrustManager[] that trusts all certificates */ private final static TrustManager[] TRUST_ALL_CERTS_TRUST_MANAGERS = new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; /** * HostnameVerifier that accepts any hostname */ private final static HostnameVerifier TRUST_ALL_HOSTS_HOSTNAME_VERIFIER = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; HttpRequest.Builder createHttpRequestBuilder(HTTPServer httpServer, String urlPath) { return new HttpRequest.Builder().withURL("http://localhost:" + httpServer.getPort() + urlPath); } HttpRequest.Builder createHttpRequestBuilderWithSSL(HTTPServer httpServer, String urlPath) { return new HttpRequest.Builder().withURL("https://localhost:" + httpServer.getPort() + urlPath) .withTrustManagers(TRUST_ALL_CERTS_TRUST_MANAGERS) .withHostnameVerifier(TRUST_ALL_HOSTS_HOSTNAME_VERIFIER); } HttpRequest.Builder createHttpRequestBuilder(HttpServer httpServer, String urlPath) { return new HttpRequest.Builder().withURL("http://localhost:" + httpServer.getAddress().getPort() + urlPath); } @Before public void init() throws IOException { registry = new CollectorRegistry(); Gauge.build("a", "a help").register(registry); Gauge.build("b", "a help").register(registry); Gauge.build("c", "a help").register(registry); } @Test(expected = IllegalArgumentException.class) public void testRefuseUsingUnbound() throws IOException { CollectorRegistry registry = new CollectorRegistry(); HTTPServer httpServer = new HTTPServer(HttpServer.create(), registry, true); httpServer.close(); } @Test public void testSimpleRequest() throws IOException { HTTPServer httpServer = new HTTPServer(new InetSocketAddress(0), registry); try { String body = createHttpRequestBuilder(httpServer, "/metrics").build().execute().getBody(); assertThat(body).contains("a 0.0"); assertThat(body).contains("b 0.0"); assertThat(body).contains("c 0.0"); } finally { httpServer.close(); } } @Test public void testBadParams() throws IOException { HTTPServer httpServer = new HTTPServer(new InetSocketAddress(0), registry); try { String body = createHttpRequestBuilder(httpServer, "/metrics?x").build().execute().getBody(); assertThat(body).contains("a 0.0"); assertThat(body).contains("b 0.0"); assertThat(body).contains("c 0.0"); } finally { httpServer.close(); } } @Test public void testSingleName() throws IOException { HTTPServer httpServer = new HTTPServer(new InetSocketAddress(0), registry); try { String body = createHttpRequestBuilder(httpServer, "/metrics?name[]=a").build().execute().getBody(); assertThat(body).contains("a 0.0"); assertThat(body).doesNotContain("b 0.0"); assertThat(body).doesNotContain("c 0.0"); } finally { httpServer.close(); } } @Test public void testMultiName() throws IOException { HTTPServer httpServer = new HTTPServer(new InetSocketAddress(0), registry); try { String body = createHttpRequestBuilder(httpServer, "/metrics?name[]=a&name[]=b").build().execute().getBody(); assertThat(body).contains("a 0.0"); assertThat(body).contains("b 0.0"); assertThat(body).doesNotContain("c 0.0"); } finally { httpServer.close(); } } @Test public void testSampleNameFilter() throws IOException { HTTPServer httpServer = new HTTPServer.Builder() .withRegistry(registry) .withSampleNameFilter(new SampleNameFilter.Builder() .nameMustNotStartWith("a") .build()) .build(); try { String body = createHttpRequestBuilder(httpServer, "/metrics?name[]=a&name[]=b").build().execute().getBody(); assertThat(body).doesNotContain("a 0.0"); assertThat(body).contains("b 0.0"); assertThat(body).doesNotContain("c 0.0"); } finally { httpServer.close(); } } @Test public void testSampleNameFilterEmptyBody() throws IOException { HTTPServer httpServer = new HTTPServer.Builder() .withRegistry(registry) .withSampleNameFilter(new SampleNameFilter.Builder() .nameMustNotStartWith("a") .nameMustNotStartWith("b") .build()) .build(); try { HttpResponse httpResponse = createHttpRequestBuilder(httpServer, "/metrics?name[]=a&name[]=b").build().execute(); assertThat(httpResponse.getBody()).isEmpty(); } finally { httpServer.close(); } } @Test public void testDecoding() throws IOException { HTTPServer httpServer = new HTTPServer(new InetSocketAddress(0), registry); try { String body = createHttpRequestBuilder(httpServer, "/metrics?n%61me[]=%61").build().execute().getBody(); assertThat(body).contains("a 0.0"); assertThat(body).doesNotContain("b 0.0"); assertThat(body).doesNotContain("c 0.0"); } finally { httpServer.close(); } } @Test public void testGzipCompression() throws IOException { HTTPServer httpServer = new HTTPServer(new InetSocketAddress(0), registry); try { String body = createHttpRequestBuilder(httpServer, "/metrics") .withHeader("Accept", "gzip") .withHeader("Accept", "deflate") .build().execute().getBody(); assertThat(body).contains("a 0.0"); assertThat(body).contains("b 0.0"); assertThat(body).contains("c 0.0"); } finally { httpServer.close(); } } @Test public void testOpenMetrics() throws IOException { HTTPServer httpServer = new HTTPServer(new InetSocketAddress(0), registry); try { String body = createHttpRequestBuilder(httpServer, "/metrics") .withHeader("Accept", "application/openmetrics-text; version=0.0.1,text/plain;version=0.0.4;q=0.5,*/*;q=0.1") .build().execute().getBody(); assertThat(body).contains("# EOF"); } finally { httpServer.close(); } } @Test public void testHealth() throws IOException { HTTPServer httpServer = new HTTPServer(new InetSocketAddress(0), registry); try { String body = createHttpRequestBuilder(httpServer, "/-/healthy").build().execute().getBody(); assertThat(body).contains("Exporter is Healthy"); } finally { httpServer.close(); } } @Test public void testHealthGzipCompression() throws IOException { HTTPServer httpServer = new HTTPServer(new InetSocketAddress(0), registry); try { String body = createHttpRequestBuilder(httpServer, "/-/healthy") .withHeader("Accept", "gzip") .withHeader("Accept", "deflate") .build().execute().getBody(); assertThat(body).contains("Exporter is Healthy"); } finally { httpServer.close(); } } @Test public void testBasicAuthSuccess() throws IOException { HTTPServer httpServer = new HTTPServer.Builder() .withRegistry(registry) .withAuthenticator(createAuthenticator("/", "user", "secret")) .build(); try { String body = createHttpRequestBuilder(httpServer, "/metrics?name[]=a&name[]=b") .withAuthorization("user", "secret") .build().execute().getBody(); assertThat(body).contains("a 0.0"); } finally { httpServer.close(); } } @Test public void testBasicAuthCredentialsMissing() throws IOException { HTTPServer httpServer = new HTTPServer.Builder() .withRegistry(registry) .withAuthenticator(createAuthenticator("/", "user", "secret")) .build(); try { createHttpRequestBuilder(httpServer, "/metrics?name[]=a&name[]=b").build().execute().getBody(); Assert.fail("expected IOException with HTTP 401"); } catch (IOException e) { Assert.assertTrue(e.getMessage().contains("401")); } finally { httpServer.close(); } } @Test public void testBasicAuthWrongCredentials() throws IOException { HTTPServer httpServer = new HTTPServer.Builder() .withRegistry(registry) .withAuthenticator(createAuthenticator("/", "user", "secret")) .build(); try { createHttpRequestBuilder(httpServer, "/metrics?name[]=a&name[]=b") .withAuthorization("user", "wrong") .build().execute().getBody(); Assert.fail("expected IOException with HTTP 401"); } catch (IOException e) { Assert.assertTrue(e.getMessage().contains("401")); } finally { httpServer.close(); } } @Test public void testHEADRequest() throws IOException { HTTPServer httpServer = new HTTPServer.Builder() .withRegistry(registry) .build(); try { HttpResponse httpResponse = createHttpRequestBuilder(httpServer, "/metrics?name[]=a&name[]=b") .withMethod(HttpRequest.METHOD.HEAD) .build().execute(); Assert.assertNotNull(httpResponse); Assert.assertNotNull(httpResponse.getHeaderAsLong("content-length")); Assert.assertTrue(httpResponse.getHeaderAsLong("content-length") == 74); assertThat(httpResponse.getBody()).isEmpty(); } finally { httpServer.close(); } } @Test public void testHEADRequestWithSSL() throws GeneralSecurityException, IOException { HTTPServer httpServer = new HTTPServer.Builder() .withRegistry(registry) .withHttpsConfigurator(HTTPS_CONFIGURATOR) .build(); try { HttpResponse httpResponse = createHttpRequestBuilderWithSSL(httpServer, "/metrics?name[]=a&name[]=b") .withMethod(HttpRequest.METHOD.HEAD) .build().execute(); Assert.assertNotNull(httpResponse); Assert.assertNotNull(httpResponse.getHeaderAsLong("content-length")); Assert.assertTrue(httpResponse.getHeaderAsLong("content-length") == 74); assertThat(httpResponse.getBody()).isEmpty(); } finally { httpServer.close(); } } @Test public void testSimpleRequestHttpServerWithHTTPMetricHandler() throws IOException { InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 0); HttpServer httpServer = HttpServer.create(inetSocketAddress, 0); httpServer.createContext("/metrics", new HTTPServer.HTTPMetricHandler(registry)); httpServer.start(); try { String body = createHttpRequestBuilder(httpServer, "/metrics").build().execute().getBody(); assertThat(body).contains("a 0.0"); assertThat(body).contains("b 0.0"); assertThat(body).contains("c 0.0"); } finally { httpServer.stop(0); } } @Test public void testHEADRequestWithSSLAndBasicAuthSuccess() throws GeneralSecurityException, IOException { HTTPServer httpServer = new HTTPServer.Builder() .withRegistry(registry) .withHttpsConfigurator(HTTPS_CONFIGURATOR) .withAuthenticator(createAuthenticator("/", "user", "secret")) .build(); try { HttpResponse httpResponse = createHttpRequestBuilderWithSSL(httpServer, "/metrics?name[]=a&name[]=b") .withMethod(HttpRequest.METHOD.HEAD) .withAuthorization("user", "secret") .build().execute(); Assert.assertNotNull(httpResponse); Assert.assertNotNull(httpResponse.getHeaderAsLong("content-length")); Assert.assertTrue(httpResponse.getHeaderAsLong("content-length") == 74); assertThat(httpResponse.getBody()).isEmpty(); } finally { httpServer.close(); } } @Test public void testHEADRequestWithSSLAndBasicAuthCredentialsMissing() throws GeneralSecurityException, IOException { HTTPServer httpServer = new HTTPServer.Builder() .withRegistry(registry) .withHttpsConfigurator(HTTPS_CONFIGURATOR) .withAuthenticator(createAuthenticator("/", "user", "secret")) .build(); try { createHttpRequestBuilderWithSSL(httpServer, "/metrics?name[]=a&name[]=b") .withMethod(HttpRequest.METHOD.HEAD) .build().execute(); Assert.fail("expected IOException with HTTP 401"); } catch (IOException e) { Assert.assertTrue(e.getMessage().contains("401")); } finally { httpServer.close(); } } @Test public void testHEADRequestWithSSLAndBasicAuthWrongCredentials() throws GeneralSecurityException, IOException { HTTPServer httpServer = new HTTPServer.Builder() .withRegistry(registry) .withHttpsConfigurator(HTTPS_CONFIGURATOR) .withAuthenticator(createAuthenticator("/", "user", "secret")) .build(); try { createHttpRequestBuilderWithSSL(httpServer, "/metrics?name[]=a&name[]=b") .withMethod(HttpRequest.METHOD.HEAD) .withAuthorization("user", "wrong") .build().execute(); Assert.fail("expected IOException with HTTP 401"); } catch (IOException e) { Assert.assertTrue(e.getMessage().contains("401")); } finally { httpServer.close(); } } @Test public void testExecutorService() throws IOException { ExecutorService executorService = Executors.newFixedThreadPool(20); HTTPServer httpServer = new HTTPServer.Builder() .withExecutorService(executorService) .withRegistry(registry) .build(); Assert.assertEquals(httpServer.executorService, executorService); try { String body = createHttpRequestBuilder(httpServer, "/metrics").build().execute().getBody(); assertThat(body).contains("a 0.0"); assertThat(body).contains("b 0.0"); assertThat(body).contains("c 0.0"); } finally { httpServer.close(); } } @Test(expected = IllegalStateException.class) public void testExecutorServiceWithHttpServer() throws IOException { InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 0); HttpServer externalHttpServer = HttpServer.create(inetSocketAddress, 0); externalHttpServer.createContext("/metrics", new HTTPServer.HTTPMetricHandler(registry)); externalHttpServer.start(); ExecutorService executorService = Executors.newFixedThreadPool(20); HTTPServer httpServer = new HTTPServer.Builder() .withExecutorService(executorService) .withHttpServer(externalHttpServer) .withRegistry(registry) .build(); try { String body = createHttpRequestBuilder(httpServer, "/metrics").build().execute().getBody(); assertThat(body).contains("a 0.0"); assertThat(body).contains("b 0.0"); assertThat(body).contains("c 0.0"); } finally { httpServer.close(); } } /** * Encodes authorization credentials * * @param username * @param password * @return String */ private final static String encodeCredentials(String username, String password) { // Per RFC4648 table 2. We support Java 6, and java.util.Base64 was only added in Java 8, try { byte[] credentialsBytes = (username + ":" + password).getBytes("UTF-8"); return "Basic " + DatatypeConverter.printBase64Binary(credentialsBytes); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } } /** * Create an SSLContext * * @param sslContextType * @param keyStoreType * @param keyStorePath * @param keyStorePassword * @return SSLContext * @throws GeneralSecurityException * @throws IOException */ private final static SSLContext createSSLContext(String sslContextType, String keyStoreType, String keyStorePath, String keyStorePassword) throws GeneralSecurityException, IOException { SSLContext sslContext = null; FileInputStream fileInputStream = null; try { File file = new File(keyStorePath); if ((file.exists() == false) || (file.isFile() == false) || (file.canRead() == false)) { throw new IllegalArgumentException("cannot read 'keyStorePath', path = [" + file.getAbsolutePath() + "]"); } fileInputStream = new FileInputStream(keyStorePath); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(fileInputStream, keyStorePassword.toCharArray()); KeyManagerFactory keyManagerFactor = KeyManagerFactory.getInstance("SunX509"); keyManagerFactor.init(keyStore, keyStorePassword.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509"); trustManagerFactory.init(keyStore); sslContext = SSLContext.getInstance(sslContextType); sslContext.init(keyManagerFactor.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { // IGNORE } } } return sslContext; } /** * Creates an Authenticator * * @param realm * @param validUsername * @param validPassword * @return Authenticator */ private final static Authenticator createAuthenticator(String realm, final String validUsername, final String validPassword) { return new BasicAuthenticator(realm) { @Override public boolean checkCredentials(String username, String password) { return validUsername.equals(username) && validPassword.equals(password); } }; } /** * Creates an HttpsConfiguration * * @param sslContext * @return HttpsConfigurator */ private static HttpsConfigurator createHttpsConfigurator(SSLContext sslContext) { return new HttpsConfigurator(sslContext) { @Override public void configure(HttpsParameters params) { try { SSLContext c = getSSLContext(); SSLEngine engine = c.createSSLEngine(); params.setNeedClientAuth(false); params.setCipherSuites(engine.getEnabledCipherSuites()); params.setProtocols(engine.getEnabledProtocols()); SSLParameters sslParameters = c.getSupportedSSLParameters(); params.setSSLParameters(sslParameters); } catch (Exception e) { throw new RuntimeException("Exception creating HttpsConfigurator", e); } } }; } }
{ "content_hash": "5155a92ae9e0cd9878a859353affd5e4", "timestamp": "", "source": "github", "line_count": 610, "max_line_length": 140, "avg_line_length": 34.131147540983605, "alnum_prop": 0.6679154658981749, "repo_name": "prometheus/client_java", "id": "2b18f4e829c4c65de610cdf23149e52c8410bb50", "size": "20820", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "simpleclient_httpserver/src/test/java/io/prometheus/client/exporter/TestHTTPServer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "91" }, { "name": "Java", "bytes": "770031" } ], "symlink_target": "" }
class FileSystem { public: FileSystem(); private: };
{ "content_hash": "30089a5ddd8dc55bc6016f5fa23397b0", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 17, "avg_line_length": 8.285714285714286, "alnum_prop": 0.6551724137931034, "repo_name": "paulsapps/7-Gears", "id": "1178be22b708fea1707fc626cbaac102ac1f9de4", "size": "91", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "inc/kernel/filesystem.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "136" }, { "name": "C", "bytes": "2714255" }, { "name": "C++", "bytes": "41374" }, { "name": "CMake", "bytes": "14700" }, { "name": "CSS", "bytes": "2855" }, { "name": "Gnuplot", "bytes": "630" }, { "name": "HTML", "bytes": "258024" }, { "name": "Makefile", "bytes": "31376" }, { "name": "Perl", "bytes": "36275" }, { "name": "Python", "bytes": "1140" }, { "name": "Shell", "bytes": "22416" } ], "symlink_target": "" }
<?php /* Safe sample input : get the $_GET['userData'] in an array sanitize : cast into int construction : use of sprintf via a %u */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $array = array(); $array[] = 'safe' ; $array[] = $_GET['userData'] ; $array[] = 'safe' ; $tainted = $array[1] ; $tainted = (int) $tainted ; $query = sprintf("SELECT * FROM COURSE c WHERE c.id IN (SELECT idcourse FROM REGISTRATION WHERE idstudent=%u)", $tainted); $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password) mysql_select_db('dbname') ; echo "query : ". $query ."<br /><br />" ; $res = mysql_query($query); //execution while($data =mysql_fetch_array($res)){ print_r($data) ; echo "<br />" ; } mysql_close($conn); ?>
{ "content_hash": "d7347ba829379da0ff081335873417b3", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 123, "avg_line_length": 24.567164179104477, "alnum_prop": 0.7253948967193196, "repo_name": "stivalet/PHP-Vulnerability-test-suite", "id": "ca17b2bbce6bc4fd5210bc01cc0fa8a990b58387", "size": "1646", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Injection/CWE_89/safe/CWE_89__array-GET__CAST-cast_int__multiple_select-sprintf_%u.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "64184004" } ], "symlink_target": "" }
var Command = {}; var settings, sessions; Command.dataElements = []; Command.matches = []; Command.lastInputValue = ''; Command.setup = function() { this.bar = document.createElement('div'); this.bar.id = 'cVim-command-bar'; this.bar.cVim = true; this.bar.style[(this.onBottom) ? 'bottom' : 'top'] = '0'; this.input = document.createElement('input'); this.input.type = 'text'; this.input.id = 'cVim-command-bar-input'; this.input.cVim = true; this.statusBar = document.createElement('div'); this.statusBar.id = 'cVim-status-bar'; this.statusBar.style[(this.onBottom) ? 'bottom' : 'top'] = '0'; this.modeIdentifier = document.createElement('span'); this.modeIdentifier.id = 'cVim-command-bar-mode'; this.modeIdentifier.cVim = true; this.bar.appendChild(this.modeIdentifier); this.bar.appendChild(this.input); this.bar.spellcheck = false; // this.input.addEventListener('blur', function() { // Possible fix for #43 // window.setTimeout(function() { // Command.hide.call(Command); // }, 0); // }); try { document.lastChild.appendChild(this.bar); document.lastChild.appendChild(this.statusBar); } catch(e) { document.body.appendChild(this.bar); document.body.appendChild(this.statusBar); } if (!this.data) { this.data = document.createElement('div'); this.data.id = 'cVim-command-bar-search-results'; this.data.cVim = true; try { document.lastChild.appendChild(this.data); } catch(e) { document.body.appendChild(this.data); } this.barHeight = parseInt(getComputedStyle(this.bar).height, 10); if (this.onBottom) { this.barPaddingTop = 0; this.barPaddingBottom = this.barHeight; this.data.style.bottom = this.barHeight + 'px'; } else { this.barPaddingBottom = 0; this.barPaddingTop = this.barHeight; this.data.style.top = this.barHeight + 'px'; } } }; Command.history = { index: {}, search: [], url: [], action: [], setInfo: function(type, index) { var fail = false; if (index < 0) { index = 0; fail = true; } if (index >= this[type].length) { index = this[type].length; fail = true; } this.index[type] = index; return !fail; }, cycle: function(type, reverse) { if (this[type].length === 0) { return false; } var len = this[type].length, index = this.index[type]; if (index === void 0) { index = len; } var lastIndex = index; index += reverse ? -1 : 1; if (Command.typed && Command.typed.trim()) { while (this.setInfo(type, index)) { if (this[type][index].substring(0, Command.typed.length) === Command.typed) { break; } index += reverse ? -1 : 1; } } if (reverse && !~index) { this.index[type] = lastIndex; return; } Command.hideData(); this.setInfo(type, index); if (this.index[type] !== this[type].length) { Command.input.value = this[type][this.index[type]]; } else { Command.input.value = Command.typed || ''; } } }; Command.completions = {}; Command.completionStyles = { topsites: [ 'Top Site', 'darkcyan' ], history: [ 'History', 'cyan' ], bookmarks: [ 'Bookmark', '#6d85fd' ] }; Command.completionOrder = { engines: 5, topsites: 4, bookmarks: 2, history: 3, getImportance: function(item) { if (!this.hasOwnProperty(item)) { return -1; } return this[item]; } }; Command.updateCompletions = function(useStyles) { this.completionResults = []; this.dataElements = []; this.data.innerHTML = ''; var key, i; var completionKeys = Object.keys(this.completions).sort(function(a, b) { return this.completionOrder.getImportance(b) - this.completionOrder.getImportance(a); }.bind(this)); for (i = 0; i < completionKeys.length; i++) { key = completionKeys[i]; for (var j = 0; j < this.completions[key].length; ++j) { this.completionResults.push([key].concat(this.completions[key][j])); } } for (i = 0; i < this.completionResults.length; ++i) { if (i > settings.searchlimit) { break; } var item = document.createElement('div'); item.className = 'cVim-completion-item'; var identifier; if (useStyles && this.completionStyles.hasOwnProperty(this.completionResults[i][0])) { var styles = this.completionStyles[this.completionResults[i][0]]; identifier = document.createElement('span'); identifier.style.color = styles[1]; identifier.textContent = styles[0] + ': '; } if (this.completionResults[i].length >= 3) { var left = document.createElement('span'); left.className = 'cVim-left'; left.textContent = decodeHTMLEntities(this.completionResults[i][1]); var right = document.createElement('span'); right.className = 'cVim-right'; right.textContent = decodeHTMLEntities(this.completionResults[i][2]); if (identifier) { left.insertBefore(identifier, left.firstChild); } item.appendChild(left); item.appendChild(right); } else { var full = document.createElement('span'); full.className = 'cVim-full'; full.textContent = decodeHTMLEntities(this.completionResults[i][1]); item.appendChild(full); } this.dataElements.push(item); this.data.appendChild(item); } if (!this.active || !commandMode) { this.hideData(); } else { this.data.style.display = 'block'; } }; Command.hideData = function() { this.completions = {}; Search.lastActive = null; this.dataElements.length = 0; if (this.data) { this.data.innerHTML = ''; Search.index = null; } }; Command.descriptions = [ ['open', 'Open a link in the current tab'], ['tabnew', 'Open a link in a new tab'], ['tabnext', 'Switch to the next open tab'], ['tabprevious', 'Switch to the previous open tab'], ['new', 'Open a link in a new window'], ['buffer', 'Select from a list of current tabs'], ['history', 'Search through your browser history'], ['bookmarks', 'Search through your bookmarks'], ['file', 'Browse local directories'], ['set', 'Configure Settings'], ['tabhistory', 'Open a tab from its history states'], ['execute', 'Execute a sequence of keys'], ['session', 'Open a saved session in a new window'], ['restore', 'Open a recently closed tab'], ['mksession', 'Create a saved session of current tabs'], ['delsession', 'Delete sessions'], ['map', 'Map a command'], ['unmap', 'Unmap a command'], ['tabattach', 'Move current tab to another window'], ['tabdetach', 'Move current tab to a new window'], ['chrome://', 'Opens Chrome urls'], ['duplicate', 'Clone the current tab'], ['settings', 'Open the options page for this extension'], ['help', 'Shows the help page'], ['changelog', 'Shows the changelog page'], ['quit', 'Close the current tab'], ['qall', 'Close the current window'], ['stop', 'Stop the current page from loading'], ['stopall', 'Stop all pages in Chrome from loading'], ['undo', 'Reopen the last closed tab'], ['togglepin', 'Toggle the tab\'s pinned state'], ['nohlsearch', 'Clears the search highlight'], ['viewsource', 'View the source for the current document'], ['script', 'Run JavaScript on the current page'] ]; Command.deleteCompletions = function(completions) { completions = completions.split(','); for (var i = 0, l = completions.length; i < l; ++i) { this.completions[completions[i]] = []; } }; Command.complete = function(value) { Search.index = null; this.typed = this.input.value; value = value.replace(/(^[^\s&!*]+)[&!*]*/, '$1'); var search = value.replace(/^(chrome:\/\/|\S+ +)/, ''); if (/^(tabnew|tabedit|tabe|tabopen|to|open|o|wo|new|winopen)(\s+)/.test(value)) { this.deleteCompletions('engines,bookmarks,complete,chrome,search'); search = search.split(/ +/).compress(); if ((search.length < 2 || !~Complete.engines.indexOf(search[0])) && !Complete.hasAlias(search[0]) || (Complete.hasAlias(search[0]) && value.slice(-1) !== ' ' && search.length < 2)) { if (~Complete.engines.indexOf(search[0])) { this.hideData(); return; } this.completions.engines = []; for (var i = 0, l = Complete.engines.length; i < l; ++i) { if (!search[0] || Complete.engines[i].indexOf(search.join(' ')) === 0) { this.completions.engines.push([Complete.engines[i], Complete.requestUrls[Complete.engines[i]]]); } } this.updateCompletions(true); this.completions.topsites = Search.topSites.filter(function(e) { return ~(e[0] + ' ' + e[1]).toLowerCase().indexOf(search.slice(0).join(' ').toLowerCase()); }).slice(0, 5).map(function(e) { return [e[0], e[1]]; }); this.updateCompletions(true); if (search.length) { Marks.match(search.join(' '), function(response) { this.completions.bookmarks = response; this.updateCompletions(true); }.bind(this), 2); } this.historyMode = false; this.searchMode = true; PORT('searchHistory', {search: value.replace(/^\S+\s+/, ''), limit: settings.searchlimit}); return; } if (search[0] = (Complete.getAlias(search[0]) || search[0])) { if (search.length < 2) { this.hideData(); return; } } if (~Complete.engines.indexOf(search[0]) && Complete.hasOwnProperty(search[0])) { Complete[search[0]](search.slice(1).join(' '), function(response) { this.completions = { search: response }; this.updateCompletions(); }.bind(this)); } return; } if (/^chrome:\/\//.test(value)) { Search.chromeMatch(search, function(matches) { this.completions = { chrome: matches }; this.updateCompletions(); }.bind(this)); return; } if (/^tabhistory +/.test(value)) { RUNTIME('getHistoryStates', null, function(response) { this.completions = { tabhistory: searchArray(response.links, value.replace(/\S+\s+/, ''), settings.searchlimit, true) }; this.updateCompletions(); }.bind(this)); return; } if (/^taba(ttach)? +/.test(value)) { RUNTIME('getWindows'); this.completions = { }; return; } if (/^buffer(\s+)/.test(value)) { PORT('getBuffers'); return; } if (/^restore\s+/.test(value)) { RUNTIME('getChromeSessions', null, function(sessions) { this.completions = { chromesessions: Object.keys(sessions).map(function(e) { return [sessions[e].id + ': ' + sessions[e].title, sessions[e].url, sessions[e].id]; }).filter(function(e) { return ~e.join('').toLowerCase().indexOf(value.replace(/^\S+\s+/, '').toLowerCase()); }) }; this.updateCompletions(); }.bind(this)); return; } if (/^(del)?session(\s+)/.test(value)) { this.completions = { sessions: sessions.filter(function(e) { var regexp; var isValidRegex = true; try { regexp = new RegExp(search, 'i'); } catch (ex) { isValidRegex = false; } if (isValidRegex) { return regexp.test(e[0]); } return e[0].substring(0, search.length) === search; }) }; this.updateCompletions(); return; } if (/^set(\s+)/.test(value)) { Search.settingsMatch(search, function(matches) { this.completions = {settings: matches}; this.updateCompletions(); }.bind(this)); return; } if (/^hist(ory)?(\s+)/.test(value)) { if (search.trim() === '') { this.hideData(); return; } this.historyMode = true; PORT('searchHistory', {search: search, limit: settings.searchlimit}); return; } if (/^file +/.test(value)) { Marks.parseFileCommand(search); return; } if (/^b(ook)?marks(\s+)/.test(value)) { this.completions = {}; if (search[0] === '/') { return Marks.matchPath(search); } Marks.match(search, function(response) { this.completions.bookmarks = response; this.updateCompletions(); }.bind(this)); return; } this.completions = { complete: this.descriptions.filter(function(element) { return value === element[0].slice(0, value.length); }) }; this.updateCompletions(); }; Command.execute = function(value, repeats) { // Match commands like ':tabnew*&! search' before commands like ':tabnew search&*!' // e.g. :tabnew& google asdf* => opens a new pinned tab // ! == whether to open in a new tab or not // & == whether the tab will be active // * == whether the tab will be pinned var tab = { active: value === (value = value.replace(/(^[^\s&]+)&([*!]*)/, '$1$2')), pinned: value !== (value = value.replace(/(^[^\s*]+)\*([!]*)/, '$1$2')), tabbed: value !== (value = value.replace(/(^[^\s!]+)!/, '$1')) }; var glob = { active: value === (value = value.replace(/&([*!]*)$/, '$1')), pinned: value !== (value = value.replace(/\*([!]*)$/, '$1')), tabbed: value !== (value = value.replace(/!$/, '')) }; tab.active = tab.active && glob.active; tab.pinned = tab.pinned || glob.pinned; tab.tabbed = tab.tabbed || glob.tabbed; if (!tab.active && !tab.tabbed) { tab.tabbed = true; } this.history.index = {}; switch (value) { case 'nohlsearch': case 'nohl': Find.clear(); HUD.hide(); return; case 'duplicate': RUNTIME('duplicateTab', {repeats: repeats}); return; case 'settings': tab.tabbed = true; RUNTIME('openLink', { tab: tab, url: chrome.extension.getURL('/pages/options.html'), repeats: repeats }); return; case 'changelog': tab.tabbed = true; RUNTIME('openLink', { tab: tab, url: chrome.extension.getURL('/pages/changelog.html'), repeats: repeats }); return; case 'help': tab.tabbed = true; RUNTIME('openLink', {tab: tab, url: chrome.extension.getURL('/pages/mappings.html')}); return; case 'stop': window.stop(); return; case 'stopall': RUNTIME('cancelAllWebRequests'); return; case 'viewsource': RUNTIME('openLink', {tab: tab, url: 'view-source:' + document.URL, noconvert: true}); return; case 'pintab': RUNTIME('pinTab', {pinned: true}); break; case 'unpintab': RUNTIME('pinTab', {pinned: false}); break; case 'togglepin': RUNTIME('pinTab'); return; case 'undo': RUNTIME('openLast'); return; case 'tabnext': case 'tabn': RUNTIME('nextTab'); return; case 'tabprevious': case 'tabp': case 'tabN': RUNTIME('previousTab'); return; case 'tabprevious': return; case 'q': case 'quit': case 'exit': RUNTIME('closeTab', {repeats: repeats}); return; case 'qa': case 'qall': RUNTIME('closeWindow'); return; } if (/^chrome:\/\/\S+$/.test(value)) { RUNTIME('openLink', { tab: tab, url: value, noconvert: true }); return; } if (/^bookmarks +/.test(value) && !/^\S+\s*$/.test(value)) { if (/^\S+\s+\//.test(value)) { RUNTIME('openBookmarkFolder', { path: value.replace(/\S+\s+/, ''), noconvert: true }); return; } if (this.completionResults.length && !this.completionResults.some(function(e) { return e[2] === value.replace(/^\S+\s*/, ''); })) { RUNTIME('openLink', { tab: tab, url: this.completionResults[0][2], noconvert: true }); return; } RUNTIME('openLink', { tab: tab, url: value.replace(/^\S+\s+/, ''), noconvert: true }); return; } if (/^history +/.test(value) && !/^\S+\s*$/.test(value)) { RUNTIME('openLink', { tab: tab, url: Complete.convertToLink(value), noconvert: true }); return; } if (/^taba(ttach)? +/.test(value) && !/^\S+\s*$/.test(value)) { var windowId; if (windowId = this.completionResults[parseInt(value.replace(/^\S+ */, ''), 10)]) { RUNTIME('moveTab', { windowId: windowId[3] }); return; } } if (/^tabd(etach)?/.test(value)) { RUNTIME('moveTab'); return; } if (/^file +/.test(value)) { RUNTIME('openLink', { tab: tab, url: 'file://' + value.replace(/\S+ +/, '').replace(/^~/, settings.homedirectory), noconvert: true }); return; } if (/^(new|winopen|wo)$/.test(value.replace(/ .*/, '')) && !/^\S+\s*$/.test(value)) { RUNTIME('openLinkWindow', { tab: tab, url: Complete.convertToLink(value), repeats: repeats, noconvert: true }); return; } if (/^restore\s+/.test(value)) { RUNTIME('restoreChromeSession', { sessionId: value.replace(/\S+\s+/, '').trimAround() }); } if (/^(tabnew|tabedit|tabe|to|tabopen|tabhistory)$/.test(value.replace(/ .*/, ''))) { tab.tabbed = true; RUNTIME('openLink', { tab: tab, url: Complete.convertToLink(value), repeats: repeats, noconvert: true }); return; } if (/^(o|open)$/.test(value.replace(/ .*/, '')) && !/^\S+\s*$/.test(value)) { RUNTIME('openLink', { tab: tab, url: Complete.convertToLink(value), noconvert: true }); return; } if (/^buffer +/.test(value)) { var index = +value.replace(/^\S+\s+/, ''), selectedBuffer; if (Number.isNaN(index)) { selectedBuffer = Command.completionResults[0]; if (selectedBuffer === void 0) { return; } } else { selectedBuffer = Command.completionResults.filter(function(e) { return e[1].indexOf(index.toString()) === 0; })[0]; } if (selectedBuffer !== void 0) { RUNTIME('goToTab', {id: selectedBuffer[3]}); } else if (Command.completionResults.length) { RUNTIME('goToTab', {id: Command.completionResults[0][3]}); } return; } if (/^execute +/.test(value)) { var command = value.replace(/^\S+/, '').trim(); realKeys = ''; repeats = ''; Command.hide(); Mappings.executeSequence(command); return; } if (/^delsession/.test(value)) { value = value.replace(/^\S+(\s+)?/, '').trimAround(); if (value === '') { Status.setMessage('argument required', 1, 'error'); return; } if (~sessions.indexOf(value)) { sessions.splice(sessions.indexOf(value), 1); } value.split(' ').forEach(function(v) { RUNTIME('deleteSession', {name: v}); }); PORT('getSessionNames'); return; } if (/^mksession/.test(value)) { value = value.replace(/^\S+(\s+)?/, '').trimAround(); if (value === '') { Status.setMessage('session name required', 1, 'error'); return; } if (/[^a-zA-Z0-9_-]/.test(value)) { Status.setMessage('only alphanumeric characters, dashes, and underscores are allowed', 1, 'error'); return; } if (!~sessions.indexOf(value)) { sessions.push(value); } RUNTIME('createSession', {name: value}); return; } if (/^session/.test(value)) { value = value.replace(/^\S+(\s+)?/, '').trimAround(); if (value === '') { Status.setMessage('session name required', 1, 'error'); return; } RUNTIME('openSession', {name: value, sameWindow: !tab.active}, function() { Status.setMessage('session does not exist', 1, 'error'); }); return; } if (/^((i?(re)?map)|i?unmap(All)?)+/.test(value)) { Mappings.parseLine(value); return; } if (/^set +/.test(value) && value !== 'set') { value = value.replace(/^set +/, '').split(/[ =]+/); var isSet, swapVal, isQuery = /\?$/.test(value[0]); value[0] = value[0].replace(/\?$/, ''); if (!settings.hasOwnProperty(value[0].replace(/^no|!$/g, ''))) { Status.setMessage('unknown option: ' + value[0], 1, 'error'); return; } if (isQuery) { Status.setMessage(value + ': ' + settings[value[0]], 1); return; } isSet = !/^no/.test(value[0]); swapVal = tab.tabbed; value[0] = value[0].replace(/^no|\?$/g, ''); if (value.length === 1 && Boolean(settings[value]) === settings[value]) { if (value[0] === 'hud' && !isSet) { HUD.hide(true); } if (swapVal) { settings[value[0]] = !settings[value[0]]; } else { settings[value[0]] = isSet; } RUNTIME('syncSettings', {settings: settings}); } return; } if (/^script +/.test(value)) { RUNTIME('runScript', {code: value.slice(7)}); } }; Command.show = function(search, value) { if (!this.domElementsLoaded) { return; } this.type = ''; this.active = true; if (document.activeElement) { document.activeElement.blur(); } if (search) { this.type = 'search'; this.modeIdentifier.innerHTML = search; } else { this.type = 'action'; this.modeIdentifier.innerHTML = ':'; } if (value) { this.input.value = value; this.typed = value; } if (Status.active) { Status.hide(); } this.bar.style.display = 'inline-block'; setTimeout(function() { this.input.focus(); // Temp fix for Chromium issue in #97 if (document.activeElement.id === 'cVim-command-bar-input') { document.activeElement.select(); document.getSelection().collapseToEnd(); } // End temp fix }.bind(this), 0); }; Command.hide = function(callback) { if (document.activeElement) { document.activeElement.blur(); } this.hideData(); if (this.bar) { this.bar.style.display = 'none'; } if (this.input) { this.input.value = ''; } if (this.data) { this.data.style.display = 'none'; } this.historyMode = false; this.active = false; commandMode = false; Search.index = null; this.history.index = {}; this.typed = ''; this.dataElements = []; if (callback) { callback(); } }; Command.insertCSS = function() { var css = settings.COMMANDBARCSS; if (!css) { return; } if (settings.linkanimations) { css += '.cVim-link-hint { transition: opacity 0.2s ease-out, background 0.2s ease-out; }'; } RUNTIME('injectCSS', {css: css, runAt: 'document_start'}); var head = document.getElementsByTagName('head'); if (head.length) { this.css = document.createElement('style'); this.css.textContent = css; head[0].appendChild(this.css); } }; Command.onDOMLoad = function() { this.insertCSS(); this.onBottom = settings.barposition === 'bottom'; if (this.data !== void 0) { this.data.style[(!this.onBottom) ? 'bottom' : 'top'] = ''; this.data.style[(this.onBottom) ? 'bottom' : 'top'] = '20px'; } if (!settings.autofocus) { var manualFocus = false; var initialFocus = window.setInterval(function() { if (document.activeElement) { if (/input|textarea/i.test(document.activeElement.localName) && !manualFocus && document.activeElement.id !== 'cVim-command-bar-input') { document.activeElement.blur(); } } if (manualFocus) { window.clearInterval(initialFocus); } }, 5); var initialKeyDown = window.addEventListener('keydown', function() { manualFocus = true; document.removeEventListener('keydown', initialKeyDown, true); }, true); var initialMouseDown = document.addEventListener('mousedown', function() { manualFocus = true; document.removeEventListener('mousedown', initialMouseDown, true); }, true); } this.setup(); this.domElementsLoaded = true; }; Command.updateSettings = function(config) { var key; if (Array.isArray(config.completionengines) && config.completionengines.length) { Complete.engines = Complete.engines.filter(function(e) { return ~config.completionengines.indexOf(e); }); } if (config.searchengines && config.searchengines.constructor === Object) { for (key in config.searchengines) { if (!~Complete.engines.indexOf(key) && typeof config.searchengines[key] === 'string') { Complete.engines.push(key); Complete.requestUrls[key] = config.searchengines[key]; } } } if (config.searchaliases && config.searchaliases.constructor === Object) { for (key in config.searchaliases) { if (Complete.engines.indexOf(key)) { Complete.aliases[key] = config.searchaliases[key]; } } } if (config.locale) { Complete.setLocale(config.locale); } if (config.hintcharacters && config.hintcharacters.split('').unique().length > 1) { settings.hintcharacters = config.hintcharacters.split('').unique().join(''); } if (config !== settings) { for (key in config) { if (key.toUpperCase() !== key && settings.hasOwnProperty(key)) { settings[key] = config[key]; } } } }; Command.init = function(enabled) { var key; Mappings.defaults = Object.clone(Mappings.defaultsClone); Mappings.parseCustom(settings.MAPPINGS); if (enabled) { this.loaded = true; this.updateSettings(settings); for (key in settings.sites) { if (matchLocation(document.URL, key)) { PORT('parseRC', {config: settings.sites[key]}); } } waitForLoad(this.onDOMLoad, this); if (settings.autohidecursor) { waitForLoad(Cursor.init, Cursor); } } else { this.loaded = false; if (this.css && this.css.parentNode) { this.css.parentNode.removeChild(this.css); } var links = document.getElementById('cVim-link-container'); if (Cursor.overlay && Cursor.overlay.parentNode) { Cursor.overlay.parentNode.removeChild(Cursor.overlay); } if (this.bar && this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } if (links) { links.parentNode.removeChild(links); } removeListeners(); } }; Command.configureSettings = function(_settings) { settings = _settings; this.initialLoadStarted = true; var checkBlacklist = function() { var blacklists = settings.blacklists, blacklist; Command.blacklisted = false; for (var i = 0, l = blacklists.length; i < l; i++) { blacklist = blacklists[i].trimAround().split(/\s+/g); if (!blacklist.length) { continue; } if (matchLocation(document.URL, blacklist[0])) { return true; } } }; var loadMain = function() { Command.loaded = true; RUNTIME('setIconEnabled'); Command.init(true); }; Search.settings = Object.keys(settings).filter(function(e) { return settings[e].constructor === Boolean; }); removeListeners(); settings.searchlimit = +settings.searchlimit; if (!checkBlacklist()) { RUNTIME('getActiveState', null, function(response) { if (response) { addListeners(); loadMain(); } else { Command.init(false); } }); } else { this.init(false); } }; if (!Command.loaded) { RUNTIME('getSettings'); }
{ "content_hash": "3c596c61ff581a85d4d83208fdc1a883", "timestamp": "", "source": "github", "line_count": 961, "max_line_length": 187, "avg_line_length": 28.329864724245578, "alnum_prop": 0.5812304866850322, "repo_name": "Jayphen/chromium-vim", "id": "b3f367057f4a6f69e97bd4de0fd464ace3531ed6", "size": "27225", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "content_scripts/command.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "29129" }, { "name": "JavaScript", "bytes": "640204" }, { "name": "Python", "bytes": "1446" }, { "name": "Shell", "bytes": "603" } ], "symlink_target": "" }
require 'rubygems' require 'minitest/autorun' require 'minitest/reporters' #require 'active_support' #require 'active_support/test_case' require 'action_controller' #require 'action_view' #require 'action_view/test_case' #require 'test_help' require 'informant' Minitest::Reporters.use! Minitest::Reporters::DefaultReporter.new
{ "content_hash": "df1c1fdc3fe24ad8a234f1374b2f3ba5", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 65, "avg_line_length": 27.416666666666668, "alnum_prop": 0.790273556231003, "repo_name": "alexreisner/informant", "id": "468d263ce6cadba4cd8a3e4313bdcd8d385e2605", "size": "329", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/test_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "14963" } ], "symlink_target": "" }
package cn.intelvision.model; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by pc on 2015/12/10. */ public class Group { private String groupId; private String groupName; private String tag; private long addTime; private String appId; @JsonProperty("group_id") public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } @JsonProperty("group_name") public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } @JsonProperty("add_time") public long getAddTime() { return addTime; } public void setAddTime(long addTime) { this.addTime = addTime; } @JsonProperty("app_id") public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } }
{ "content_hash": "70577cfe7ca296603cccea6bf1caf04c", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 53, "avg_line_length": 18.915254237288135, "alnum_prop": 0.6102150537634409, "repo_name": "zeno-tech/intelvision-sdk-java", "id": "2d22fd5606fb2fe32057381c5e36c2429b17f7fa", "size": "1116", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/cn/intelvision/model/Group.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "159537" } ], "symlink_target": "" }
DIR=$(cd "$(dirname "${BASH_SOURCE-$0}")">/dev/null; pwd) # set S2GRAPH_HOME if [ -z $S2GRAPH_HOME ]; then export S2GRAPH_HOME="$( cd -P "$DIR/.." && pwd )" fi # set other environment variables for directories, relative to $S2GRAPH_HOME # not intended to be individually configurable, # configurations can be added or overridden in conf/application.conf export S2GRAPH_BIN_DIR=$S2GRAPH_HOME/bin export S2GRAPH_LIB_DIR=$S2GRAPH_HOME/lib export S2GRAPH_LOG_DIR=$S2GRAPH_HOME/logs export S2GRAPH_CONF_DIR=$S2GRAPH_HOME/conf export S2GRAPH_HBASE_DIR=$S2GRAPH_HOME/var/hbase export S2GRAPH_METASTORE_DIR=$S2GRAPH_HOME/var/metastore export S2GRAPH_PID_DIR=$S2GRAPH_HOME/var/pid mkdir -p "$S2GRAPH_LOG_DIR" "$S2GRAPH_CONF_DIR" "$S2GRAPH_HBASE_DIR" \ "$S2GRAPH_METASTORE_DIR" "$S2GRAPH_PID_DIR" # apply the minimal JVM settings if none was given; # in production, this variable is expected to be given by a deployment system. if [ -z "$S2GRAPH_OPTS" ]; then export S2GRAPH_OPTS="-Xms1g -Xmx1g" fi # the maximum wait time for a process to finish, before sending SIGKILL if [ -z "$S2GRAPH_STOP_TIMEOUT" ]; then export S2GRAPH_STOP_TIMEOUT=60 # in seconds fi
{ "content_hash": "ec38defd040d22cf1932fdef6b269243", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 78, "avg_line_length": 37.516129032258064, "alnum_prop": 0.7386070507308684, "repo_name": "SteamShon/incubator-s2graph", "id": "66941b742d5e9e61a6d74e9c6f197e41e7c913f0", "size": "2182", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "bin/s2graph-env.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "4776" }, { "name": "Java", "bytes": "15838" }, { "name": "Python", "bytes": "3508" }, { "name": "Scala", "bytes": "1351225" }, { "name": "Shell", "bytes": "26027" } ], "symlink_target": "" }
using Rhino.Security.Model; namespace Rhino.Security.Interfaces { /// <summary> /// Allows to edit the security information of the /// system /// </summary> public interface IAuthorizationRepository { /// <summary> /// Creates a new users group. /// </summary> /// <param name="name">The name of the new group.</param> UsersGroup CreateUsersGroup(string name); /// <summary> /// Creates a new entities group. /// </summary> /// <param name="name">The name of the new group.</param> EntitiesGroup CreateEntitiesGroup(string name); /// <summary> /// Gets the associated users group for the specified user. /// </summary> /// <param name="user">The user.</param> UsersGroup[] GetAssociatedUsersGroupFor(IUser user); /// <summary> /// Gets the users group by its name /// </summary> /// <param name="groupName">Name of the group.</param> UsersGroup GetUsersGroupByName(string groupName); /// <summary> /// Gets the entities group by its name /// </summary> /// <param name="groupName">The name of the group.</param> EntitiesGroup GetEntitiesGroupByName(string groupName); /// <summary> /// Gets the groups the specified entity is associated with /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="entity">The entity.</param> /// <returns></returns> EntitiesGroup[] GetAssociatedEntitiesGroupsFor<TEntity>(TEntity entity) where TEntity : class; /// <summary> /// Associates the entity with a group with the specified name /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="entity">The entity.</param> /// <param name="groupName">Name of the group.</param> void AssociateEntityWith<TEntity>(TEntity entity, string groupName) where TEntity : class; /// <summary> /// Associates the entity with the specified group /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="entity">The entity.</param> /// <param name="group">The group.</param> void AssociateEntityWith<TEntity>(TEntity entity, EntitiesGroup group) where TEntity : class; /// <summary> /// Associates the user with a group with the specified name /// </summary> /// <param name="user">The user.</param> /// <param name="groupName">Name of the group.</param> void AssociateUserWith(IUser user, string groupName); /// <summary> /// Associates the user with a group with the specified name /// </summary> /// <param name="user">The user.</param> /// <param name="group">The group.</param> void AssociateUserWith(IUser user, UsersGroup group); /// <summary> /// Creates the operation with the given name /// </summary> /// <param name="operationName">Name of the operation.</param> /// <returns></returns> Operation CreateOperation(string operationName); /// <summary> /// Gets the operation by the specified name /// </summary> /// <param name="operationName">Name of the operation.</param> /// <returns></returns> Operation GetOperationByName(string operationName); /// <summary> /// Removes the user from the specified group /// </summary> /// <param name="user">The user.</param> /// <param name="usersGroupName">Name of the users group.</param> void DetachUserFromGroup(IUser user, string usersGroupName); /// <summary> /// Removes the entities from the specified group /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="entity">The entity.</param> /// <param name="entitiesGroupName">Name of the entities group.</param> void DetachEntityFromGroup<TEntity>(TEntity entity, string entitiesGroupName) where TEntity : class; /// <summary> /// Creates the users group as a child of <paramref name="parentGroupName"/>. /// </summary> /// <param name="parentGroupName">Name of the parent group.</param> /// <param name="usersGroupName">Name of the users group.</param> /// <returns></returns> UsersGroup CreateChildUserGroupOf(string parentGroupName, string usersGroupName); /// <summary> /// Gets the ancestry association of a user with the named users group. /// This allows to track how a user is associated to a group through /// their ancestry. /// </summary> /// <param name="user">The user.</param> /// <param name="usersGroupName">Name of the users group.</param> /// <returns></returns> UsersGroup[] GetAncestryAssociation(IUser user, string usersGroupName); /// <summary> /// Removes the specified users group. /// Cannot remove parent users groups, you must remove them first. /// Will also delete all permissions that are related to this group. /// </summary> /// <param name="usersGroupName">Name of the users group.</param> void RemoveUsersGroup(string usersGroupName); /// <summary> /// Removes the specified entities group. /// Will also delete all permissions that are associated with this group. /// </summary> /// <param name="entitesGroupName">Name of the entites group.</param> void RemoveEntitiesGroup(string entitesGroupName); /// <summary> /// Removes the specified operation. /// Will also delete all permissions for this operation /// </summary> /// <param name="operationName">The operation N ame.</param> void RemoveOperation(string operationName); /// <summary> /// Removes the user from rhino security. /// This does NOT delete the user itself, merely reset all the /// information that rhino security knows about it. /// It also allows it to be removed by external API without violating /// FK constraints /// </summary> /// <param name="user">The user.</param> void RemoveUser(IUser user); /// <summary> /// Removes the specified permission. /// </summary> /// <param name="permission">The permission.</param> void RemovePermission(Permission permission); } }
{ "content_hash": "d696d8ad16c22fd3e3b80d95cb923d21", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 96, "avg_line_length": 36.05917159763314, "alnum_prop": 0.6652445027896291, "repo_name": "brumschlag/rhino-tools", "id": "12470e2663f48a6cd100ee90edd42d935809e415", "size": "6094", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rhino-security/Rhino.Security/Interfaces/IAuthorizationRepository.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "7340" }, { "name": "Boo", "bytes": "210167" }, { "name": "C#", "bytes": "4487411" }, { "name": "C++", "bytes": "2173" }, { "name": "Visual Basic", "bytes": "41378" } ], "symlink_target": "" }
package com.esafirm.androidplayground.ui.nestedscroll; import android.content.Context; import com.google.android.material.appbar.AppBarLayout; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.core.view.ViewCompat; import android.util.AttributeSet; import android.view.View; public class FixAppBarLayoutBehavior extends AppBarLayout.Behavior { public FixAppBarLayoutBehavior() { super(); } public FixAppBarLayoutBehavior(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void onNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) { super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type); stopNestedScrollIfNeeded(dyUnconsumed, child, target, type); } @Override public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed, int type) { super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type); stopNestedScrollIfNeeded(dy, child, target, type); } private void stopNestedScrollIfNeeded(int dy, AppBarLayout child, View target, int type) { if (type == ViewCompat.TYPE_NON_TOUCH) { final int currOffset = getTopAndBottomOffset(); if ((dy < 0 && currOffset == 0) || (dy > 0 && currOffset == -child.getTotalScrollRange())) { ViewCompat.stopNestedScroll(target, ViewCompat.TYPE_NON_TOUCH); } } } }
{ "content_hash": "e12a315bd9246876291248bf5cc6b555", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 110, "avg_line_length": 40, "alnum_prop": 0.6886363636363636, "repo_name": "esafirm/android-playground", "id": "1cc7741084711450e4b8b1ac5bbed8d4ddc86bd2", "size": "1760", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "app/src/main/java/com/esafirm/androidplayground/ui/nestedscroll/FixAppBarLayoutBehavior.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "46299" }, { "name": "JavaScript", "bytes": "514" }, { "name": "Kotlin", "bytes": "252867" }, { "name": "Ruby", "bytes": "745" } ], "symlink_target": "" }
import {Component} from '@angular/core'; import {IIndicatorInfo} from '../../../app.interfaces'; import {IndicatorService} from '../../../services/indicator.service'; @Component({ moduleId: __filename, selector: 'procurement-integrity', templateUrl: 'procurement-integrity.component.html' }) export class DashboardsIntegrityPage { public indicator: IIndicatorInfo; public columnIds = ['id', 'title', 'buyers.name', 'lots.bids.bidders.name', 'indicators.pii']; constructor(indicators: IndicatorService) { this.indicator = indicators.INTEGRITY; } }
{ "content_hash": "110b1a56cf5478f6ea7dc7245d4dd752", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 95, "avg_line_length": 32.8235294117647, "alnum_prop": 0.7347670250896058, "repo_name": "digiwhist/opentender-frontend", "id": "c50785962848c5336e18d2ea2c3efb2f4992046a", "size": "558", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/pages/dashboards/procurement-integrity/procurement-integrity.component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "124137" }, { "name": "HTML", "bytes": "121051" }, { "name": "JavaScript", "bytes": "36012" }, { "name": "TypeScript", "bytes": "368837" } ], "symlink_target": "" }
from . import mymodule def f(): return mymodule.add(1, 2)
{ "content_hash": "43ea35c3c709f8e7545b3389231e8db1", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 29, "avg_line_length": 12.8, "alnum_prop": 0.640625, "repo_name": "tbenthompson/cppimport", "id": "bd4c9cbd3a3fe66c2a07e2ee8b868d4f061134b6", "size": "64", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "tests/apackage/rel_import_tester.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "960" }, { "name": "C++", "bytes": "2107" }, { "name": "Python", "bytes": "33555" } ], "symlink_target": "" }
var fs = require('fs'); var path = require('path'); var RELATIVE = global.__base = path.resolve(__dirname, path.join('..', 'npm-analytics')); var NODE_MODULES = path.resolve(__dirname, path.join('..', 'npm-analytics', 'node_modules')); var BASE_DIR = path.resolve(__dirname, path.join('..', '..')); var BASE_DIR_NODE_MODULES = path.resolve(BASE_DIR, 'node_modules'); require.main.paths.unshift(NODE_MODULES); var getVersions = require(RELATIVE + '/lib/getVersions'); // the following will ensure that the analytics will be only // performed on the last call if( path.resolve(process.cwd(), path.join('..', '..')) == BASE_DIR ) { var info = {}; var packageJSON = JSON.parse(fs.readFileSync(path.join(BASE_DIR, 'package.json'), 'utf8')); var npmArgv = JSON.parse(process.env.npm_config_argv); var deps = []; var devDeps = []; if(packageJSON.dependencies) { deps = deps.concat(Object.keys(packageJSON.dependencies)); } if(packageJSON.devDependencies) { devDeps = devDeps.concat(Object.keys(packageJSON.devDependencies)); } // since package.json is not updated til after this script we'll check the arguments that were used to run npm install // It might look something like this: // process.env.npm_config_argv == '{"remain":["gsap"],"cooked":["i","gsap","--save"],"original":["i","gsap","--save"]}', // a new module was installed remain contains modules being currently installed if(npmArgv.remain.length > 0) { // if this was called through npm i something --save if(npmArgv.original.indexOf('--save') > -1) { deps = deps.concat(npmArgv.remain); fillInInfo(); } else if(npmArgv.original.indexOf('--save-dev') > -1) { devDeps = devDeps.concat(npmArgv.remain); fillInInfo(); } } else { fillInInfo(); } } function fillInInfo() { info.initAuthor = process.env.npm_config_init_author_github; info.time = (new Date()).toString(); info.initiators = npmArgv.remain.slice(); info.module = { name: packageJSON.name, version: packageJSON.version, description: packageJSON.description, license: packageJSON.license, author: packageJSON.author, keywords: packageJSON.keywords, repository: packageJSON.repository, homepage: packageJSON.homepage }; return getVersions(deps) .then(function(dependencies) { info.module.dependencies = dependencies; return getVersions(devDeps); }) .then(function(devDependencies) { info.module.devDependencies = devDependencies; }) .then(function() { console.log(info); }); }
{ "content_hash": "155ae7cb106a3c2bad4e65198eedf805", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 121, "avg_line_length": 27.217391304347824, "alnum_prop": 0.6888977635782748, "repo_name": "MikkoH/npm-analytics", "id": "887a4adc11daa76a2cead0048e89a4e2021dc51f", "size": "2525", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "analytics.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3894" } ], "symlink_target": "" }
\documentclass[a4Paper, 10pt]{article} \usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage{hyperref} %opening \title{Sviluppi decimali} \author{\href{http://www.baudo.hol.es}{giuseppe baudo}} \begin{document} \maketitle \section{DEFINIZIONE} \end{document}
{ "content_hash": "f716fcc7f7a5c532b3ed48414aa1de74", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 55, "avg_line_length": 16.166666666666668, "alnum_prop": 0.711340206185567, "repo_name": "baudo2048/mathematics", "id": "37f1f20d165ac6c528a40f95214a938b25d2447a", "size": "291", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "latex/concetti/SviluppiDecimali.tex", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1122" }, { "name": "CSS", "bytes": "500" }, { "name": "Java", "bytes": "8956" }, { "name": "M", "bytes": "249" }, { "name": "Matlab", "bytes": "330" }, { "name": "PowerShell", "bytes": "15" }, { "name": "Shell", "bytes": "1820" }, { "name": "TeX", "bytes": "1507597" } ], "symlink_target": "" }
import { Component, Input, Output, OnInit, ViewChild, ChangeDetectionStrategy, ChangeDetectorRef, EventEmitter, OnChanges, SimpleChanges, Inject } from "@angular/core"; import { Router } from "@angular/router"; import { forkJoin } from "rxjs"; import { finalize } from "rxjs/operators"; import { TranslateService } from "@ngx-translate/core"; import { Comparator, State } from "../service/interface"; import { Repository, SystemInfo, SystemInfoService, RepositoryService, RequestQueryParams, RepositoryItem, TagService } from '../service/index'; import { ErrorHandler } from '../error-handler/error-handler'; import { CustomComparator, DEFAULT_PAGE_SIZE, calculatePage, doFiltering, doSorting, clone } from '../utils'; import { ConfirmationState, ConfirmationTargets, ConfirmationButtons } from '../shared/shared.const'; import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component'; import { ConfirmationMessage } from '../confirmation-dialog/confirmation-message'; import { ConfirmationAcknowledgement } from '../confirmation-dialog/confirmation-state-message'; import { Tag } from '../service/interface'; import { GridViewComponent } from '../gridview/grid-view.component'; import { OperationService } from "../operation/operation.service"; import { UserPermissionService } from "../service/permission.service"; import { USERSTATICPERMISSION } from "../service/permission-static"; import { OperateInfo, OperationState, operateChanges } from "../operation/operate"; import { SERVICE_CONFIG, IServiceConfig } from '../service.config'; import { map, catchError } from "rxjs/operators"; import { Observable, throwError as observableThrowError } from "rxjs"; import { errorHandler as errorHandFn } from "../shared/shared.utils"; @Component({ selector: "hbr-repository-gridview", templateUrl: "./repository-gridview.component.html", styleUrls: ["./repository-gridview.component.scss"], changeDetection: ChangeDetectionStrategy.OnPush }) export class RepositoryGridviewComponent implements OnChanges, OnInit { signedCon: { [key: string]: any | string[] } = {}; downloadLink: string; @Input() projectId: number; @Input() projectName = "unknown"; @Input() urlPrefix: string; @Input() hasSignedIn: boolean; @Input() hasProjectAdminRole: boolean; @Input() mode = "admiral"; @Output() repoClickEvent = new EventEmitter<RepositoryItem>(); @Output() repoProvisionEvent = new EventEmitter<RepositoryItem>(); @Output() addInfoEvent = new EventEmitter<RepositoryItem>(); lastFilteredRepoName: string; repositories: RepositoryItem[] = []; repositoriesCopy: RepositoryItem[] = []; systemInfo: SystemInfo; selectedRow: RepositoryItem[] = []; loading = true; isCardView: boolean; cardHover = false; listHover = false; pullCountComparator: Comparator<RepositoryItem> = new CustomComparator<RepositoryItem>('pull_count', 'number'); tagsCountComparator: Comparator<RepositoryItem> = new CustomComparator<RepositoryItem>('tags_count', 'number'); pageSize: number = DEFAULT_PAGE_SIZE; currentPage = 1; totalCount = 0; currentState: State; @ViewChild("confirmationDialog") confirmationDialog: ConfirmationDialogComponent; @ViewChild("gridView") gridView: GridViewComponent; hasCreateRepositoryPermission: boolean; hasDeleteRepositoryPermission: boolean; constructor(@Inject(SERVICE_CONFIG) private configInfo: IServiceConfig, private errorHandler: ErrorHandler, private translateService: TranslateService, private repositoryService: RepositoryService, private systemInfoService: SystemInfoService, private tagService: TagService, private operationService: OperationService, public userPermissionService: UserPermissionService, private ref: ChangeDetectorRef, private router: Router) { if (this.configInfo && this.configInfo.systemInfoEndpoint) { this.downloadLink = this.configInfo.systemInfoEndpoint + "/getcert"; } } public get registryUrl(): string { return this.systemInfo ? this.systemInfo.registry_url : ""; } public get withClair(): boolean { return this.systemInfo ? this.systemInfo.with_clair : false; } public get isClairDBReady(): boolean { return ( this.systemInfo && this.systemInfo.clair_vulnerability_status && this.systemInfo.clair_vulnerability_status.overall_last_update > 0 ); } public get withAdmiral(): boolean { return this.mode === "admiral"; } public get showDBStatusWarning(): boolean { return this.withClair && !this.isClairDBReady; } get canDownloadCert(): boolean { return this.systemInfo && this.systemInfo.has_ca_root; } ngOnChanges(changes: SimpleChanges): void { if (changes["projectId"] && changes["projectId"].currentValue) { this.refresh(); } } ngOnInit(): void { // Get system info for tag views this.systemInfoService.getSystemInfo() .subscribe(systemInfo => (this.systemInfo = systemInfo) , error => this.errorHandler.error(error)); if (this.mode === "admiral") { this.isCardView = true; } else { this.isCardView = false; } this.lastFilteredRepoName = ""; this.getHelmChartVersionPermission(this.projectId); } confirmDeletion(message: ConfirmationAcknowledgement) { let repArr: any[] = []; message.data.forEach(repo => { if (!this.signedCon[repo.name]) { repArr.push(this.getTagInfo(repo.name)); } }); this.loading = true; forkJoin(...repArr).subscribe(() => { if (message && message.source === ConfirmationTargets.REPOSITORY && message.state === ConfirmationState.CONFIRMED) { let repoLists = message.data; if (repoLists && repoLists.length) { let observableLists: any[] = []; repoLists.forEach(repo => { observableLists.push(this.delOperate(repo)); }); forkJoin(observableLists).subscribe((item) => { this.selectedRow = []; this.refresh(); let st: State = this.getStateAfterDeletion(); if (!st) { this.refresh(); } else { this.clrLoad(st); } }, error => { this.errorHandler.error(error); this.loading = false; }); } } }, error => { this.errorHandler.error(error); this.loading = false; }); } delOperate(repo: RepositoryItem): Observable<any> { // init operation info let operMessage = new OperateInfo(); operMessage.name = 'OPERATION.DELETE_REPO'; operMessage.data.id = repo.id; operMessage.state = OperationState.progressing; operMessage.data.name = repo.name; this.operationService.publishInfo(operMessage); if (this.signedCon[repo.name].length !== 0) { return forkJoin(this.translateService.get('BATCH.DELETED_FAILURE'), this.translateService.get('REPOSITORY.DELETION_TITLE_REPO_SIGNED')).pipe(map(res => { operateChanges(operMessage, OperationState.failure, res[1]); })); } else { return this.repositoryService .deleteRepository(repo.name) .pipe(map( response => { this.translateService.get('BATCH.DELETED_SUCCESS').subscribe(res => { operateChanges(operMessage, OperationState.success); }); }), catchError(error => { const message = errorHandFn(error); this.translateService.get(message).subscribe(res => operateChanges(operMessage, OperationState.failure, res) ); return observableThrowError(message); })); } } doSearchRepoNames(repoName: string) { this.lastFilteredRepoName = repoName; this.currentPage = 1; let st: State = this.currentState; if (!st || !st.page) { st = { page: {} }; } st.page.size = this.pageSize; st.page.from = 0; st.page.to = this.pageSize - 1; this.clrLoad(st); } saveSignatures(event: { [key: string]: string[] }): void { Object.assign(this.signedCon, event); } deleteRepos(repoLists: RepositoryItem[]) { if (repoLists && repoLists.length) { let repoNames: string[] = []; repoLists.forEach(repo => { repoNames.push(repo.name); }); this.confirmationDialogSet( 'REPOSITORY.DELETION_TITLE_REPO', '', repoNames.join(','), repoLists, 'REPOSITORY.DELETION_SUMMARY_REPO', ConfirmationButtons.DELETE_CANCEL); } } getTagInfo(repoName: string): Observable<void> { this.signedCon[repoName] = []; return this.tagService.getTags(repoName) .pipe(map(items => { items.forEach((t: Tag) => { if (t.signature !== null) { this.signedCon[repoName].push(t.name); } }); }) , catchError(error => observableThrowError(error))); } confirmationDialogSet(summaryTitle: string, signature: string, repoName: string, repoLists: RepositoryItem[], summaryKey: string, button: ConfirmationButtons): void { this.translateService.get(summaryKey, { repoName: repoName, signedImages: signature, }).pipe(finalize(() => { let hnd = setInterval(() => this.ref.markForCheck(), 100); setTimeout(() => clearInterval(hnd), 5000); })) .subscribe((res: string) => { summaryKey = res; let message = new ConfirmationMessage( summaryTitle, summaryKey, repoName, repoLists, ConfirmationTargets.REPOSITORY, button); this.confirmationDialog.open(message); }); } containsLatestTag(repo: RepositoryItem): Observable<boolean> { return this.tagService.getTags(repo.name) .pipe(map(items => { if (items.some((t: Tag) => { return t.name === 'latest'; })) { return true; } else { return false; } }) , catchError(error => observableThrowError(false))); } provisionItemEvent(evt: any, repo: RepositoryItem): void { evt.stopPropagation(); let repoCopy = clone(repo); repoCopy.name = this.registryUrl + ":443/" + repoCopy.name; this.containsLatestTag(repo) .subscribe(containsLatest => { if (containsLatest) { this.repoProvisionEvent.emit(repoCopy); } else { this.addInfoEvent.emit(repoCopy); } }, error => this.errorHandler.error(error)); } itemAddInfoEvent(evt: any, repo: RepositoryItem): void { evt.stopPropagation(); let repoCopy = clone(repo); repoCopy.name = this.registryUrl + ":443/" + repoCopy.name; this.addInfoEvent.emit(repoCopy); } deleteItemEvent(evt: any, item: RepositoryItem): void { evt.stopPropagation(); this.deleteRepos([item]); } selectedChange(): void { let hnd = setInterval(() => this.ref.markForCheck(), 100); setTimeout(() => clearInterval(hnd), 2000); } refresh() { this.doSearchRepoNames(""); } loadNextPage() { this.currentPage = this.currentPage + 1; // Pagination let params: RequestQueryParams = new RequestQueryParams(); params.set("page", "" + this.currentPage); params.set("page_size", "" + this.pageSize); this.loading = true; this.repositoryService.getRepositories( this.projectId, this.lastFilteredRepoName, params ) .subscribe((repo: Repository) => { this.totalCount = repo.metadata.xTotalCount; this.repositoriesCopy = repo.data; this.signedCon = {}; // Do filtering and sorting this.repositoriesCopy = doFiltering<RepositoryItem>( this.repositoriesCopy, this.currentState ); this.repositoriesCopy = doSorting<RepositoryItem>( this.repositoriesCopy, this.currentState ); this.repositories = this.repositories.concat(this.repositoriesCopy); this.loading = false; }, error => { this.loading = false; this.errorHandler.error(error); }); let hnd = setInterval(() => this.ref.markForCheck(), 500); setTimeout(() => clearInterval(hnd), 5000); } clrLoad(state: State): void { if (!state || !state.page) { return; } this.selectedRow = []; // Keep it for future filtering and sorting this.currentState = state; let pageNumber: number = calculatePage(state); if (pageNumber <= 0) { pageNumber = 1; } // Pagination let params: RequestQueryParams = new RequestQueryParams(); params.set("page", "" + pageNumber); params.set("page_size", "" + this.pageSize); this.loading = true; this.repositoryService.getRepositories( this.projectId, this.lastFilteredRepoName, params ) .subscribe((repo: Repository) => { this.totalCount = repo.metadata.xTotalCount; this.repositories = repo.data; this.signedCon = {}; // Do filtering and sorting this.repositories = doFiltering<RepositoryItem>( this.repositories, state ); this.repositories = doSorting<RepositoryItem>(this.repositories, state); this.loading = false; }, error => { this.loading = false; this.errorHandler.error(error); }); // Force refresh view let hnd = setInterval(() => this.ref.markForCheck(), 100); setTimeout(() => clearInterval(hnd), 5000); } getStateAfterDeletion(): State { let total: number = this.totalCount - 1; if (total <= 0) { return null; } let totalPages: number = Math.ceil(total / this.pageSize); let targetPageNumber: number = this.currentPage; if (this.currentPage > totalPages) { targetPageNumber = totalPages; // Should == currentPage -1 } let st: State = this.currentState; if (!st) { st = { page: {} }; } st.page.size = this.pageSize; st.page.from = (targetPageNumber - 1) * this.pageSize; st.page.to = targetPageNumber * this.pageSize - 1; return st; } watchRepoClickEvt(repo: RepositoryItem) { this.repoClickEvent.emit(repo); } getImgLink(repo: RepositoryItem): string { return "/container-image-icons?container-image=" + repo.name; } showCard(cardView: boolean) { if (this.isCardView === cardView) { return; } this.isCardView = cardView; this.refresh(); } mouseEnter(itemName: string) { if (itemName === "card") { this.cardHover = true; } else { this.listHover = true; } } mouseLeave(itemName: string) { if (itemName === "card") { this.cardHover = false; } else { this.listHover = false; } } isHovering(itemName: string) { if (itemName === "card") { return this.cardHover; } else { return this.listHover; } } getHelmChartVersionPermission(projectId: number): void { let hasCreateRepositoryPermission = this.userPermissionService.getPermission(this.projectId, USERSTATICPERMISSION.REPOSITORY.KEY, USERSTATICPERMISSION.REPOSITORY.VALUE.CREATE); let hasDeleteRepositoryPermission = this.userPermissionService.getPermission(this.projectId, USERSTATICPERMISSION.REPOSITORY.KEY, USERSTATICPERMISSION.REPOSITORY.VALUE.DELETE); forkJoin(hasCreateRepositoryPermission, hasDeleteRepositoryPermission).subscribe(permissions => { this.hasCreateRepositoryPermission = permissions[0] as boolean; this.hasDeleteRepositoryPermission = permissions[1] as boolean; }, error => this.errorHandler.error(error)); } }
{ "content_hash": "51ef2611c84e5ec09c0e0dc7c621545f", "timestamp": "", "source": "github", "line_count": 507, "max_line_length": 115, "avg_line_length": 35.232741617357, "alnum_prop": 0.5691653137770811, "repo_name": "steven-zou/harbor", "id": "074bea76e7752eb15a6b9d0e6d8ed6be234ff434", "size": "17863", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/portal/lib/src/repository-gridview/repository-gridview.component.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "65898" }, { "name": "Dockerfile", "bytes": "15610" }, { "name": "Go", "bytes": "2394949" }, { "name": "HTML", "bytes": "323559" }, { "name": "JavaScript", "bytes": "2238" }, { "name": "Makefile", "bytes": "26935" }, { "name": "Mako", "bytes": "494" }, { "name": "PLSQL", "bytes": "148" }, { "name": "PLpgSQL", "bytes": "11853" }, { "name": "Python", "bytes": "238276" }, { "name": "RobotFramework", "bytes": "281940" }, { "name": "Shell", "bytes": "68780" }, { "name": "Smarty", "bytes": "26225" }, { "name": "TypeScript", "bytes": "961483" } ], "symlink_target": "" }
package com.amazonaws.services.directconnect.model.transform; import java.util.Map; import java.util.Map.Entry; import com.amazonaws.services.directconnect.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * AllocatePrivateVirtualInterfaceResult JSON Unmarshaller */ public class AllocatePrivateVirtualInterfaceResultJsonUnmarshaller implements Unmarshaller<AllocatePrivateVirtualInterfaceResult, JsonUnmarshallerContext> { public AllocatePrivateVirtualInterfaceResult unmarshall( JsonUnmarshallerContext context) throws Exception { AllocatePrivateVirtualInterfaceResult allocatePrivateVirtualInterfaceResult = new AllocatePrivateVirtualInterfaceResult(); 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("ownerAccount", targetDepth)) { context.nextToken(); allocatePrivateVirtualInterfaceResult .setOwnerAccount(StringJsonUnmarshaller .getInstance().unmarshall(context)); } if (context.testExpression("virtualInterfaceId", targetDepth)) { context.nextToken(); allocatePrivateVirtualInterfaceResult .setVirtualInterfaceId(StringJsonUnmarshaller .getInstance().unmarshall(context)); } if (context.testExpression("location", targetDepth)) { context.nextToken(); allocatePrivateVirtualInterfaceResult .setLocation(StringJsonUnmarshaller.getInstance() .unmarshall(context)); } if (context.testExpression("connectionId", targetDepth)) { context.nextToken(); allocatePrivateVirtualInterfaceResult .setConnectionId(StringJsonUnmarshaller .getInstance().unmarshall(context)); } if (context.testExpression("virtualInterfaceType", targetDepth)) { context.nextToken(); allocatePrivateVirtualInterfaceResult .setVirtualInterfaceType(StringJsonUnmarshaller .getInstance().unmarshall(context)); } if (context.testExpression("virtualInterfaceName", targetDepth)) { context.nextToken(); allocatePrivateVirtualInterfaceResult .setVirtualInterfaceName(StringJsonUnmarshaller .getInstance().unmarshall(context)); } if (context.testExpression("vlan", targetDepth)) { context.nextToken(); allocatePrivateVirtualInterfaceResult .setVlan(IntegerJsonUnmarshaller.getInstance() .unmarshall(context)); } if (context.testExpression("asn", targetDepth)) { context.nextToken(); allocatePrivateVirtualInterfaceResult .setAsn(IntegerJsonUnmarshaller.getInstance() .unmarshall(context)); } if (context.testExpression("authKey", targetDepth)) { context.nextToken(); allocatePrivateVirtualInterfaceResult .setAuthKey(StringJsonUnmarshaller.getInstance() .unmarshall(context)); } if (context.testExpression("amazonAddress", targetDepth)) { context.nextToken(); allocatePrivateVirtualInterfaceResult .setAmazonAddress(StringJsonUnmarshaller .getInstance().unmarshall(context)); } if (context.testExpression("customerAddress", targetDepth)) { context.nextToken(); allocatePrivateVirtualInterfaceResult .setCustomerAddress(StringJsonUnmarshaller .getInstance().unmarshall(context)); } if (context .testExpression("virtualInterfaceState", targetDepth)) { context.nextToken(); allocatePrivateVirtualInterfaceResult .setVirtualInterfaceState(StringJsonUnmarshaller .getInstance().unmarshall(context)); } if (context.testExpression("customerRouterConfig", targetDepth)) { context.nextToken(); allocatePrivateVirtualInterfaceResult .setCustomerRouterConfig(StringJsonUnmarshaller .getInstance().unmarshall(context)); } if (context.testExpression("virtualGatewayId", targetDepth)) { context.nextToken(); allocatePrivateVirtualInterfaceResult .setVirtualGatewayId(StringJsonUnmarshaller .getInstance().unmarshall(context)); } if (context.testExpression("routeFilterPrefixes", targetDepth)) { context.nextToken(); allocatePrivateVirtualInterfaceResult .setRouteFilterPrefixes(new ListUnmarshaller<RouteFilterPrefix>( RouteFilterPrefixJsonUnmarshaller .getInstance()).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 allocatePrivateVirtualInterfaceResult; } private static AllocatePrivateVirtualInterfaceResultJsonUnmarshaller instance; public static AllocatePrivateVirtualInterfaceResultJsonUnmarshaller getInstance() { if (instance == null) instance = new AllocatePrivateVirtualInterfaceResultJsonUnmarshaller(); return instance; } }
{ "content_hash": "d505dc338966c478f6fbd3220efb1c5a", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 130, "avg_line_length": 47.79220779220779, "alnum_prop": 0.5472826086956522, "repo_name": "trasa/aws-sdk-java", "id": "51d81faa447b4093f94fb337512d19d12538aff9", "size": "7944", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-directconnect/src/main/java/com/amazonaws/services/directconnect/model/transform/AllocatePrivateVirtualInterfaceResultJsonUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "100011199" }, { "name": "Scilab", "bytes": "2354" } ], "symlink_target": "" }
import csv import operator import os import platform import sys # Putil imports import putil.exh import putil.misc import putil.pcontracts from putil.ptypes import ( csv_col_filter, csv_filtered, csv_row_filter, file_name, file_name_exists, non_negative_integer ) from .write import _write_int ### # Exception tracing initialization code ### """ [[[cog import os, sys sys.path.append(os.environ['TRACER_DIR']) import trace_ex_pcsv_csv_file exobj = trace_ex_pcsv_csv_file.trace_module(no_print=True) ]]] [[[end]]] """ ### # Functions ### def _homogenize_data_filter(dfilter): """ Make data filter definition consistent, create a tuple where first element is the row filter and the second element is the column filter """ if isinstance(dfilter, tuple) and (len(dfilter) == 1): dfilter = (dfilter[0], None) if (dfilter is None) or (dfilter == (None, None)) or (dfilter == (None, )): dfilter = (None, None) elif isinstance(dfilter, dict): dfilter = (dfilter, None) elif (isinstance(dfilter, str) or (isinstance(dfilter, int) and (not isinstance(dfilter, bool))) or isinstance(dfilter, list)): dfilter = (None, dfilter if isinstance(dfilter, list) else [dfilter]) elif (isinstance(dfilter[0], dict) or ((dfilter[0] is None) and (not isinstance(dfilter[1], dict)))): pass else: dfilter = (dfilter[1], dfilter[0]) return dfilter def _tofloat(obj): """ Convert to float if object is a float string """ if 'inf' in obj.lower().strip(): return obj try: return int(obj) except ValueError: try: return float(obj) except ValueError: return obj ### # Classes ### class CsvFile(object): r""" Processes comma-separated values (CSV) files :param fname: Name of the comma-separated values file to read :type fname: :ref:`FileNameExists` :param dfilter: Row and/or column filter. If None no data filtering is done :type dfilter: :ref:`CsvDataFilter` or None :param has_header: Flag that indicates whether the comma-separated values file has column headers in its first line (True) o not (False) :type has_header: boolean :param frow: First data row (starting from 1). If 0 the row where data starts is auto-detected as the first row that has a number (integer of float) in at least one of its columns :type frow: :ref:`NonNegativeInteger` :rtype: :py:class:`putil.pcsv.CsvFile` object .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.pcsv.csv_file.CsvFile.__init__ :raises: * OSError (File *[fname]* could not be found) * RuntimeError (Argument \`dfilter\` is not valid) * RuntimeError (Argument \`fname\` is not valid) * RuntimeError (Argument \`frow\` is not valid) * RuntimeError (Argument \`has_header\` is not valid) * RuntimeError (Column headers are not unique in file *[fname]*) * RuntimeError (File *[fname]* has no valid data) * RuntimeError (File *[fname]* is empty) * RuntimeError (Invalid column specification) * ValueError (Column *[column_identifier]* not found) .. [[[end]]] """ # pylint: disable=R0902,W0631 @putil.pcontracts.contract( fname='file_name_exists' ) def __init__(self, fname, dfilter=None, has_header=True, frow=0): self._header = None self._header_upper = None self._data = None self._fdata = None self._cfilter = None self._rfilter = None self._exh = None self._fname = fname self._has_header = None self._data_rows = None self._fdata_rows = None self._data_cols = None self._fdata_cols = None self._set_has_header(has_header) # Register exceptions empty_exobj = putil.exh.addex(RuntimeError, 'File *[fname]* is empty') col_exobj = putil.exh.addex( RuntimeError, 'Column headers are not unique in file *[fname]*' ) nvdata_exobj = putil.exh.addex( RuntimeError, 'File *[fname]* has no valid data' ) edata = {'field':'fname', 'value':self._fname} # Read data if sys.hexversion < 0x03000000: # pragma: no cover, no branch fname = putil.misc.normalize_windows_fname(fname) with open(fname, 'r') as file_handle: self._raw_data = [row for row in csv.reader(file_handle)] else: # pragma: no cover, no branch with open(fname, 'r', newline='') as file_handle: self._raw_data = [row for row in csv.reader(file_handle)] # Process header empty_exobj(not len(self._raw_data), edata) if has_header: self._header = self._raw_data[0] self._header_upper = [col.upper() for col in self._header] col_exobj( len(set(self._header_upper)) != len(self._header_upper), edata ) else: self._header = list(range(0, len(self._raw_data[0]))) self._header_upper = self._header frow = self._validate_frow(frow) if frow == 0: # Find start of data row. A data row is defined as one that has at # least one column with a number for num, row in enumerate(self._raw_data[1 if has_header else 0:]): if any([putil.misc.isnumber(_tofloat(col)) for col in row]): break else: nvdata_exobj(True, edata) else: nvdata_exobj(frow > len(self._raw_data), edata) num = frow-(2 if has_header else 1) # Set up class properties self._data = [ [ None if col.strip() == '' else _tofloat(col) for col in row ] for row in self._raw_data[num+(1 if has_header else 0):] ] self._data_cols = len(self._header) self._data_rows = len(self._data) self._fdata_rows = self._data_rows self._reset_dfilter_int() # [r|c]rfilter already validated, can use internal function, # not API end-point self._set_dfilter(dfilter) def __eq__(self, other): """ Tests object equality. For example: >>> import putil.misc, putil.pcsv >>> with putil.misc.TmpFile() as fname: ... putil.pcsv.write(fname, [['a'], [1]], append=False) ... obj1 = putil.pcsv.CsvFile(fname, dfilter='a') ... obj2 = putil.pcsv.CsvFile(fname, dfilter='a') ... >>> with putil.misc.TmpFile() as fname: ... putil.pcsv.write(fname, [['a'], [2]], append=False) ... obj3 = putil.pcsv.CsvFile(fname, dfilter='a') ... >>> obj1 == obj2 True >>> obj1 == obj3 False >>> 5 == obj3 False """ # pylint: disable=W0212 if not isinstance(other, CsvFile): return False sfname = putil.misc.normalize_windows_fname(self._fname) ofname = putil.misc.normalize_windows_fname(other._fname) return all( [ sfname == ofname, self._rfilter == other._rfilter, self._cfilter == other._cfilter, self._has_header == other._has_header ] ) def __repr__(self): """ Returns a string with the expression needed to re-create the object. For example: >>> import putil.misc, putil.pcsv >>> with putil.misc.TmpFile() as fname: ... putil.pcsv.write(fname, [['a'], [1]], append=False) ... obj1 = putil.pcsv.CsvFile(fname, dfilter='a') ... exec("obj2="+repr(obj1)) >>> obj1 == obj2 True >>> repr(obj1) "putil.pcsv.CsvFile(fname=r'...', dfilter=['a'])" """ dfilter_list = ( None, self._cfilter, self._rfilter, (self._rfilter, self._cfilter) ) dfilter = dfilter_list[ 2*(self._rfilter is not None)+(self._cfilter is not None) ] has_header = self._has_header ret = [ "putil.pcsv.CsvFile(fname=r'{0}'".format( putil.misc.normalize_windows_fname(self._fname) ) ] if dfilter: ret.append("dfilter={0}".format(dfilter)) if not has_header: ret.append("has_header={0}".format(has_header)) return ", ".join(ret)+")" def __str__(self): """ Returns a string with a detailed description of the object's contents. For example: >>> from __future__ import print_function >>> import putil.misc, putil.pcsv >>> with putil.misc.TmpFile() as fname: ... putil.pcsv.write(fname, [['a', 'b'], [1, 2], [3, 4]]) ... obj = putil.pcsv.CsvFile(fname, dfilter='a') ... >>> print(str(obj)) #doctest: +ELLIPSIS File: ... Header: ['a', 'b'] Row filter: None Column filter: ['a'] Rows: 2 Columns: 2 (1 filtered) """ ret = ['File: {0}'.format(self._fname)] ret += ['Header: {0}'.format(self._header)] ret += ['Row filter: {0}'.format(self._rfilter)] ret += ['Column filter: {0}'.format(self._cfilter)] ret += [ 'Rows: {rrows}{urows}'.format( rrows=self._data_rows, urows=( ' ({rows} filtered)'.format(rows=self._fdata_rows) if self._rfilter is not None else '' ) ) ] ret += [ 'Columns: {rcols}{ucols}'.format( rcols=self._data_cols, ucols=( ' ({cols} filtered)'.format(cols=self._fdata_cols) if self._cfilter is not None else '' ) ) ] return '\n'.join(ret) def _format_rfilter(self, rfilter): return [ ( ( self._header_upper.index(key.upper()) if isinstance(key, str) else key ), ( [value] if not putil.misc.isiterable(value) else [item for item in value] ) ) for key, value in rfilter.items() ] if rfilter else [] def _gen_col_index(self, filtered=True): col_index_list = [] if self._cfilter and (filtered in [True, 'B', 'b', 'C', 'c']): for col in self._cfilter: if isinstance(col, str): col_index_list.append( self._header_upper.index(col.upper()) ) else: col_index_list.append(col) return col_index_list return range(len(self._header)) def _get_cfilter(self): return self._cfilter def _get_dfilter(self): return (self._rfilter, self._cfilter) def _get_rfilter(self): return self._rfilter def _reset_dfilter_int(self, ftype=True): if ftype in [True, 'B', 'b', 'R', 'r']: self._rfilter = None if ftype in [True, 'B', 'b', 'C', 'c']: self._cfilter = None def _in_header(self, col): """ Validate column identifier(s) """ if not self._has_header: # Conditionally register exceptions so that they do not appear # in situations where has_header is always True. In this way # they are not auto-documented by default icol_ex = putil.exh.addex( RuntimeError, 'Invalid column specification' ) hnf_ex = putil.exh.addex( ValueError, 'Column *[column_identifier]* not found' ) col_list = ( [col] if isinstance(col, str) or isinstance(col, int) else col ) for col in col_list: edata = {'field':'column_identifier', 'value':col} if not self._has_header: # Condition not subsumed in raise_exception_if # so that calls that always have has_header=True # do not pick up this exception icol_ex(not isinstance(col, int)) hnf_ex((col < 0) or (col > len(self._header)-1), edata) else: hnf_ex( (isinstance(col, int) and ((col < 0) or (col > self._data_cols))) or (isinstance(col, str) and (col.upper() not in self._header_upper)), edata ) return col_list @putil.pcontracts.contract(cfilter='csv_col_filter') def _set_cfilter(self, cfilter): self._reset_dfilter_int('C') self._add_dfilter_int(cfilter) @putil.pcontracts.contract(dfilter='csv_data_filter') def _set_dfilter(self, dfilter): dfilter = _homogenize_data_filter(dfilter) self._reset_dfilter_int() self._add_dfilter_int(dfilter) @putil.pcontracts.contract(rfilter='csv_row_filter') def _set_rfilter(self, rfilter): self._reset_dfilter_int('R') self._add_dfilter_int(rfilter, letter='r') def _add_dfilter_int(self, dfilter, letter='d'): rfilter, cfilter = _homogenize_data_filter(dfilter) if cfilter is not None: cfilter = self._in_header(cfilter) if self._cfilter is None: self._cfilter = [] self._cfilter.append(cfilter) cfilter = putil.misc.flatten_list(self._cfilter) col_indexes = ( [ item if isinstance(item, int) else self._header_upper.index(item.upper()) for item in cfilter ] ) self._cfilter = [self._header[item] for item in col_indexes] self._fdata_cols = len(cfilter) if rfilter is not None: self._validate_rfilter(rfilter, letter) for key in rfilter: if self._rfilter is None: self._rfilter = {} if key in self._rfilter: self._rfilter[key] = list( set( ( self._rfilter[key] if isinstance(self._rfilter[key], list) else [self._rfilter[key]] ) + ( rfilter[key] if isinstance(rfilter[key], list) else [rfilter[key]] ) ) ) else: self._rfilter[key] = rfilter[key] self._fdata_rows = len(self._apply_filter('R')) def _apply_filter(self, ftype, no_empty=False): # pylint: disable=W0141 rlist = [True, 'B', 'b', 'R', 'r'] clist = [True, 'B', 'b', 'C', 'c'] apply_filter = ( self._rfilter and (ftype in rlist) or self._cfilter and (ftype in clist) ) if self._rfilter and (ftype in rlist): # Row filter df_tuples = self._format_rfilter(self._rfilter) self._fdata = [ row for row in self._data if all([row[col_num] in col_value for col_num, col_value in df_tuples]) ] if self._cfilter and (ftype in clist): # Column filter col_index_list = self._gen_col_index() # Filter column data self._fdata = [ [row[index] for index in col_index_list] for row in ( self._fdata if self._rfilter and (ftype in rlist) else self._data ) ] data = self._fdata if apply_filter else self._data ffull = lambda row: not any([item is None for item in row]) return list(filter(ffull, data)) if no_empty else data @putil.pcontracts.contract(has_header=bool) def _set_has_header(self, has_header): self._has_header = has_header def _validate_frow(self, frow): """ Validate frow argument """ is_int = isinstance(frow, int) and (not isinstance(frow, bool)) putil.exh.addai('frow', not (is_int and (frow >= 0))) return frow def _validate_rfilter(self, rfilter, letter='d'): """ Validate that all columns in filter are in header """ if letter == 'd': putil.exh.addai( 'dfilter', ( (not self._has_header) and any( [ not isinstance(item, int) for item in rfilter.keys() ] ) ) ) else: putil.exh.addai( 'rfilter', ( (not self._has_header) and any( [ not isinstance(item, int) for item in rfilter.keys() ] ) ) ) for key in rfilter: self._in_header(key) rfilter[key] = ( [rfilter[key]] if isinstance(rfilter[key], str) else rfilter[key] ) @putil.pcontracts.contract(dfilter='csv_data_filter') def add_dfilter(self, dfilter): r""" Adds more row(s) or column(s) to the existing data filter. Duplicate filter values are eliminated :param dfilter: Row and/or column filter :type dfilter: :ref:`CsvDataFilter` .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.pcsv.csv_file.CsvFile.add_dfilter :raises: * RuntimeError (Argument \`dfilter\` is not valid) * RuntimeError (Invalid column specification) * ValueError (Column *[column_identifier]* not found) .. [[[end]]] """ self._add_dfilter_int(dfilter) @putil.pcontracts.contract(filtered=bool) def cols(self, filtered=False): r""" Returns the number of data columns :param filtered: Flag that indicates whether the raw (input) data should be used (False) or whether filtered data should be used (True) :type filtered: boolean .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.pcsv.csv_file.CsvFile.cols :raises: RuntimeError (Argument \`filtered\` is not valid) .. [[[end]]] """ return self._fdata_cols if filtered else self._data_cols @putil.pcontracts.contract(filtered='csv_filtered', no_empty=bool) def data(self, filtered=False, no_empty=False): r""" Returns (filtered) file data. The returned object is a list, each item is a sub-list corresponding to a row of data; each item in the sub-lists contains data corresponding to a particular column :param filtered: Filtering type :type filtered: :ref:`CsvFiltered` :param no_empty: Flag that indicates whether rows with empty columns should be filtered out (True) or not (False) :type no_empty: bool :rtype: list .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.pcsv.csv_file.CsvFile.data :raises: * RuntimeError (Argument \`filtered\` is not valid) * RuntimeError (Argument \`no_empty\` is not valid) .. [[[end]]] """ return self._apply_filter(filtered, no_empty) @putil.pcontracts.contract(order='csv_col_sort') def dsort(self, order): r""" Sorts rows :param order: Sort order :type order: :ref:`CsvColFilter` .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.pcsv.csv_file.CsvFile.dsort :raises: * RuntimeError (Argument \`order\` is not valid) * RuntimeError (Invalid column specification) * ValueError (Column *[column_identifier]* not found) .. [[[end]]] """ # Make order conforming to a list of dictionaries order = order if isinstance(order, list) else [order] norder = [ {item:'A'} if not isinstance(item, dict) else item for item in order ] # Verify that all columns exist in file self._in_header([list(item.keys())[0] for item in norder]) # Get column indexes clist = [] for nitem in norder: for key, value in nitem.items(): clist.append( ( key if isinstance(key, int) else self._header_upper.index(key.upper()), value.upper() == 'D' ) ) # From the Python documentation: # "Starting with Python 2.3, the sort() method is guaranteed to be # stable. A sort is stable if it guarantees not to change the # relative order of elements that compare equal - this is helpful # for sorting in multiple passes (for example, sort by department, # then by salary grade)." # This means that the sorts have to be done from "minor" column to # "major" column for (cindex, rvalue) in reversed(clist): fpointer = operator.itemgetter(cindex) self._data.sort(key=fpointer, reverse=rvalue) @putil.pcontracts.contract(filtered=bool) def header(self, filtered=False): r""" Returns the data header. When the raw (input) data is used the data header is a list of the comma-separated values file header if the file is loaded with header (each list item is a column header) or a list of column numbers if the file is loaded without header (column zero is the leftmost column). When filtered data is used the data header is the active column filter, if any, otherwise it is the same as the raw (input) data header :param filtered: Flag that indicates whether the raw (input) data should be used (False) or whether filtered data should be used (True) :type filtered: boolean :rtype: list of strings or integers .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.pcsv.csv_file.CsvFile.header :raises: RuntimeError (Argument \`filtered\` is not valid) .. [[[end]]] """ return ( self._header if (not filtered) or (filtered and self._cfilter is None) else self._cfilter ) @putil.pcontracts.contract(rdata='list(list)', filtered='csv_filtered') def replace(self, rdata, filtered=False): r""" Replaces data :param rdata: Replacement data :type rdata: list of lists :param filtered: Filtering type :type filtered: :ref:`CsvFiltered` .. [[[cog cog.out(exobj.get_sphinx_autodoc(width=63)) ]]] .. Auto-generated exceptions documentation for .. putil.pcsv.csv_file.CsvFile.replace :raises: * RuntimeError (Argument \`filtered\` is not valid) * RuntimeError (Argument \`rdata\` is not valid) * ValueError (Number of columns mismatch between input and replacement data) * ValueError (Number of rows mismatch between input and replacement data) .. [[[end]]] """ # pylint: disable=R0914 rdata_ex = putil.exh.addai('rdata') rows_ex = putil.exh.addex( ValueError, 'Number of rows mismatch between input and replacement data' ) cols_ex = putil.exh.addex( ValueError, 'Number of columns mismatch between input and replacement data' ) rdata_ex(any([len(item) != len(rdata[0]) for item in rdata])) # Use all columns if no specification has been given cfilter = ( self._cfilter if filtered in [True, 'B', 'b', 'C', 'c'] else self._header ) # Verify column names, has to be done before getting data col_num = len(self._data[0])-1 odata = self._apply_filter(filtered) cfilter = ( self._cfilter if filtered in [True, 'B', 'b', 'C', 'c'] else self._header ) col_index = [ self._header_upper.index(col_id.upper()) if isinstance(col_id, str) else col_id for col_id in cfilter ] rows_ex(len(odata) != len(rdata)) cols_ex(len(odata[0]) != len(rdata[0])) df_tuples = self._format_rfilter(self._rfilter) rnum = 0 for row in self._data: if (not filtered) or (filtered and all([row[col_num] in col_value for col_num, col_value in df_tuples])): for col_num, new_data in zip(col_index, rdata[rnum]): row[col_num] = new_data rnum = rnum+1 @putil.pcontracts.contract(ftype='csv_filtered') def reset_dfilter(self, ftype=True): r""" Reset (clears) the data filter :param ftype: Filter type :type ftype: :ref:`CsvFiltered` .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.pcsv.csv_file.CsvFile.reset_dfilter :raises: RuntimeError (Argument \`ftype\` is not valid) .. [[[end]]] """ self._reset_dfilter_int(ftype) @putil.pcontracts.contract(filtered=bool) def rows(self, filtered=False): r""" Returns the number of data rows :param filtered: Flag that indicates whether the raw (input) data should be used (False) or whether filtered data should be used (True) :type filtered: boolean .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.pcsv.csv_file.CsvFile.rows :raises: RuntimeError (Argument \`filtered\` is not valid) .. [[[end]]] """ return self._fdata_rows if filtered else self._data_rows @putil.pcontracts.contract( fname='None|file_name', filtered='csv_filtered', header='str|bool|list[>0](str)', append=bool ) def write(self, fname=None, filtered=False, header=True, append=False): r""" Writes (processed) data to a specified comma-separated values (CSV) file :param fname: Name of the comma-separated values file to be written. If None the file from which the data originated is overwritten :type fname: :ref:`FileName` :param filtered: Filtering type :type filtered: :ref:`CsvFiltered` :param header: If a list, column headers to use in the file. If boolean, flag that indicates whether the input column headers should be written (True) or not (False) :type header: string, list of strings or boolean :param append: Flag that indicates whether data is added to an existing file (or a new file is created if it does not exist) (True), or whether data overwrites the file contents (if the file exists) or creates a new file if the file does not exists (False) :type append: boolean .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.pcsv.csv_file.CsvFile.write :raises: * OSError (File *[fname]* could not be created: *[reason]*) * RuntimeError (Argument \`append\` is not valid) * RuntimeError (Argument \`filtered\` is not valid) * RuntimeError (Argument \`fname\` is not valid) * RuntimeError (Argument \`header\` is not valid) * RuntimeError (Argument \`no_empty\` is not valid) * ValueError (There is no data to save to file) .. [[[end]]] """ # pylint: disable=R0913 write_ex = putil.exh.addex( ValueError, 'There is no data to save to file' ) fname = self._fname if fname is None else fname data = self.data(filtered=filtered) write_ex( (len(data) == 0) or ((len(data) == 1) and (len(data[0]) == 0)) ) if header: header = [header] if isinstance(header, str) else header cfilter = self._gen_col_index(filtered=filtered) filtered_header = ( [self._header[item] for item in cfilter] if self._has_header else cfilter ) file_header = ( filtered_header if isinstance(header, bool) else header ) # Convert None's to '' data = [ ["''" if item is None else item for item in row] for row in data ] _write_int( fname, [file_header]+data if header else data, append=append ) # Managed attributes cfilter = property(_get_cfilter, _set_cfilter, doc='Column filter') r""" Sets or returns the column filter :type: :ref:`CsvColFilter` or None. If None no column filtering is done :rtype: :ref:`CsvColFilter` or None .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.pcsv.csv_file.CsvFile.cfilter :raises: (when assigned) * RuntimeError (Argument \`cfilter\` is not valid) * RuntimeError (Invalid column specification) * ValueError (Column *[column_identifier]* not found) .. [[[end]]] """ dfilter = property(_get_dfilter, _set_dfilter, doc='Data filter') r""" Sets or returns the data (row and/or column) filter. The first tuple item is the row filter and the second tuple item is the column filter :type: :ref:`CsvDataFilter` or None. If None no data filtering is done :rtype: :ref:`CsvDataFilter` or None .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.pcsv.csv_file.CsvFile.dfilter :raises: (when assigned) * RuntimeError (Argument \`dfilter\` is not valid) * RuntimeError (Invalid column specification) * ValueError (Column *[column_identifier]* not found) .. [[[end]]] """ rfilter = property(_get_rfilter, _set_rfilter, doc='Returns row filter') r""" Sets or returns the row filter :type: :ref:`CsvRowFilter` or None. If None no row filtering is done :rtype: :ref:`CsvRowFilter` or None .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.pcsv.csv_file.CsvFile.rfilter :raises: (when assigned) * RuntimeError (Argument \`rfilter\` is not valid) * RuntimeError (Invalid column specification) * ValueError (Argument \`rfilter\` is empty) * ValueError (Column *[column_identifier]* not found) .. [[[end]]] """
{ "content_hash": "2a598a1806453f7b31d9ec399e8688fb", "timestamp": "", "source": "github", "line_count": 952, "max_line_length": 79, "avg_line_length": 34.21638655462185, "alnum_prop": 0.5320194019770369, "repo_name": "pmacosta/putil", "id": "7002543a08a7c76e4058310aa20746dbc66c23c5", "size": "32732", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "putil/pcsv/csv_file.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "16611" }, { "name": "Makefile", "bytes": "2425" }, { "name": "PowerShell", "bytes": "7209" }, { "name": "Python", "bytes": "1220525" }, { "name": "Shell", "bytes": "56372" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_101) on Mon Sep 19 15:00:22 UTC 2016 --> <title>MailMessage (Spring Framework 4.3.3.RELEASE API)</title><script>var _hmt = _hmt || [];(function() {var hm = document.createElement("script");hm.src = "//hm.baidu.com/hm.js?dd1361ca20a10cc161e72d4bc4fef6df";var s = document.getElementsByTagName("script")[0];s.parentNode.insertBefore(hm, s);})();</script> <meta name="date" content="2016-09-19"> <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="MailMessage (Spring Framework 4.3.3.RELEASE API)"; } } catch(err) { } //--> var methods = {"i0":6,"i1":6,"i2":6,"i3":6,"i4":6,"i5":6,"i6":6,"i7":6,"i8":6,"i9":6,"i10":6}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Spring Framework</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../org/springframework/mail/MailException.html" title="class in org.springframework.mail"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/springframework/mail/MailMessage.html" target="_top">Frames</a></li> <li><a href="MailMessage.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.springframework.mail</div> <h2 title="Interface MailMessage" class="title">Interface MailMessage</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../org/springframework/mail/javamail/MimeMailMessage.html" title="class in org.springframework.mail.javamail">MimeMailMessage</a>, <a href="../../../org/springframework/mail/SimpleMailMessage.html" title="class in org.springframework.mail">SimpleMailMessage</a></dd> </dl> <hr> <br> <pre>public interface <span class="typeNameLabel">MailMessage</span></pre> <div class="block">This is a common interface for mail messages, allowing a user to set key values required in assembling a mail message, without needing to know if the underlying message is a simple text message or a more sophisticated MIME message. <p>Implemented by both SimpleMailMessage and MimeMessageHelper, to let message population code interact with a simple message or a MIME message through a common interface.</div> <dl> <dt><span class="simpleTagLabel">Since:</span></dt> <dd>1.1.5</dd> <dt><span class="simpleTagLabel">Author:</span></dt> <dd>Juergen Hoeller</dd> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../org/springframework/mail/SimpleMailMessage.html" title="class in org.springframework.mail"><code>SimpleMailMessage</code></a>, <a href="../../../org/springframework/mail/javamail/MimeMessageHelper.html" title="class in org.springframework.mail.javamail"><code>MimeMessageHelper</code></a></dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/springframework/mail/MailMessage.html#setBcc-java.lang.String-">setBcc</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;bcc)</code>&nbsp;</td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/springframework/mail/MailMessage.html#setBcc-java.lang.String:A-">setBcc</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[]&nbsp;bcc)</code>&nbsp;</td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/springframework/mail/MailMessage.html#setCc-java.lang.String-">setCc</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;cc)</code>&nbsp;</td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/springframework/mail/MailMessage.html#setCc-java.lang.String:A-">setCc</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[]&nbsp;cc)</code>&nbsp;</td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/springframework/mail/MailMessage.html#setFrom-java.lang.String-">setFrom</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;from)</code>&nbsp;</td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/springframework/mail/MailMessage.html#setReplyTo-java.lang.String-">setReplyTo</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;replyTo)</code>&nbsp;</td> </tr> <tr id="i6" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/springframework/mail/MailMessage.html#setSentDate-java.util.Date-">setSentDate</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/util/Date.html?is-external=true" title="class or interface in java.util">Date</a>&nbsp;sentDate)</code>&nbsp;</td> </tr> <tr id="i7" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/springframework/mail/MailMessage.html#setSubject-java.lang.String-">setSubject</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;subject)</code>&nbsp;</td> </tr> <tr id="i8" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/springframework/mail/MailMessage.html#setText-java.lang.String-">setText</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;text)</code>&nbsp;</td> </tr> <tr id="i9" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/springframework/mail/MailMessage.html#setTo-java.lang.String-">setTo</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;to)</code>&nbsp;</td> </tr> <tr id="i10" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/springframework/mail/MailMessage.html#setTo-java.lang.String:A-">setTo</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[]&nbsp;to)</code>&nbsp;</td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="setFrom-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setFrom</h4> <pre>void&nbsp;setFrom(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;from) throws <a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></code></dd> </dl> </li> </ul> <a name="setReplyTo-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setReplyTo</h4> <pre>void&nbsp;setReplyTo(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;replyTo) throws <a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></code></dd> </dl> </li> </ul> <a name="setTo-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setTo</h4> <pre>void&nbsp;setTo(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;to) throws <a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></code></dd> </dl> </li> </ul> <a name="setTo-java.lang.String:A-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setTo</h4> <pre>void&nbsp;setTo(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[]&nbsp;to) throws <a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></code></dd> </dl> </li> </ul> <a name="setCc-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setCc</h4> <pre>void&nbsp;setCc(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;cc) throws <a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></code></dd> </dl> </li> </ul> <a name="setCc-java.lang.String:A-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setCc</h4> <pre>void&nbsp;setCc(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[]&nbsp;cc) throws <a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></code></dd> </dl> </li> </ul> <a name="setBcc-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setBcc</h4> <pre>void&nbsp;setBcc(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;bcc) throws <a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></code></dd> </dl> </li> </ul> <a name="setBcc-java.lang.String:A-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setBcc</h4> <pre>void&nbsp;setBcc(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[]&nbsp;bcc) throws <a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></code></dd> </dl> </li> </ul> <a name="setSentDate-java.util.Date-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setSentDate</h4> <pre>void&nbsp;setSentDate(<a href="http://docs.oracle.com/javase/8/docs/api/java/util/Date.html?is-external=true" title="class or interface in java.util">Date</a>&nbsp;sentDate) throws <a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></code></dd> </dl> </li> </ul> <a name="setSubject-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setSubject</h4> <pre>void&nbsp;setSubject(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;subject) throws <a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></code></dd> </dl> </li> </ul> <a name="setText-java.lang.String-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>setText</h4> <pre>void&nbsp;setText(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;text) throws <a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail">MailParseException</a></code></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="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Spring Framework</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../org/springframework/mail/MailException.html" title="class in org.springframework.mail"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../org/springframework/mail/MailParseException.html" title="class in org.springframework.mail"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/springframework/mail/MailMessage.html" target="_top">Frames</a></li> <li><a href="MailMessage.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "17f97cfaa0ffdd0b7982aa256c6776bd", "timestamp": "", "source": "github", "line_count": 427, "max_line_length": 391, "avg_line_length": 48.26463700234192, "alnum_prop": 0.6790237274976951, "repo_name": "piterlin/piterlin.github.io", "id": "f836e70077ec8598e78a14f8f6322cf65a5e7533", "size": "20609", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/spring4.3.3-docs/javadoc-api/org/springframework/mail/MailMessage.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "479" }, { "name": "HTML", "bytes": "9480869" }, { "name": "JavaScript", "bytes": "246" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>FST - Slade Prestwich</title> <meta name="description" content="Keep track of the statistics from Slade Prestwich. Average heat score, heat wins, heat wins percentage, epic heats road to the final"> <meta name="author" content=""> <link rel="apple-touch-icon" sizes="57x57" href="/favicon/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/favicon/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/favicon/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/favicon/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/favicon/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/favicon/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/favicon/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/favicon/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/favicon/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/favicon/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <meta property="og:title" content="Fantasy Surfing tips"/> <meta property="og:image" content="https://fantasysurfingtips.com/img/just_waves.png"/> <meta property="og:description" content="See how great Slade Prestwich is surfing this year"/> <!-- Bootstrap Core CSS - Uses Bootswatch Flatly Theme: https://bootswatch.com/flatly/ --> <link href="https://fantasysurfingtips.com/css/bootstrap.css" rel="stylesheet"> <!-- Custom CSS --> <link href="https://fantasysurfingtips.com/css/freelancer.css" rel="stylesheet"> <link href="https://cdn.datatables.net/plug-ins/1.10.7/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet" /> <!-- Custom Fonts --> <link href="https://fantasysurfingtips.com/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css"> <script src="https://code.jquery.com/jquery-2.x-git.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ujs/1.2.1/rails.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script> <script src="https://www.w3schools.com/lib/w3data.js"></script> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <script> (adsbygoogle = window.adsbygoogle || []).push({ google_ad_client: "ca-pub-2675412311042802", enable_page_level_ads: true }); </script> </head> <body> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.6"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <!-- Navigation --> <div w3-include-html="https://fantasysurfingtips.com/layout/header.html"></div> <!-- Header --> <div w3-include-html="https://fantasysurfingtips.com/layout/sponsor.html"></div> <section > <div class="container"> <div class="row"> <div class="col-sm-3 "> <div class="col-sm-2 "> </div> <div class="col-sm-8 "> <!-- <img src="http://fantasysurfingtips.com/img/surfers/spre.png" class="img-responsive" alt=""> --> <h3 style="text-align:center;">Slade Prestwich</h3> <a href="https://twitter.com/share" class="" data-via="fansurfingtips"><i class="fa fa-twitter"></i> Share on Twitter</i></a> <br/> <a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Ffantasysurfingtips.com%2Fsurfers%2Fspre&amp;src=sdkpreparse"><i class="fa fa-facebook"></i> Share on Facebook</a> </div> <div class="col-sm-2 "> </div> </div> <div class="col-sm-3 portfolio-item"> </div> <div class="col-sm-3 portfolio-item"> <h6 style="text-align:center;">Avg Heat Score (FST DATA)</h6> <h1 style="text-align:center;">10.97</h1> </div> </div> <hr/> <h4 style="text-align:center;" >Competitions</h4> <h4 style="text-align:center;" >Epic Battles</h4> <div class="row"> <div class="col-sm-6 "> <p style="text-align:center;">Surfed <b>5</b> heats against <a href="http://fantasysurfingtips.com/surfers/mqs/amas.html"> Adin Masencamp</a> <br/> <b>won 3</b> and <b>lost 2</b></p> </div> <div class="col-sm-6 "> <p style="text-align:center;">Surfed <b>4</b> heats against <a href="http://fantasysurfingtips.com/surfers/mqs/bde.html"> Beyrick De Vries</a> <br/> <b>won 0</b> and <b>lost 4</b></p> </div> </div> <hr/> <h4 style="text-align:center;" >Heat Stats (FST data)</h4> <div class="row"> <div class="col-sm-4 portfolio-item"> <h6 style="text-align:center;">Heats</h6> <h2 style="text-align:center;">105</h2> </div> <div class="col-sm-4 portfolio-item"> <h6 style="text-align:center;">Heat wins</h6> <h2 style="text-align:center;">21</h2> </div> <div class="col-sm-4 portfolio-item"> <h6 style="text-align:center;">HEAT WINS PERCENTAGE</h6> <h2 style="text-align:center;">20.0%</h2> </div> </div> <hr/> <h4 style="text-align:center;">Avg Heat Score progression</h4> <div id="avg_chart" style="height: 250px;"></div> <hr/> <h4 style="text-align:center;">Heat stats progression</h4> <div id="heat_chart" style="height: 250px;"></div> <hr/> <style type="text/css"> .heats-all{ z-index: 3; margin-left: 5px; cursor: pointer; } </style> <div class="container"> <div id="disqus_thread"></div> <script> /** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/ var disqus_config = function () { this.page.url = "http://fantasysurfingtips.com/surfers/spre"; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = '1119'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = '//fantasysurfingtips.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> </section> <script type="text/javascript"> $('.heats-all').click(function(){ $('.heats-all-stat').css('display', 'none') $('#'+$(this).attr('id')+'-stat').css('display', 'block') }); $('.heats-2016').click(function(){ $('.heats-2016-stat').css('display', 'none') $('#'+$(this).attr('id')+'-stat').css('display', 'block') }); $('document').ready(function(){ new Morris.Line({ // ID of the element in which to draw the chart. element: 'avg_chart', // Chart data records -- each entry in this array corresponds to a point on // the chart. data: [], // The name of the data record attribute that contains x-values. xkey: 'year', // A list of names of data record attributes that contain y-values. ykeys: ['avg', 'avg_all'], // Labels for the ykeys -- will be displayed when you hover over the // chart. labels: ['Avg score in year', 'Avg score FST DATA'] }); new Morris.Bar({ // ID of the element in which to draw the chart. element: 'heat_chart', // Chart data records -- each entry in this array corresponds to a point on // the chart. data: [], // The name of the data record attribute that contains x-values. xkey: 'year', // A list of names of data record attributes that contain y-values. ykeys: ['heats', 'wins', 'percs'], // Labels for the ykeys -- will be displayed when you hover over the // chart. labels: ['Heats surfed', 'Heats won', 'Winning percentage'] }); }); </script> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> <!-- Footer --> <div w3-include-html="https://fantasysurfingtips.com/layout/footer.html"></div> <script type="text/javascript"> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-74337819-1', 'auto'); // Replace with your property ID. ga('send', 'pageview'); </script> <script> w3IncludeHTML(); </script> <!-- jQuery --> <script src="https://fantasysurfingtips.com/js/jquery.js"></script> <script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="https://fantasysurfingtips.com/js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> <script src="https://fantasysurfingtips.com/js/classie.js"></script> <script src="https://fantasysurfingtips.com/js/cbpAnimatedHeader.js"></script> <!-- Contact Form JavaScript --> <script src="https://fantasysurfingtips.com/js/jqBootstrapValidation.js"></script> <script src="https://fantasysurfingtips.com/js/contact_me.js"></script> <!-- Custom Theme JavaScript --> <script src="https://fantasysurfingtips.com/js/freelancer.js"></script> <script type="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script> <script type="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script> </body> </html>
{ "content_hash": "3b59dab5b00d63cc0b3c11bbfc1d1705", "timestamp": "", "source": "github", "line_count": 296, "max_line_length": 295, "avg_line_length": 40.16891891891892, "alnum_prop": 0.6251471825063079, "repo_name": "chicofilho/fst", "id": "64aca7410179e0a84e24b00f70cc1d68a65241ee", "size": "11890", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "surfers/mqs/spre.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "25157" }, { "name": "HTML", "bytes": "114679577" }, { "name": "JavaScript", "bytes": "43263" }, { "name": "PHP", "bytes": "1097" } ], "symlink_target": "" }
#ifndef LLSCHEME_PARSER_HPP #define LLSCHEME_PARSER_HPP #include <memory> #include <list> #include <llvm/ADT/STLExtras.h> #include "ast.hpp" #include "reader.hpp" namespace llscm { using namespace std; /*class ParserException { string msg; public: ParserException(const string & str): msg(str) {} const char * what() { return msg.c_str(); } };*/ class Parser { const unique_ptr<Reader>& reader; bool err_flag; bool match(const Token * tok, const Token && expected); void error(const string & msg); public: Parser(const unique_ptr<Reader>& r): reader(r) { err_flag = false; } bool fail() { return err_flag; } ScmProg NT_Prog(); P_ScmObj NT_Form(); P_ScmObj NT_Def(); P_ScmObj NT_CallOrSyntax(); P_ScmObj NT_Expr(); P_ScmObj NT_Data(); P_ScmObj NT_Atom(bool quoted); P_ScmObj NT_List(); P_ScmObj NT_SymList(); P_ScmObj NT_BindList(); P_ScmObj NT_Body(); }; } #endif //LLSCHEME_PARSER_HPP
{ "content_hash": "022d5e7408c9c1d8c2401c99a450741e", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 57, "avg_line_length": 19.08, "alnum_prop": 0.6530398322851153, "repo_name": "nohajc/llscheme", "id": "602abc821011c7c9d2ecda160a946d3706a38f12", "size": "954", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/parser.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "43115" }, { "name": "C++", "bytes": "483645" }, { "name": "CMake", "bytes": "4022" }, { "name": "Makefile", "bytes": "2470" }, { "name": "Ruby", "bytes": "1664" }, { "name": "Scheme", "bytes": "9980" } ], "symlink_target": "" }
var sls_target; var sls_width; var sls_type; var sls_handle_target; var sls_handle_width; var sls_input; var sls_handle_dist; var slider=function(){ // setting up $("div.sls").each(function(){ // "width" - "handle width" // because sls-limit means there must be two handles // and each of their movement field is that width because one whitch can't overlap other // that's why defining movement field explicitically var width = $(this).width() - $(this).children(".sls-handle").width(); $(this).prepend("<div style='width:"+width+"px' class='sls-knob-stack'></div>"); if($(this).attr("data-start") && $(this).attr("data-end") && !$(this).hasClass("sls-limit") && !$(this).hasClass("sls-knob-disabled")){ var start = parseInt($(this).attr("data-start")); var end = parseInt($(this).attr("data-end")); var diff = Math.abs(start - end); for(var i=0; i<diff; i++){ $(this).children(".sls-knob-stack").append("<span class='sls-knob'></span>"); } } if($(this).attr("data-start") && $(this).attr("data-end")){ $(this).children(".sls-handle").html($(this).attr("data-start")); } if($(this).hasClass("sls-limit")){ // getting end value from attribute var end = parseInt($(this).attr("data-end")); // positioning the second button on the far right var second_handle_left = $(this).width() - $(this).find(".sls-handle").outerWidth(); // adding button $(this).append("<div style='left:"+second_handle_left+"px;' class='sls-handle'>"+end+"</div>"); } }); $("div.sls > .sls-handle").on("mousedown touchstart", function(e){ // on mousedown or touch it'll get and store all info about the slider into the global variables // that are in the beginning // next two line prevent selection on drag e.preventDefault(); e.cancelBubble=true; // when the user press button the slider's data-drag attr will change to 1 // that means it can be moved/dragged now (verified on mousemove) // if the user moves button up then it changes back to 0 (it's done later) $(this).parent().attr("data-drag","1"); // next 3 lines sets gloal variable sls_target = $(this).parent(); sls_handle_width = sls_target.find(".sls-handle").outerWidth(); sls_width = sls_target.width(); sls_input = sls_target.siblings("input"); // it registers which handle is going to move, and it's used in mousemove // as an example, if the user press on the first handle then only first one gonna move sls_handle_target = $(this).index(); sls_handle_dist = Math.abs(e.pageX - $(this).offset().left); // if user wants two handles then specify it in global variables if($(this).parent().hasClass("sls-limit")){ sls_type = "limit"; }else{ sls_type = "single"; } }); // as said before when user unclick it'll be non-movable $(document).on("mouseup touchend", function(){ sls_target.attr("data-drag","0"); var data = sls_target.find(".sls-handle").eq(0).text(); if(sls_target.find(".sls-handle").eq(1).length > 0){ data += "-"+sls_target.find(".sls-handle").eq(1).text(); } sls_input.val(data); }); // now the real part... $(document).on("mousemove touchmove", function(e){ // if data-drag=1 then handles will move if(sls_target && sls_target.attr("data-drag") == 1){ // getting event type, touch or mouse if(e.type == "touchmove"){ var event = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0]; }else if(e.type == "mousemove"){ var event = e; } // getting the active handle that // because of starting number i had to substarct 1 from original index number var handle = sls_target.find(".sls-handle").eq(sls_handle_target - 1); // if the active one is the first and has two switches (limit) if(sls_handle_target == 1 && sls_type == "limit"){ // getting position of mouse var posX = event.pageX - sls_target.offset().left; // left position of the left handle var handle_left_pos = posX - sls_handle_dist; // if position is greated than 0 and less than (total width - handle width) // then move according to mouse position if(handle_left_pos >= 0 && handle_left_pos <= (sls_width - sls_handle_width*2)){ // moving handle.css({ "left": handle_left_pos + "px" }); // if the first handle collides with the second then drag it with the first one // untill it stops // "posX + sls_handle_width" : because posX is the left position of first whitch // that's why added it's width so the second one will drag like is would in real life // if end point of the first handle is biggert than start point of second handle if(handle_left_pos + sls_handle_width > parseInt(handle.next().css("left"))){ handle.next().css({ "left": handle_left_pos + sls_handle_width + "px" }).addClass("merge-left"); handle.addClass("merge-right"); // calculation position & printing it on the handle // while dragging with the first handle, second handle also need to change value as it drags var start = parseInt(sls_target.attr("data-start")); var end = parseInt(sls_target.attr("data-end")); var length_value = (Math.round(parseInt(handle.next().css("left")) - sls_handle_width)/(sls_width - sls_handle_width*2) * 100); var value = start + Math.round( length_value/(100/(end - start))); handle.next().html(value); }else{ handle.removeClass("merge-right"); handle.next().removeClass("merge-left"); } // if reaches right end limit then set it to the right }else if(handle_left_pos > (sls_width - sls_handle_width*2)){ handle.css({ "left": sls_width - sls_handle_width*2 + "px" }).addClass("merge-right"); // if first handle reaches end end then // secont handle's left = end of width = bar width - handle width // because of perfection handle.next().css({ "left": sls_width - sls_handle_width + "px" }).addClass("merge-left"); // calculation position & printing it on the handle // again calculation if first handle reaches end.. // otherwise adjustment of the second handle will be imperfect at the end var start = parseInt(sls_target.attr("data-start")); var end = parseInt(sls_target.attr("data-end")); var length_value = (Math.round(parseInt(handle.next().css("left")) - sls_handle_width)/(sls_width - sls_handle_width*2) * 100); var value = start + Math.round( length_value/(100/(end - start))); handle.next().html(value); // if reaches left end limit then set it to the left }else if(handle_left_pos <= 0){ handle.css({ "left": 0 + "px" }); } // calculation position & printing it on the handle // (this same calculation is done in the previous two state) if(sls_target.attr("data-start") && sls_target.attr("data-end")){ var start = parseInt(sls_target.attr("data-start")); var end = parseInt(sls_target.attr("data-end")); var length_value = Math.round(parseInt(handle.css("left"))/(sls_width - sls_handle_width*2) * 100); var value = start + Math.round( length_value/(100/(end - start))); handle.html(value); } // just like the first one second condition is 90% same // in this case if the second handle is active }else if(sls_handle_target == 2 && sls_type == "limit"){ var posX = event.pageX - sls_target.offset().left; // left position of the left handle var handle_left_pos = posX - sls_handle_dist; if(handle_left_pos > sls_handle_width && handle_left_pos < (sls_width - sls_handle_width)){ handle.css({ "left": handle_left_pos + "px" }); // // now, unlike the first condition, the second handle must stop before (0px + handle width) // from the left, because first handle is there // // again if second handle collides with first // then drag it with the second one if(handle_left_pos <= parseInt(handle.prev().css("left")) + sls_handle_width){ handle.prev().css({ "left": handle_left_pos - sls_handle_width + "px" }).addClass("merge-right"); handle.addClass("merge-left"); // calculating.. var start = parseInt(sls_target.attr("data-start")); var end = parseInt(sls_target.attr("data-end")); var length_value = Math.round(parseInt(handle.prev().css("left"))/(sls_width - sls_handle_width*2) * 100); var value = start + Math.round( length_value/(100/(end - start))); handle.prev().html(value); }else{ handle.removeClass("merge-left"); handle.prev().removeClass("merge-right"); } // if reaches right end limit then set it to the right }else if((handle_left_pos + sls_handle_width) > sls_width){ handle.css({ "left": sls_width - sls_handle_width + "px" }); // if reaches left end limit then set it to the left }else if(handle_left_pos < sls_handle_width){ handle.css({ "left": sls_handle_width + "px" }).addClass("merge-left"); // if second hanndle reaches end then // first handle's left = 0 // because of perfection handle.prev().css({ "left": 0 + "px" }).addClass("merge-right"); // calculating... var start = parseInt(sls_target.attr("data-start")); var end = parseInt(sls_target.attr("data-end")); var length_value = Math.round(parseInt(handle.prev().css("left"))/(sls_width - sls_handle_width*2) * 100); var value = start + Math.round( length_value/(100/(end - start))); handle.prev().html(value); } if(sls_target.attr("data-start") && sls_target.attr("data-end")){ var start = parseInt(sls_target.attr("data-start")); var end = parseInt(sls_target.attr("data-end")); var length_value = (Math.round(parseInt(handle.css("left")) - sls_handle_width)/(sls_width - sls_handle_width*2) * 100); var value = start + Math.round( length_value/(100/(end - start))); handle.html(value); } // else if user don't need two handles }else if(sls_handle_target == 1 && sls_type != "limit"){ var posX = event.pageX - sls_target.offset().left; // left position of the left handle var handle_left_pos = posX - sls_handle_dist; if(handle_left_pos > 0 && handle_left_pos < (sls_width - sls_handle_width)){ handle.css({ "left": handle_left_pos + "px" }); }else if(handle_left_pos > (sls_width - sls_handle_width)){ handle.css({ "left": sls_width - sls_handle_width + "px" }); }else if(handle_left_pos < 0){ handle.css({ "left": 0 + "px" }); } if(sls_target.attr("data-start") && sls_target.attr("data-end")){ var start = parseInt(sls_target.attr("data-start")); var end = parseInt(sls_target.attr("data-end")); var length_value = Math.round(parseInt(handle.css("left"))/(sls_width - sls_handle_width) * 100); var value = start + Math.round( length_value/(100/(end - start))); handle.html(value); } } } }); }
{ "content_hash": "3a23c514afb3ef8308a7cc7ec10239de", "timestamp": "", "source": "github", "line_count": 271, "max_line_length": 137, "avg_line_length": 40.87084870848709, "alnum_prop": 0.6237811484290358, "repo_name": "ankur841/InvestmentApp", "id": "89672d9de17d2baeacd0d621781bf15853050a3b", "size": "11093", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "uat/lib/inputSlider/inputSlider-1.0.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "158772" }, { "name": "CSS", "bytes": "29442" }, { "name": "HTML", "bytes": "61739" }, { "name": "JavaScript", "bytes": "681426" } ], "symlink_target": "" }
package helpers import ( "context" "fmt" "strconv" "strings" ) // PerfTest represents a type of test to run when running `netperf`. type PerfTest string const ( // TCP_RR represents a netperf test for TCP Request/Response performance. // For more information, consult : http://www.cs.kent.edu/~farrell/dist/ref/Netperf.html TCP_RR = PerfTest("TCP_RR") // TCP_STREAM represents a netperf test for TCP throughput performance. // For more information, consult : http://www.cs.kent.edu/~farrell/dist/ref/Netperf.html TCP_STREAM = PerfTest("TCP_STREAM") // TCP_MAERTS represents a netperf test for TCP throughput performance (reverse direction of TCP_STREAM). // For more information, consult : http://www.cs.kent.edu/~farrell/dist/ref/Netperf.html TCP_MAERTS = PerfTest("TCP_MAERTS") // TCP_CRR represents a netperf test that connects and sends single request/response // For more information, consult : http://www.cs.kent.edu/~farrell/dist/ref/Netperf.html TCP_CRR = PerfTest("TCP_CRR") // UDP_RR represents a netperf test for UDP Request/Response performance. // For more information, consult : http://www.cs.kent.edu/~farrell/dist/ref/Netperf.html UDP_RR = PerfTest("UDP_RR") ) // PingWithCount returns the string representing the ping command to ping the // specified endpoint, and takes a custom number of requests to send. func PingWithCount(endpoint string, count uint) string { return fmt.Sprintf("ping -W %d -c %d %s", PingTimeout, count, endpoint) } // Ping returns the string representing the ping command to ping the specified // endpoint. func Ping(endpoint string) string { return PingWithCount(endpoint, PingCount) } // Ping6 returns the string representing the ping6 command to ping6 the // specified endpoint. func Ping6(endpoint string) string { return fmt.Sprintf("ping6 -c %d %s", PingCount, endpoint) } func Ping6WithID(endpoint string, icmpID uint16) string { return fmt.Sprintf("xping -6 -W %d -c %d -x %d %s", PingTimeout, PingCount, icmpID, endpoint) } func PingWithID(endpoint string, icmpID uint16) string { return fmt.Sprintf("xping -W %d -c %d -x %d %s", PingTimeout, PingCount, icmpID, endpoint) } // Wrk runs a standard wrk test for http func Wrk(endpoint string) string { return fmt.Sprintf("wrk -t2 -c100 -d30s -R2000 http://%s", endpoint) } // CurlFail returns the string representing the curl command with `-s` and // `--fail` options enabled to curl the specified endpoint. It takes a // variadic optionalValues argument. This is passed on to fmt.Sprintf() and // used into the curl message. func CurlFail(endpoint string, optionalValues ...interface{}) string { statsInfo := `time-> DNS: '%{time_namelookup}(%{remote_ip})', Connect: '%{time_connect}',` + `Transfer '%{time_starttransfer}', total '%{time_total}'` if len(optionalValues) > 0 { endpoint = fmt.Sprintf(endpoint, optionalValues...) } return fmt.Sprintf( `curl --path-as-is -s -D /dev/stderr --fail --connect-timeout %d --max-time %d %s -w "%s"`, CurlConnectTimeout, CurlMaxTimeout, endpoint, statsInfo) } // CurlFailNoStats does the same as CurlFail() except that it does not print // the stats info. func CurlFailNoStats(endpoint string, optionalValues ...interface{}) string { if len(optionalValues) > 0 { endpoint = fmt.Sprintf(endpoint, optionalValues...) } return fmt.Sprintf( `curl --path-as-is -s -D /dev/stderr --fail --connect-timeout %[1]d --max-time %[2]d %[3]s`, CurlConnectTimeout, CurlMaxTimeout, endpoint) } // CurlWithHTTPCode retunrs the string representation of the curl command which // only outputs the HTTP code returned by its execution against the specified // endpoint. It takes a variadic optinalValues argument. This is passed on to // fmt.Sprintf() and uses into the curl message func CurlWithHTTPCode(endpoint string, optionalValues ...interface{}) string { if len(optionalValues) > 0 { endpoint = fmt.Sprintf(endpoint, optionalValues...) } return fmt.Sprintf( `curl --path-as-is -s -D /dev/stderr --output /dev/stderr -w '%%{http_code}' --connect-timeout %d %s`, CurlConnectTimeout, endpoint) } // CurlWithRetries returns the string representation of the curl command that // retries the request if transient problems occur. The parameter "retries" // indicates the maximum number of attempts. If flag "fail" is true, the // function will call CurlFail() and add --retry flag at the end of the command // and return. If flag "fail" is false, the function will generate the command // with --retry flag and return. func CurlWithRetries(endpoint string, retries int, fail bool, optionalValues ...interface{}) string { if fail { return fmt.Sprintf( `%s --retry %d`, CurlFail(endpoint, optionalValues...), retries) } if len(optionalValues) > 0 { endpoint = fmt.Sprintf(endpoint, optionalValues...) } return fmt.Sprintf( `curl --path-as-is -s -D /dev/stderr --output /dev/stderr --retry %d %s`, retries, endpoint) } // Netperf returns the string representing the netperf command to use when testing // connectivity between endpoints. func Netperf(endpoint string, perfTest PerfTest, options string) string { return fmt.Sprintf("netperf -l 3 -t %s -H %s %s", perfTest, endpoint, options) } // SuperNetperf returns the string representing the super_netperf command to use when // testing connectivity between endpoints. func SuperNetperf(sessions int, endpoint string, perfTest PerfTest, options string) string { return fmt.Sprintf("super_netperf %d -t %s -H %s %s", sessions, perfTest, endpoint, options) } // Netcat returns the string representing the netcat command to the specified // endpoint. It takes a variadic optionalValues arguments, This is passed to // fmt.Sprintf uses in the netcat message. func Netcat(endpoint string, optionalValues ...interface{}) string { if len(optionalValues) > 0 { endpoint = fmt.Sprintf(endpoint, optionalValues...) } return fmt.Sprintf("nc -w 4 %s", endpoint) } // PythonBind returns the string representing a python3 command which will try // to bind a socket on the given address and port. Python is available in the // log-gatherer pod. func PythonBind(addr string, port uint16, proto string) string { var opts []string if strings.Contains(addr, ":") { opts = append(opts, "family=socket.AF_INET6") } else { opts = append(opts, "family=socket.AF_INET") } switch strings.ToLower(proto) { case "tcp": opts = append(opts, "type=socket.SOCK_STREAM") case "udp": opts = append(opts, "type=socket.SOCK_DGRAM") } return fmt.Sprintf( `/usr/bin/python3 -c 'import socket; socket.socket(%s).bind((%q, %d))`, strings.Join(opts, ", "), addr, port) } // ReadFile returns the string representing a cat command to read the file at // the give path. func ReadFile(path string) string { return fmt.Sprintf("cat %q", path) } // OpenSSLShowCerts retrieve the TLS certificate presented at the given // host:port when serverName is requested. The openssl cli is available in the // Cilium pod. func OpenSSLShowCerts(host string, port uint16, serverName string) string { serverNameFlag := "" if serverName != "" { serverNameFlag = fmt.Sprintf("-servername %q", serverName) } return fmt.Sprintf("openssl s_client -connect %s:%d %s -showcerts | openssl x509 -outform PEM", host, port, serverNameFlag) } // GetBPFPacketsCount returns the number of packets for a given drop reason and // direction by parsing BPF metrics. func GetBPFPacketsCount(kubectl *Kubectl, pod, reason, direction string) (int, error) { cmd := fmt.Sprintf("cilium bpf metrics list -o json | jq '.[] | select(.description == \"%s\").values.%s.packets'", reason, direction) res := kubectl.CiliumExecMustSucceed(context.TODO(), pod, cmd) return strconv.Atoi(strings.TrimSpace(res.Stdout())) }
{ "content_hash": "2ac290cbf01b486462f23e85187e59ef", "timestamp": "", "source": "github", "line_count": 197, "max_line_length": 135, "avg_line_length": 39.31472081218274, "alnum_prop": 0.7278244028405423, "repo_name": "tgraf/cilium", "id": "7f177e548e7743824c335fd6bc7b9a0dc148e458", "size": "8340", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/helpers/wrappers.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1109708" }, { "name": "C++", "bytes": "6557" }, { "name": "Dockerfile", "bytes": "27333" }, { "name": "Go", "bytes": "9930421" }, { "name": "HCL", "bytes": "1127" }, { "name": "Makefile", "bytes": "72210" }, { "name": "Mustache", "bytes": "1457" }, { "name": "Python", "bytes": "11099" }, { "name": "Ruby", "bytes": "392" }, { "name": "Shell", "bytes": "369722" }, { "name": "SmPL", "bytes": "6540" }, { "name": "Smarty", "bytes": "10858" }, { "name": "TeX", "bytes": "416" }, { "name": "sed", "bytes": "1336" } ], "symlink_target": "" }
package validation import ( "github.com/GoogleCloudPlatform/kubernetes/pkg/util" "github.com/GoogleCloudPlatform/kubernetes/pkg/util/fielderrors" "github.com/openshift/origin/pkg/oauth/api" ) func ValidateAccessToken(accessToken *api.OAuthAccessToken) fielderrors.ValidationErrorList { allErrs := fielderrors.ValidationErrorList{} if len(accessToken.Name) == 0 { allErrs = append(allErrs, fielderrors.NewFieldRequired("name")) } if len(accessToken.ClientName) == 0 { allErrs = append(allErrs, fielderrors.NewFieldRequired("clientname")) } if len(accessToken.UserName) == 0 { allErrs = append(allErrs, fielderrors.NewFieldRequired("username")) } if len(accessToken.UserUID) == 0 { allErrs = append(allErrs, fielderrors.NewFieldRequired("useruid")) } if len(accessToken.Namespace) != 0 { allErrs = append(allErrs, fielderrors.NewFieldInvalid("namespace", accessToken.Namespace, "namespace must be empty")) } allErrs = append(allErrs, validateLabels(accessToken.Labels)...) return allErrs } func ValidateAuthorizeToken(authorizeToken *api.OAuthAuthorizeToken) fielderrors.ValidationErrorList { allErrs := fielderrors.ValidationErrorList{} if len(authorizeToken.Name) == 0 { allErrs = append(allErrs, fielderrors.NewFieldRequired("name")) } if len(authorizeToken.ClientName) == 0 { allErrs = append(allErrs, fielderrors.NewFieldRequired("clientname")) } if len(authorizeToken.UserName) == 0 { allErrs = append(allErrs, fielderrors.NewFieldRequired("username")) } if len(authorizeToken.UserUID) == 0 { allErrs = append(allErrs, fielderrors.NewFieldRequired("useruid")) } if len(authorizeToken.Namespace) != 0 { allErrs = append(allErrs, fielderrors.NewFieldInvalid("namespace", authorizeToken.Namespace, "namespace must be empty")) } allErrs = append(allErrs, validateLabels(authorizeToken.Labels)...) return allErrs } func ValidateClient(client *api.OAuthClient) fielderrors.ValidationErrorList { allErrs := fielderrors.ValidationErrorList{} if len(client.Name) == 0 { allErrs = append(allErrs, fielderrors.NewFieldRequired("name")) } if len(client.Namespace) != 0 { allErrs = append(allErrs, fielderrors.NewFieldInvalid("namespace", client.Namespace, "namespace must be empty")) } allErrs = append(allErrs, validateLabels(client.Labels)...) return allErrs } func ValidateClientAuthorization(clientAuthorization *api.OAuthClientAuthorization) fielderrors.ValidationErrorList { allErrs := fielderrors.ValidationErrorList{} if len(clientAuthorization.Name) == 0 { allErrs = append(allErrs, fielderrors.NewFieldRequired("name")) } if len(clientAuthorization.ClientName) == 0 { allErrs = append(allErrs, fielderrors.NewFieldRequired("clientname")) } if len(clientAuthorization.UserName) == 0 { allErrs = append(allErrs, fielderrors.NewFieldRequired("username")) } if len(clientAuthorization.UserUID) == 0 { allErrs = append(allErrs, fielderrors.NewFieldRequired("useruid")) } if len(clientAuthorization.Namespace) != 0 { allErrs = append(allErrs, fielderrors.NewFieldInvalid("namespace", clientAuthorization.Namespace, "namespace must be empty")) } allErrs = append(allErrs, validateLabels(clientAuthorization.Labels)...) return allErrs } func ValidateClientAuthorizationUpdate(newAuth *api.OAuthClientAuthorization, oldAuth *api.OAuthClientAuthorization) fielderrors.ValidationErrorList { allErrs := ValidateClientAuthorization(newAuth) if oldAuth.Name != newAuth.Name { allErrs = append(allErrs, fielderrors.NewFieldInvalid("name", newAuth.Name, "name is not a mutable field")) } if oldAuth.ClientName != newAuth.ClientName { allErrs = append(allErrs, fielderrors.NewFieldInvalid("clientname", newAuth.ClientName, "clientname is not a mutable field")) } if oldAuth.UserName != newAuth.UserName { allErrs = append(allErrs, fielderrors.NewFieldInvalid("username", newAuth.UserName, "username is not a mutable field")) } if oldAuth.UserUID != newAuth.UserUID { allErrs = append(allErrs, fielderrors.NewFieldInvalid("useruid", newAuth.UserUID, "useruid is not a mutable field")) } allErrs = append(allErrs, validateLabels(newAuth.Labels)...) return allErrs } func validateLabels(labels map[string]string) fielderrors.ValidationErrorList { allErrs := fielderrors.ValidationErrorList{} for k := range labels { if !util.IsDNS952Label(k) { allErrs = append(allErrs, fielderrors.NewFieldNotSupported("label", k)) } } return allErrs }
{ "content_hash": "9541208ce836d5c4fddc82543c3181d6", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 150, "avg_line_length": 40.35454545454545, "alnum_prop": 0.7677404820905609, "repo_name": "westmisfit/origin", "id": "4b698d71275d68184506ff793c6a06072163239d", "size": "4439", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "pkg/oauth/api/validation/validation.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "40163" }, { "name": "Go", "bytes": "10510664" }, { "name": "HTML", "bytes": "72342" }, { "name": "JavaScript", "bytes": "182591" }, { "name": "Makefile", "bytes": "2748" }, { "name": "Python", "bytes": "3979" }, { "name": "Ruby", "bytes": "121" }, { "name": "Shell", "bytes": "118674" } ], "symlink_target": "" }
package graphql_test import ( "context" "encoding/json" "errors" "testing" "time" graphql "github.com/graph-gophers/graphql-go" qerrors "github.com/graph-gophers/graphql-go/errors" "github.com/graph-gophers/graphql-go/gqltesting" ) type rootResolver struct { *helloResolver *helloSaidResolver *helloSaidNullableResolver } type helloResolver struct{} func (r *helloResolver) Hello() string { return "Hello world!" } var resolverErr = errors.New("resolver error") var resolverQueryErr = &qerrors.QueryError{Message: "query", ResolverError: resolverErr} type helloSaidResolver struct { err error upstream <-chan *helloSaidEventResolver } type helloSaidEventResolver struct { msg string err error } func (r *helloSaidResolver) HelloSaid(ctx context.Context) (chan *helloSaidEventResolver, error) { if r.err != nil { return nil, r.err } c := make(chan *helloSaidEventResolver) go func() { for r := range r.upstream { select { case <-ctx.Done(): close(c) return case c <- r: } } close(c) }() return c, nil } func (r *rootResolver) OtherField(ctx context.Context) <-chan int32 { return make(chan int32) } func (r *helloSaidEventResolver) Msg() (string, error) { return r.msg, r.err } func closedUpstream(rr ...*helloSaidEventResolver) <-chan *helloSaidEventResolver { c := make(chan *helloSaidEventResolver, len(rr)) for _, r := range rr { c <- r } close(c) return c } type helloSaidNullableResolver struct { err error upstream <-chan *helloSaidNullableEventResolver } type helloSaidNullableEventResolver struct { msg *string err error } func (r *helloSaidNullableResolver) HelloSaidNullable(ctx context.Context) (chan *helloSaidNullableEventResolver, error) { if r.err != nil { return nil, r.err } c := make(chan *helloSaidNullableEventResolver) go func() { for r := range r.upstream { select { case <-ctx.Done(): close(c) return case c <- r: } } close(c) }() return c, nil } func (r *helloSaidNullableEventResolver) Msg() (*string, error) { return r.msg, r.err } func closedUpstreamNullable(rr ...*helloSaidNullableEventResolver) <-chan *helloSaidNullableEventResolver { c := make(chan *helloSaidNullableEventResolver, len(rr)) for _, r := range rr { c <- r } close(c) return c } func TestSchemaSubscribe(t *testing.T) { gqltesting.RunSubscribes(t, []*gqltesting.TestSubscription{ { Name: "ok", Schema: graphql.MustParseSchema(schema, &rootResolver{ helloSaidResolver: &helloSaidResolver{ upstream: closedUpstream( &helloSaidEventResolver{msg: "Hello world!"}, &helloSaidEventResolver{err: resolverErr}, &helloSaidEventResolver{msg: "Hello again!"}, ), }, }), Query: ` subscription onHelloSaid { helloSaid { msg } } `, ExpectedResults: []gqltesting.TestResponse{ { Data: json.RawMessage(` { "helloSaid": { "msg": "Hello world!" } } `), }, { Data: json.RawMessage(` null `), Errors: []*qerrors.QueryError{qerrors.Errorf("%s", resolverErr)}, }, { Data: json.RawMessage(` { "helloSaid": { "msg": "Hello again!" } } `), }, }, }, { Name: "parse_errors", Schema: graphql.MustParseSchema(schema, &rootResolver{}), Query: `invalid graphQL query`, ExpectedResults: []gqltesting.TestResponse{ { Errors: []*qerrors.QueryError{qerrors.Errorf("%s", `syntax error: unexpected "invalid", expecting "fragment" (line 1, column 9)`)}, }, }, }, { Name: "subscribe_to_query_succeeds", Schema: graphql.MustParseSchema(schema, &rootResolver{}), Query: ` query Hello { hello } `, ExpectedResults: []gqltesting.TestResponse{ { Data: json.RawMessage(` { "hello": "Hello world!" } `), }, }, }, { Name: "subscription_resolver_can_error", Schema: graphql.MustParseSchema(schema, &rootResolver{ helloSaidResolver: &helloSaidResolver{err: resolverErr}, }), Query: ` subscription onHelloSaid { helloSaid { msg } } `, ExpectedResults: []gqltesting.TestResponse{ { Data: json.RawMessage(` null `), Errors: []*qerrors.QueryError{qerrors.Errorf("%s", resolverErr)}, }, }, }, { Name: "subscription_resolver_can_error_optional_msg", Schema: graphql.MustParseSchema(schema, &rootResolver{ helloSaidNullableResolver: &helloSaidNullableResolver{ upstream: closedUpstreamNullable( &helloSaidNullableEventResolver{err: resolverErr}, ), }, }), Query: ` subscription onHelloSaid { helloSaidNullable { msg } } `, ExpectedResults: []gqltesting.TestResponse{ { Data: json.RawMessage(` { "helloSaidNullable": { "msg": null } } `), Errors: []*qerrors.QueryError{qerrors.Errorf("%s", resolverErr)}, }, }, }, { Name: "subscription_resolver_can_error_optional_event", Schema: graphql.MustParseSchema(schema, &rootResolver{ helloSaidNullableResolver: &helloSaidNullableResolver{err: resolverErr}, }), Query: ` subscription onHelloSaid { helloSaidNullable { msg } } `, ExpectedResults: []gqltesting.TestResponse{ { Data: json.RawMessage(` { "helloSaidNullable": null } `), Errors: []*qerrors.QueryError{qerrors.Errorf("%s", resolverErr)}, }, }, }, { Name: "subscription_resolver_can_query_error", Schema: graphql.MustParseSchema(schema, &rootResolver{ helloSaidResolver: &helloSaidResolver{err: resolverQueryErr}, }), Query: ` subscription onHelloSaid { helloSaid { msg } } `, ExpectedResults: []gqltesting.TestResponse{ { Data: json.RawMessage(` null `), Errors: []*qerrors.QueryError{resolverQueryErr}, }, }, }, { Name: "schema_without_resolver_errors", Schema: graphql.MustParseSchema(schema, nil), Query: ` subscription onHelloSaid { helloSaid { msg } } `, ExpectedErr: errors.New("schema created without resolver, can not subscribe"), }, }) } func TestRootOperations_invalidSubscriptionSchema(t *testing.T) { type args struct { Schema string } type want struct { Error string } testTable := map[string]struct { Args args Want want }{ "Subscription as incorrect type": { Args: args{ Schema: ` schema { query: Query subscription: String } type Query { thing: String } `, }, Want: want{Error: `root operation "subscription" must be an OBJECT`}, }, "Subscription declared by schema, but type not present": { Args: args{ Schema: ` schema { query: Query subscription: Subscription } type Query { hello: String! } `, }, Want: want{Error: `graphql: type "Subscription" not found`}, }, } for name, tt := range testTable { tt := tt t.Run(name, func(t *testing.T) { t.Parallel() _, err := graphql.ParseSchema(tt.Args.Schema, nil) if err == nil || err.Error() != tt.Want.Error { t.Logf("got: %v", err) t.Logf("want: %s", tt.Want.Error) t.Fail() } }) } } func TestRootOperations_validSubscriptionSchema(t *testing.T) { gqltesting.RunSubscribes(t, []*gqltesting.TestSubscription{ { Name: "Default name, schema omitted", Schema: graphql.MustParseSchema(` type Query { hello: String! } type Subscription { helloSaid: HelloSaidEvent! } type HelloSaidEvent { msg: String! } `, &rootResolver{helloSaidResolver: &helloSaidResolver{upstream: closedUpstream(&helloSaidEventResolver{msg: "Hello world!"})}}), Query: `subscription { helloSaid { msg } }`, ExpectedResults: []gqltesting.TestResponse{ { Data: json.RawMessage(`{"helloSaid": {"msg": "Hello world!"}}`), }, }, }, { Name: "Custom name, schema omitted", Schema: graphql.MustParseSchema(` type Query { hello: String! } type SubscriptionType { helloSaid: HelloSaidEvent! } type HelloSaidEvent { msg: String! } `, &rootResolver{}), Query: `subscription { helloSaid { msg } }`, ExpectedErr: errors.New("no subscriptions are offered by the schema"), }, { Name: "Custom name, schema required", Schema: graphql.MustParseSchema(` schema { query: Query subscription: SubscriptionType } type Query { hello: String! } type SubscriptionType { helloSaid: HelloSaidEvent! } type HelloSaidEvent { msg: String! } `, &rootResolver{helloSaidResolver: &helloSaidResolver{upstream: closedUpstream(&helloSaidEventResolver{msg: "Hello world!"})}}), Query: `subscription { helloSaid { msg } }`, ExpectedResults: []gqltesting.TestResponse{ { Data: json.RawMessage(`{"helloSaid": {"msg": "Hello world!"}}`), }, }, }, { Name: "Explicit schema without subscription field", Schema: graphql.MustParseSchema(` schema { query: Query } type Query { hello: String! } type Subscription { helloSaid: HelloSaidEvent! } type HelloSaidEvent { msg: String! } `, &rootResolver{helloSaidResolver: &helloSaidResolver{upstream: closedUpstream(&helloSaidEventResolver{msg: "Hello world!"})}}), Query: `subscription { helloSaid { msg } }`, ExpectedErr: errors.New("no subscriptions are offered by the schema"), }, }) } func TestError_multiple_subscription_fields(t *testing.T) { gqltesting.RunSubscribes(t, []*gqltesting.TestSubscription{ { Name: "Explicit schema without subscription field", Schema: graphql.MustParseSchema(` schema { query: Query subscription: Subscription } type Query { hello: String! } type Subscription { helloSaid: HelloSaidEvent! otherField: Int! } type HelloSaidEvent { msg: String! } `, &rootResolver{helloSaidResolver: &helloSaidResolver{upstream: closedUpstream(&helloSaidEventResolver{msg: "Hello world!"})}}), Query: `subscription { helloSaid { msg } otherField }`, ExpectedResults: []gqltesting.TestResponse{ { Errors: []*qerrors.QueryError{qerrors.Errorf("can subscribe to at most one subscription at a time")}, }, }, }, }) } const schema = ` schema { subscription: Subscription, query: Query } type Subscription { helloSaid: HelloSaidEvent! helloSaidNullable: HelloSaidEventNullable } type HelloSaidEvent { msg: String! } type HelloSaidEventNullable { msg: String } type Query { hello: String! } ` type subscriptionsCustomTimeout struct{} type messageResolver struct{} func (r messageResolver) Msg() string { time.Sleep(5 * time.Millisecond) return "failed!" } func (r *subscriptionsCustomTimeout) OnTimeout() <-chan *messageResolver { c := make(chan *messageResolver) go func() { c <- &messageResolver{} close(c) }() return c } func TestSchemaSubscribe_CustomResolverTimeout(t *testing.T) { r := &struct { *subscriptionsCustomTimeout }{ subscriptionsCustomTimeout: &subscriptionsCustomTimeout{}, } gqltesting.RunSubscribe(t, &gqltesting.TestSubscription{ Schema: graphql.MustParseSchema(` type Query {} type Subscription { onTimeout : Message! } type Message { msg: String! } `, r, graphql.SubscribeResolverTimeout(1*time.Millisecond)), Query: ` subscription { onTimeout { msg } } `, ExpectedResults: []gqltesting.TestResponse{ {Errors: []*qerrors.QueryError{{Message: "context deadline exceeded"}}}, }, }) } type subscriptionsPanicInResolver struct{} func (r *subscriptionsPanicInResolver) OnPanic() <-chan string { panic("subscriptionsPanicInResolver") } func TestSchemaSubscribe_PanicInResolver(t *testing.T) { r := &struct { *subscriptionsPanicInResolver }{ subscriptionsPanicInResolver: &subscriptionsPanicInResolver{}, } gqltesting.RunSubscribe(t, &gqltesting.TestSubscription{ Schema: graphql.MustParseSchema(` type Query {} type Subscription { onPanic : String! } `, r), Query: ` subscription { onPanic } `, ExpectedResults: []gqltesting.TestResponse{ {Errors: []*qerrors.QueryError{{Message: "panic occurred: subscriptionsPanicInResolver"}}}, }, }) }
{ "content_hash": "b83cd36a3d375adc4debcda07bbea4f5", "timestamp": "", "source": "github", "line_count": 575, "max_line_length": 136, "avg_line_length": 21.74608695652174, "alnum_prop": 0.6396353166986565, "repo_name": "chris-ramon/graphql-go", "id": "26baf7ed7bc77b180fc990af111982ce9ea2e13f", "size": "12504", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "subscription_test.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "772599" } ], "symlink_target": "" }
html, body{ height: 100%; min-height: 100%; } /* make sure it takes aaaaaaaaaall the space*/ .content { height: 100%; min-height: 100%; } /* image next to the channel name*/ .logo{ max-height: 50px; max-width: 50px; margin-right: 1rem; } /* make sure the tab columns is black no matter what */ .tabsColumn { background-color: #111; } /* remove has-tip default styling */ .has-tip{ border: none; font-weight: normal; } /* set display to block */ .block { display: block; margin: 1rem 0 1rem 0; } /* watch btn styling */ .watchBtn { margin: auto; background-color: transparent; border: 1px solid #CCC; border-radius: 5px; color: #CCC; } .watchBtn:hover, .watchBtn:focus { background-color: #000; border-color: #FFF; color: #FFF; } /* logo of offline channels */ .torso { display: inline-block; padding-top: 5px; font-size: 20px; min-width: 50px; margin-right: 1rem; } /* prevent tabs from growing too much in width */ #tabsWrapper{ margin: 0; } /* each menu container, there are 3 menus : all, online, offline*/ .accordion { background-color: #111; margin: 0; border: none; } .accordion-title { border-bottom: solid 1px #333; } .accordion-title:hover, .accordion-title:focus { background-color: #222; } .accordion-content { background-color: #444; border: none; } /* change color of links inside stream info */ .accordion-content > a { color: #CCC; } .accordion-content > a:hover { color: #FFF; } /* what's switching the accordions, i.e. all online offline */ .tabs { background-color: #000; border: none; } .tabs-content { border: none; } .tabs-panel { padding: 0; } .tabs-title { width: 100%; } .tabs-title > a { text-align: center; font-family: "Sans serif", Serif; background-color: #000; color: #FFF; } .tabs-title > a[aria-selected='true'] { background-color: #333; } .tabs-title > a:hover, .tabs-title > a:focus { background-color: #333; color: #FFF; } #playerContainer{ margin: 0 10% 0 10%; } /* text above twitch player */ #streamInfo{ font-family: "Sans Serif", Serif; padding-top: 2em; } /* container of twitch player, text above twitch player and gradient hr */ .streamColumn{ margin: 0 auto 0 auto; background-color: #CCC; min-height: 500px; } /* simulated hr with gradient color */ .gradientHr { width: 100px; height: 2px; background: linear-gradient(to right, #36B8E9, #000, #36B8E9); } @media (min-width: 1024px) { .gradientHr { margin: 4rem auto 4rem auto; } } @media (max-width: 1023px) { .gradientHr { margin: 2rem auto 2rem auto; } }
{ "content_hash": "8d764328e0f8c65aee0405a99afc0214", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 74, "avg_line_length": 15.524390243902438, "alnum_prop": 0.6649646504320503, "repo_name": "StephaneLeveugle/Twitch_Player", "id": "3a03594d4e7a4c1b74cab8a1be93abf247fb3e34", "size": "2546", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "74197" }, { "name": "HTML", "bytes": "2352" }, { "name": "JavaScript", "bytes": "6834" } ], "symlink_target": "" }
require 'mhash/mhash' module Mhash VERSION = "1.2" end
{ "content_hash": "3ba5b95b52ea403d8c2140096b101211", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 21, "avg_line_length": 11.6, "alnum_prop": 0.6896551724137931, "repo_name": "TibshoOT/ruby-mhash", "id": "4f07b24a19323062347eba7c999736b3638dee36", "size": "58", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/mhash.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "19993" }, { "name": "Ruby", "bytes": "17124" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>formMethod property - ImageButtonInputElement class - polymer_app_layout library - Dart API</title> <!-- required because all the links are pseudo-absolute --> <base href="../.."> <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="static-assets/prettify.css"> <link rel="stylesheet" href="static-assets/css/bootstrap.min.css"> <link rel="stylesheet" href="static-assets/styles.css"> <meta name="description" content="API docs for the formMethod property from the ImageButtonInputElement class, for the Dart programming language."> <link rel="icon" href="static-assets/favicon.png"> <!-- Do not remove placeholder --> <!-- Header Placeholder --> </head> <body> <div id="overlay-under-drawer"></div> <header class="container-fluid" id="title"> <nav class="navbar navbar-fixed-top"> <div class="container"> <button id="sidenav-left-toggle" type="button">&nbsp;</button> <ol class="breadcrumbs gt-separated hidden-xs"> <li><a href="index.html">polymer_app_layout_template</a></li> <li><a href="polymer_app_layout/polymer_app_layout-library.html">polymer_app_layout</a></li> <li><a href="polymer_app_layout/ImageButtonInputElement-class.html">ImageButtonInputElement</a></li> <li class="self-crumb">formMethod</li> </ol> <div class="self-name">formMethod</div> </div> </nav> <div class="container masthead"> <ol class="breadcrumbs gt-separated visible-xs"> <li><a href="index.html">polymer_app_layout_template</a></li> <li><a href="polymer_app_layout/polymer_app_layout-library.html">polymer_app_layout</a></li> <li><a href="polymer_app_layout/ImageButtonInputElement-class.html">ImageButtonInputElement</a></li> <li class="self-crumb">formMethod</li> </ol> <div class="title-description"> <h1 class="title"> <div class="kind">property</div> formMethod </h1> <!-- p class="subtitle"> </p --> </div> <ul class="subnav"> </ul> </div> </header> <div class="container body"> <div class="col-xs-6 col-sm-3 sidebar sidebar-offcanvas-left"> <h5><a href="index.html">polymer_app_layout_template</a></h5> <h5><a href="polymer_app_layout/polymer_app_layout-library.html">polymer_app_layout</a></h5> <h5><a href="polymer_app_layout/ImageButtonInputElement-class.html">ImageButtonInputElement</a></h5> <ol> <li class="section-title"><a href="polymer_app_layout/ImageButtonInputElement-class.html#instance-properties">Properties</a></li> <li><a href="polymer_app_layout/ImageButtonInputElement/alt.html">alt</a> </li> <li>attributes </li> <li>autofocus </li> <li>baseUri </li> <li>borderEdge </li> <li>childNodes </li> <li>children </li> <li>classes </li> <li>className </li> <li>client </li> <li>clientHeight </li> <li>clientLeft </li> <li>clientTop </li> <li>clientWidth </li> <li>contentEdge </li> <li>contentEditable </li> <li>contextMenu </li> <li>dataset </li> <li>dir </li> <li>disabled </li> <li>documentOffset </li> <li>draggable </li> <li>dropzone </li> <li>firstChild </li> <li><a href="polymer_app_layout/ImageButtonInputElement/formAction.html">formAction</a> </li> <li><a href="polymer_app_layout/ImageButtonInputElement/formEnctype.html">formEnctype</a> </li> <li><a href="polymer_app_layout/ImageButtonInputElement/formMethod.html">formMethod</a> </li> <li><a href="polymer_app_layout/ImageButtonInputElement/formNoValidate.html">formNoValidate</a> </li> <li><a href="polymer_app_layout/ImageButtonInputElement/formTarget.html">formTarget</a> </li> <li><a href="polymer_app_layout/ImageButtonInputElement/height.html">height</a> </li> <li>hidden </li> <li>id </li> <li>incremental </li> <li>indeterminate </li> <li>innerHtml </li> <li>isContentEditable </li> <li>labels </li> <li>lang </li> <li>lastChild </li> <li>localName </li> <li>marginEdge </li> <li>name </li> <li>namespaceUri </li> <li>nextElementSibling </li> <li>nextNode </li> <li>nodeName </li> <li>nodes </li> <li>nodeType </li> <li>nodeValue </li> <li>offset </li> <li>offsetHeight </li> <li>offsetLeft </li> <li>offsetParent </li> <li>offsetTop </li> <li>offsetWidth </li> <li>on </li> <li>onAbort </li> <li>onBeforeCopy </li> <li>onBeforeCut </li> <li>onBeforePaste </li> <li>onBlur </li> <li>onCanPlay </li> <li>onCanPlayThrough </li> <li>onChange </li> <li>onClick </li> <li>onContextMenu </li> <li>onCopy </li> <li>onCut </li> <li>onDoubleClick </li> <li>onDrag </li> <li>onDragEnd </li> <li>onDragEnter </li> <li>onDragLeave </li> <li>onDragOver </li> <li>onDragStart </li> <li>onDrop </li> <li>onDurationChange </li> <li>onEmptied </li> <li>onEnded </li> <li>onError </li> <li>onFocus </li> <li>onFullscreenChange </li> <li>onFullscreenError </li> <li>onInput </li> <li>onInvalid </li> <li>onKeyDown </li> <li>onKeyPress </li> <li>onKeyUp </li> <li>onLoad </li> <li>onLoadedData </li> <li>onLoadedMetadata </li> <li>onMouseDown </li> <li>onMouseEnter </li> <li>onMouseLeave </li> <li>onMouseMove </li> <li>onMouseOut </li> <li>onMouseOver </li> <li>onMouseUp </li> <li>onMouseWheel </li> <li>onPaste </li> <li>onPause </li> <li>onPlay </li> <li>onPlaying </li> <li>onRateChange </li> <li>onReset </li> <li>onResize </li> <li>onScroll </li> <li>onSearch </li> <li>onSeeked </li> <li>onSeeking </li> <li>onSelect </li> <li>onSelectStart </li> <li>onStalled </li> <li>onSubmit </li> <li>onSuspend </li> <li>onTimeUpdate </li> <li>onTouchCancel </li> <li>onTouchEnd </li> <li>onTouchEnter </li> <li>onTouchLeave </li> <li>onTouchMove </li> <li>onTouchStart </li> <li>onTransitionEnd </li> <li>onVolumeChange </li> <li>onWaiting </li> <li>outerHtml </li> <li>ownerDocument </li> <li>paddingEdge </li> <li>parent </li> <li>parentNode </li> <li>previousElementSibling </li> <li>previousNode </li> <li>scrollHeight </li> <li>scrollLeft </li> <li>scrollTop </li> <li>scrollWidth </li> <li>shadowRoot </li> <li>spellcheck </li> <li><a href="polymer_app_layout/ImageButtonInputElement/src.html">src</a> </li> <li>style </li> <li>tabIndex </li> <li>tagName </li> <li>text </li> <li>title </li> <li>translate </li> <li>validationMessage </li> <li>validity </li> <li>value </li> <li><a href="polymer_app_layout/ImageButtonInputElement/width.html">width</a> </li> <li>willValidate </li> <li>xtag </li> <li class="section-title"><a href="polymer_app_layout/ImageButtonInputElement-class.html#constructors">Constructors</a></li> <li><a href="polymer_app_layout/ImageButtonInputElement/ImageButtonInputElement.html">ImageButtonInputElement</a></li> <li class="section-title"><a href="polymer_app_layout/ImageButtonInputElement-class.html#methods">Methods</a></li> <li>addEventListener </li> <li>animate </li> <li>append </li> <li>appendHtml </li> <li>appendText </li> <li>attached </li> <li>attributeChanged </li> <li>blur </li> <li>checkValidity </li> <li>click </li> <li>clone </li> <li>contains </li> <li>createFragment </li> <li>createShadowRoot </li> <li>detached </li> <li>dispatchEvent </li> <li>enteredView </li> <li>focus </li> <li>getAnimationPlayers </li> <li>getAttribute </li> <li>getAttributeNS </li> <li>getBoundingClientRect </li> <li>getClientRects </li> <li>getComputedStyle </li> <li>getDestinationInsertionPoints </li> <li>getElementsByClassName </li> <li>getNamespacedAttributes </li> <li>hasChildNodes </li> <li>insertAdjacentElement </li> <li>insertAdjacentHtml </li> <li>insertAdjacentText </li> <li>insertAllBefore </li> <li>insertBefore </li> <li>leftView </li> <li>matches </li> <li>matchesWithAncestors </li> <li>offsetTo </li> <li>query </li> <li>queryAll </li> <li>querySelector </li> <li>querySelectorAll </li> <li>remove </li> <li>removeEventListener </li> <li>replaceWith </li> <li>requestFullscreen </li> <li>requestPointerLock </li> <li>scrollIntoView </li> <li>setAttribute </li> <li>setAttributeNS </li> <li>setCustomValidity </li> <li>setInnerHtml </li> </ol> </div><!--/.sidebar-offcanvas--> <div class="col-xs-12 col-sm-9 col-md-6 main-content"> <section class="multi-line-signature"> <span class="returntype">String</span> <span class="name ">formMethod</span> <div class="readable-writable"> read / write </div> </section> <section class="desc markdown"> <p class="no-docs">Not documented.</p> </section> </div> <!-- /.main-content --> </div> <!-- container --> <footer> <div class="container-fluid"> <div class="container"> <p class="text-center"> <span class="no-break"> polymer_app_layout_template 0.1.0 api docs </span> &bull; <span class="copyright no-break"> <a href="https://www.dartlang.org"> <img src="static-assets/favicon.png" alt="Dart" title="Dart"width="16" height="16"> </a> </span> &bull; <span class="copyright no-break"> <a href="http://creativecommons.org/licenses/by-sa/4.0/">cc license</a> </span> </p> </div> </div> </footer> <script src="static-assets/prettify.js"></script> <script src="static-assets/script.js"></script> <!-- Do not remove placeholder --> <!-- Footer Placeholder --> </body> </html>
{ "content_hash": "f41f65a4de2aa6ddc64a794eaec83829", "timestamp": "", "source": "github", "line_count": 534, "max_line_length": 151, "avg_line_length": 20.726591760299627, "alnum_prop": 0.5736357065413805, "repo_name": "lejard-h/polymer_app_layout_templates", "id": "d93c26fc3aad92bf49bbaf86869722e1a016ca57", "size": "11068", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/api/polymer_app_layout/ImageButtonInputElement/formMethod.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "2381" }, { "name": "Dart", "bytes": "25778" }, { "name": "HTML", "bytes": "17680" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_66) on Mon Apr 25 01:00:02 PDT 2016 --> <title>Uses of Package ml.utils</title> <meta name="date" content="2016-04-25"> <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="Uses of Package ml.utils"; } } 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</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../index.html?ml/utils/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.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> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Uses of Package ml.utils" class="title">Uses of Package<br>ml.utils</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../ml/utils/package-summary.html">ml.utils</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#la.matrix">la.matrix</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#ml.recommendation.util">ml.recommendation.util</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#ml.utils">ml.utils</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="la.matrix"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../ml/utils/package-summary.html">ml.utils</a> used by <a href="../../la/matrix/package-summary.html">la.matrix</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../ml/utils/class-use/Pair.html#la.matrix">Pair</a>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="ml.recommendation.util"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../ml/utils/package-summary.html">ml.utils</a> used by <a href="../../ml/recommendation/util/package-summary.html">ml.recommendation.util</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../ml/utils/class-use/Pair.html#ml.recommendation.util">Pair</a>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="ml.utils"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../ml/utils/package-summary.html">ml.utils</a> used by <a href="../../ml/utils/package-summary.html">ml.utils</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../ml/utils/class-use/FindResult.html#ml.utils">FindResult</a> <div class="block">A wrapper for the output of find function.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../ml/utils/class-use/Pair.html#ml.utils">Pair</a>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../index.html?ml/utils/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.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> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "ec993a8bf7cd9954c34573004f036a78", "timestamp": "", "source": "github", "line_count": 200, "max_line_length": 230, "avg_line_length": 33.71, "alnum_prop": 0.6367546722040938, "repo_name": "MingjieQian/LAML", "id": "a00374945cddd7ac61cdfd4a6dc5df8ea63df97b", "size": "6742", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/ml/utils/package-use.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1297773" } ], "symlink_target": "" }
@interface PayAccountViewController ()<UITableViewDataSource,UITableViewDelegate> { IBOutlet UITableView *accountTableView; IBOutlet UIButton *moneyButton; NSMutableArray * _keys; IBOutlet UILabel *hasMoneyText; NSMutableArray * dataSounrce; NSString * hasMoney; NSString * moneyFloatView; } @end @implementation PayAccountViewController - (instancetype)initWithCoder:(NSCoder *)coder { self = [super initWithCoder:coder]; if (self) { dataSounrce = [NSMutableArray array]; _keys = [NSMutableArray array]; } return self; } - (void)viewWillAppear:(BOOL)animated{ if([Global getInstance].isPaySuccessed == YES || [Global getInstance].isWithdrawSuccessed == YES) { NSString * accountId = [Global getInstance].currentAccountId; NSDictionary * post = @{@"accountId":accountId}; NSMutableDictionary * postData = [post mutableCopy]; [NetRequest POST:GET_ACCOUNT_RECORD parameters:postData atView:self.view andHUDMessage:@"获取中.." success:^(id resposeObject) { NSMutableDictionary * result = resposeObject[@"account"]; [self setData:result]; } failure:^(NSError *error) { NSLog(@"报错"); }]; } } - (void)viewDidLoad { [super viewDidLoad]; moneyButton.userInteractionEnabled =NO; accountTableView.rowHeight = 56; accountTableView.tableFooterView = [UIView new]; hasMoneyText.text = hasMoney; } - (IBAction)rechargeHandler:(id)sender { //充值; NSLog(@"充值"); RechargeViewController * rechargeVC = [[UIStoryboard storyboardWithName:@"PayAccount" bundle:nil] instantiateViewControllerWithIdentifier:@"recharge"]; [self.navigationController pushViewController:rechargeVC animated:YES]; } - (IBAction)withdrawalsHandler:(id)sender { //提现; NSLog(@"提现"); WithdrawViewController * withdrawVC = [[UIStoryboard storyboardWithName:@"PayAccount" bundle:nil] instantiateViewControllerWithIdentifier:@"withdraw"]; [withdrawVC setHasMoney:moneyFloatView]; [self.navigationController pushViewController:withdrawVC animated:YES]; } - (void)setData:(NSMutableDictionary*)data{ NSNumber * haveMoney = [data objectForKey:@"accountBalance"]; moneyFloatView = [NSString stringWithFormat:@"%.2lf",haveMoney.floatValue]; NSString * money = [NSString stringWithFormat:@"(%.2lf元)",haveMoney.floatValue]; hasMoney = money; [Global getInstance].currentAccountId = [data objectForKey:@"accountId"]; NSMutableArray *list = [data objectForKey:@"payList"]; NSMutableString * oldTime = [NSMutableString stringWithString:@""]; for(NSInteger i = 0;i < list.count;i++) { NSMutableDictionary * dic = list[i]; NSString * currentTime = [Global getSimpleDateByTime:[dic objectForKey:@"finishTime"]]; if([currentTime compare:oldTime] != 0) { [_keys addObject:currentTime]; } oldTime = [NSMutableString stringWithString:currentTime]; } for(NSInteger i = 0;i < _keys.count;i++) { NSString * time = _keys[i]; NSMutableArray * array = [NSMutableArray array]; for(NSInteger j = 0;j < list.count;j++) { NSMutableDictionary * dic = list[j]; NSString * currentTime = [Global getSimpleDateByTime:[dic objectForKey:@"finishTime"]]; if([time compare:currentTime] == 0) { [array addObject:dic]; } } [dataSounrce addObject:array]; } [accountTableView reloadData]; } #pragma mark -- UITableViewDataSource - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSMutableArray * currentData = dataSounrce[section]; return currentData.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *identifier = @"accountRecordCell"; AccountRecordTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier]; if(!cell) { cell = [[AccountRecordTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier]; } NSMutableDictionary * currentData = dataSounrce[indexPath.section][indexPath.row]; NSString * payType = [currentData objectForKey:@"payFor"]; NSString * addOrSub; NSString * title; NSString * address = @""; switch(payType.integerValue) { case 1: //充值; addOrSub = @"+"; title = @"充值"; break; case 2: //场地费; addOrSub = @"-"; title = @"场地费支付"; address = [currentData objectForKey:@"address"]; break; case 3: //提现; addOrSub = @"-"; title = @"提现"; break; } NSNumber * money = [currentData objectForKey:@"payAmount"]; NSString * moneyStr = [NSString stringWithFormat:@"%@ %.2lf元",addOrSub,money.floatValue]; cell.moneyLabel.text = moneyStr; cell.titleLabel.text = title; NSString * time = [Global getDateByTime:[currentData objectForKey:@"finishTime"] isSimple:NO]; NSString * timeAndAddress; if(address.length > 0) { timeAndAddress = [NSString stringWithFormat:@"%@\n%@",address,time]; }else{ timeAndAddress = [NSString stringWithFormat:@"%@",time]; } cell.timeLabel.text = timeAndAddress; return cell; } //返回组数 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [_keys count]; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return _keys[section]; } #pragma mark -- UITableViewDelegate @end
{ "content_hash": "c2a3bf1a126cd4ed5bad22cfa8049f34", "timestamp": "", "source": "github", "line_count": 198, "max_line_length": 155, "avg_line_length": 29.828282828282827, "alnum_prop": 0.6388418557399255, "repo_name": "LinusStark/iSoccer", "id": "1df301d63db09f5439444b75dc615eb1be9b6f67", "size": "6327", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "iSoccer/PayAccountViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "4555" }, { "name": "Objective-C", "bytes": "1174903" }, { "name": "Objective-C++", "bytes": "1967" }, { "name": "Ruby", "bytes": "369" } ], "symlink_target": "" }
from telemetry import multi_page_benchmark from telemetry import util MEMORY_HISTOGRAMS = [ {'name': 'V8.MemoryExternalFragmentationTotal', 'units': 'percent'}, {'name': 'V8.MemoryHeapSampleTotalCommitted', 'units': 'kb'}, {'name': 'V8.MemoryHeapSampleTotalUsed', 'units': 'kb'}] class PageCycler(multi_page_benchmark.MultiPageBenchmark): def CustomizeBrowserOptions(self, options): options.AppendExtraBrowserArg('--dom-automation') options.AppendExtraBrowserArg('--js-flags=--expose_gc') def MeasurePage(self, _, tab, results): def _IsDone(): return tab.GetCookieByName('__pc_done') == '1' util.WaitFor(_IsDone, 1200, poll_interval=5) print 'Pages: [%s]' % tab.GetCookieByName('__pc_pages') # TODO(tonyg): Get IO and memory statistics. for histogram in MEMORY_HISTOGRAMS: name = histogram['name'] data = tab.EvaluateJavaScript( 'window.domAutomationController.getHistogram("%s")' % name) results.Add(name, histogram['units'], data, data_type='histogram') def _IsNavigatedToReport(): return tab.GetCookieByName('__navigated_to_report') == '1' util.WaitFor(_IsNavigatedToReport, 60, poll_interval=5) timings = tab.EvaluateJavaScript('__get_timings()').split(',') results.Add('t', 'ms', [int(t) for t in timings], chart_name='times') # TODO(tonyg): Add version that runs with extension profile.
{ "content_hash": "d24117bdcacad441dc2b2d33646e4397", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 73, "avg_line_length": 41.1764705882353, "alnum_prop": 0.6857142857142857, "repo_name": "nacl-webkit/chrome_deps", "id": "04f15347febbf83fe1a66493a8f3747982206f30", "size": "1567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/perf/perf_tools/page_cycler.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "1173441" }, { "name": "Awk", "bytes": "9519" }, { "name": "C", "bytes": "74568368" }, { "name": "C#", "bytes": "1132" }, { "name": "C++", "bytes": "156174457" }, { "name": "DOT", "bytes": "1559" }, { "name": "F#", "bytes": "381" }, { "name": "Java", "bytes": "3088381" }, { "name": "JavaScript", "bytes": "18179048" }, { "name": "Logos", "bytes": "4517" }, { "name": "M", "bytes": "2190" }, { "name": "Matlab", "bytes": "3044" }, { "name": "Objective-C", "bytes": "6965520" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "932725" }, { "name": "Python", "bytes": "8458718" }, { "name": "R", "bytes": "262" }, { "name": "Ragel in Ruby Host", "bytes": "3621" }, { "name": "Shell", "bytes": "1526176" }, { "name": "Tcl", "bytes": "277077" }, { "name": "XSLT", "bytes": "13493" } ], "symlink_target": "" }
package com.emc.documentum.rest.client.sample.model.json; import java.util.List; import java.util.Objects; import com.emc.documentum.rest.client.sample.client.util.Equals; import com.emc.documentum.rest.client.sample.model.VirtualDocumentNode; import com.fasterxml.jackson.annotation.JsonProperty; public class JsonVirtualDocumentNode extends JsonInlineLinkableBase implements VirtualDocumentNode { @JsonProperty("are-children-compound") private boolean areChildrenCompound; @JsonProperty("available-versions") private List<String> availableVersions; @JsonProperty("binding") private String binding; @JsonProperty("can-be-removed") private boolean canBeRemoved; @JsonProperty("can-be-restructured") private boolean canBeRestructured; @JsonProperty("child-count") private int childCount; @JsonProperty("chronicle-id") private String chronicleId; @JsonProperty("copy-behavior") private int copyBehavior; @JsonProperty("follow-assembly") private boolean followAssembly; @JsonProperty("node-id") private String nodeId; @JsonProperty("is-binding-broken") private boolean isBindingBroken; @JsonProperty("is-compound") private boolean isCompound; @JsonProperty("is-from-assembly") private boolean isFromAssembly; @JsonProperty("is-structurally-modified") private boolean isStructurallyModified; @JsonProperty("is-virtual-document") private boolean isVirtualDocument; @JsonProperty("late-binding-value") private String lateBindingValue; @JsonProperty("override-late-binding") private boolean overrideLateBinding; @JsonProperty("vdm-number") private String vdmNumber; @JsonProperty("selected-object-name") private String selectedObjectName; @JsonProperty("selected-object-id") private String selectedObjectId; @Override public List<String> getAvailableVersions() { return availableVersions; } public void setAvailableVersions(List<String> availableVersions) { this.availableVersions = availableVersions; } @Override public String getBinding() { return binding; } public void setBinding(String binding) { this.binding = binding; } @Override public int getChildCount() { return childCount; } public void setChildCount(int childCount) { this.childCount = childCount; } @Override public String getChronicleId() { return chronicleId; } public void setChronicleId(String chronicleId) { this.chronicleId = chronicleId; } @Override public int getCopyBehavior() { return copyBehavior; } public void setCopyBehavior(int copyBehavior) { this.copyBehavior = copyBehavior; } @Override public boolean isFollowAssembly() { return followAssembly; } public void setFollowAssembly(boolean followAssembly) { this.followAssembly = followAssembly; } @Override public String getNodeId() { return nodeId; } public void setNodeId(String id) { this.nodeId = id; } @Override public String getLateBindingValue() { return lateBindingValue; } public void setLateBindingValue(String lateBindingValue) { this.lateBindingValue = lateBindingValue; } @Override public boolean isOverrideLateBinding() { return overrideLateBinding; } public void setOverrideLateBinding(boolean overrideLateBinding) { this.overrideLateBinding = overrideLateBinding; } @Override public String getVdmNumber() { return vdmNumber; } public void setVdmNumber(String vdmNumber) { this.vdmNumber = vdmNumber; } @Override public boolean isAreChildrenCompound() { return areChildrenCompound; } public void setAreChildrenCompound(boolean areChildrenCompound) { this.areChildrenCompound = areChildrenCompound; } @Override public boolean isCanBeRemoved() { return canBeRemoved; } public void setCanBeRemoved(boolean canBeRemoved) { this.canBeRemoved = canBeRemoved; } @Override public boolean isCanBeRestructured() { return canBeRestructured; } public void setCanBeRestructured(boolean canBeRestructured) { this.canBeRestructured = canBeRestructured; } @Override public boolean isBindingBroken() { return isBindingBroken; } public void setBindingBroken(boolean isBindingBroken) { this.isBindingBroken = isBindingBroken; } @Override public boolean isCompound() { return isCompound; } public void setCompound(boolean isCompound) { this.isCompound = isCompound; } @Override public boolean isFromAssembly() { return isFromAssembly; } public void setFromAssembly(boolean isFromAssembly) { this.isFromAssembly = isFromAssembly; } @Override public boolean isStructurallyModified() { return isStructurallyModified; } public void setStructurallyModified(boolean isStructurallyModified) { this.isStructurallyModified = isStructurallyModified; } @Override public boolean isVirtualDocument() { return isVirtualDocument; } public void setVirtualDocument(boolean isVirtualDocument) { this.isVirtualDocument = isVirtualDocument; } @Override public String getSelectedObjectName() { return selectedObjectName; } public void setSelectedObjectName(String selectedObjectName) { this.selectedObjectName = selectedObjectName; } @Override public String getSelectedObjectId() { return selectedObjectId; } public void setSelectedObjectId(String selectedObjectId) { this.selectedObjectId = selectedObjectId; } @Override public boolean equals(Object obj) { JsonVirtualDocumentNode that = (JsonVirtualDocumentNode) obj; return Equals.equal(areChildrenCompound, that.areChildrenCompound) && Equals.equal(availableVersions, that.availableVersions) && Equals.equal(binding, that.binding) && Equals.equal(canBeRemoved, that.canBeRemoved) && Equals.equal(canBeRestructured, that.canBeRestructured) && Equals.equal(childCount, that.childCount) && Equals.equal(chronicleId, that.chronicleId) && Equals.equal(copyBehavior, that.copyBehavior) && Equals.equal(followAssembly, that.followAssembly) && Equals.equal(nodeId, that.nodeId) && Equals.equal(isBindingBroken, that.isBindingBroken) && Equals.equal(isCompound, that.isCompound) && Equals.equal(isFromAssembly, that.isFromAssembly) && Equals.equal(isStructurallyModified, that.isStructurallyModified) && Equals.equal(isVirtualDocument, that.isVirtualDocument) && Equals.equal(lateBindingValue, that.lateBindingValue) && Equals.equal(overrideLateBinding, that.overrideLateBinding) && Equals.equal(vdmNumber, that.vdmNumber) && Equals.equal(selectedObjectName, that.selectedObjectName) && Equals.equal(selectedObjectId, that.selectedObjectId) && super.equals(obj); } @Override public int hashCode() { return Objects.hash(nodeId, vdmNumber, selectedObjectId); } }
{ "content_hash": "b1bcfb6839d53574181df029808445d2", "timestamp": "", "source": "github", "line_count": 263, "max_line_length": 100, "avg_line_length": 28.91254752851711, "alnum_prop": 0.67859021567596, "repo_name": "Enterprise-Content-Management/documentum-rest-client-java", "id": "30605d8b8a2f404b4f2be144d652aa5d8bbc1fd6", "size": "7677", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/emc/documentum/rest/client/sample/model/json/JsonVirtualDocumentNode.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "935131" } ], "symlink_target": "" }
using System; using System.Collections; using System.Collections.Generic; namespace Plethora.Collections { public class ListIndexIterator<T> : IEnumerator<T>, IEnumerable<T>, ICollection<T> { #region Fields private readonly IList<T> list; private readonly int startIndex; private readonly int endIndex; private int currentIndex; private T current; #endregion #region Constructors public ListIndexIterator(IList<T> list, int startIndex, int count) { if (list == null) throw new ArgumentNullException(nameof(list)); if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, ResourceProvider.ArgMustBeGreaterThanEqualToZero(nameof(startIndex))); if (startIndex >= list.Count) throw new ArgumentOutOfRangeException(nameof(startIndex), ResourceProvider.ArgMustBeBetween(nameof(startIndex), "0", "list.Count")); if ((count < 0) || ((startIndex + count) > list.Count)) throw new ArgumentOutOfRangeException(nameof(count), ResourceProvider.ArgMustBeBetween(nameof(count), "0", "list.Count - startIndex")); this.list = list; this.startIndex = startIndex; this.endIndex = startIndex + count - 1; this.Reset(); } #endregion #region Implementation of IDisposable public void Dispose() { this.Reset(); } #endregion #region Implementation of IEnumerable IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region Implementation of IEnumerable<T> public IEnumerator<T> GetEnumerator() { return this; } #endregion #region Implementation of IEnumerator public bool MoveNext() { if (this.currentIndex == -1) this.currentIndex = this.startIndex; else this.currentIndex++; if ((this.currentIndex > this.endIndex) || (this.currentIndex > this.list.Count)) { this.current = default(T); return false; } this.current = this.list[this.currentIndex]; return true; } public void Reset() { this.currentIndex = -1; this.current = default(T); } object IEnumerator.Current { get { return this.Current; } } #endregion #region Implementation of IEnumerator<T> public T Current { get { return this.current; } } #endregion #region Implementation of ICollection<T> void ICollection<T>.Add(T item) { throw new InvalidOperationException(ResourceProvider.CollectionReadonly()); } void ICollection<T>.Clear() { throw new InvalidOperationException(ResourceProvider.CollectionReadonly()); } public bool Contains(T item) { for (int i = this.startIndex; i <= this.endIndex; i++) { if (EqualityComparer<T>.Default.Equals(this.list[i], item)) return true; } return false; } public void CopyTo(T[] array, int arrayIndex) { List<T> l = this.list as List<T>; if (l != null) { l.CopyTo( this.startIndex, array, arrayIndex, this.endIndex - this.startIndex + 1); } else { for (int i = this.startIndex; i <= this.endIndex; i++) { array[arrayIndex++] = this.list[i]; } } } public int Count { get { return this.endIndex - this.startIndex + 1; } } bool ICollection<T>.IsReadOnly { get { return true; } } bool ICollection<T>.Remove(T item) { throw new InvalidOperationException(ResourceProvider.CollectionReadonly()); } #endregion } }
{ "content_hash": "030ca29eb126cffbeeb9cc1df70d3919", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 102, "avg_line_length": 26.74137931034483, "alnum_prop": 0.4960240704921556, "repo_name": "mikebarker/Plethora.NET", "id": "fc6ef4605e81c587230497670fe64c7205f5321d", "size": "4655", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/Plethora.Common/Collections/ListIndexIterator.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "3169669" }, { "name": "Rich Text Format", "bytes": "48" }, { "name": "TSQL", "bytes": "23846" } ], "symlink_target": "" }
package sgml import ( "fmt" "io" "strings" texttemplate "text/template" "github.com/bytesparadise/libasciidoc/pkg/types" "github.com/pkg/errors" ) func (r *sgmlRenderer) renderList(ctx *context, l *types.List) (string, error) { switch l.Kind { case types.OrderedListKind: return r.renderOrderedList(ctx, l) case types.UnorderedListKind: return r.renderUnorderedList(ctx, l) case types.LabeledListKind: return r.renderLabeledList(ctx, l) case types.CalloutListKind: return r.renderCalloutList(ctx, l) default: return "", fmt.Errorf("unable to render list of kind '%s'", l.Kind) } } // ------------------------------------------------------- // Ordered Lists // ------------------------------------------------------- func (r *sgmlRenderer) renderOrderedList(ctx *context, l *types.List) (string, error) { content := &strings.Builder{} for _, element := range l.Elements { e, ok := element.(*types.OrderedListElement) if !ok { return "", errors.Errorf("unable to render ordered list element of type '%T'", element) } if err := r.renderOrderedListElement(ctx, content, e); err != nil { return "", errors.Wrap(err, "unable to render ordered list") } } roles, err := r.renderElementRoles(ctx, l.Attributes) if err != nil { return "", errors.Wrap(err, "unable to render ordered list roles") } style, err := getNumberingStyle(l) if err != nil { return "", errors.Wrap(err, "unable to render ordered list roles") } title, err := r.renderElementTitle(ctx, l.Attributes) if err != nil { return "", errors.Wrap(err, "unable to render callout list roles") } return r.execute(r.orderedList, struct { Context *context ID string Title string Roles string Style string ListStyle string Start string Content string Reversed bool }{ ID: r.renderElementID(l.Attributes), Title: title, Roles: roles, Style: style, ListStyle: r.numberingType(style), Start: l.Attributes.GetAsStringWithDefault(types.AttrStart, ""), Content: content.String(), Reversed: l.Attributes.HasOption("reversed"), }) } func getNumberingStyle(l *types.List) (string, error) { if s, found := l.Attributes.GetAsString(types.AttrStyle); found { return s, nil } e, ok := l.Elements[0].(*types.OrderedListElement) if !ok { return "", errors.Errorf("unable to render ordered list style based on element of type '%T'", l.Elements[0]) } return e.Style, nil } // this numbering style is only really relevant to HTML func (r *sgmlRenderer) numberingType(style string) string { switch style { case types.LowerAlpha: return `a` case types.UpperAlpha: return `A` case types.LowerRoman: return `i` case types.UpperRoman: return `I` default: return "" } } func (r *sgmlRenderer) renderOrderedListElement(ctx *context, w io.Writer, element *types.OrderedListElement) error { content, err := r.renderListElements(ctx, element.GetElements()) if err != nil { return errors.Wrap(err, "unable to render ordered list element content") } tmpl, err := r.orderedListElement() if err != nil { return errors.Wrap(err, "unable to load ordered list element template") } if err = tmpl.Execute(w, struct { Context *context Content string }{ Context: ctx, Content: string(content), }); err != nil { return errors.Wrap(err, "unable to render ordered list element") } return nil } // ------------------------------------------------------- // Unordered Lists // ------------------------------------------------------- func (r *sgmlRenderer) renderUnorderedList(ctx *context, l *types.List) (string, error) { // make sure nested elements are aware of that their rendering occurs within a list checkList := false if len(l.Elements) > 0 { e, ok := l.Elements[0].(*types.UnorderedListElement) if !ok { return "", errors.Errorf("unable to render unordered list element of type '%T'", l.Elements[0]) } if e.CheckStyle != types.NoCheck { checkList = true } } content := &strings.Builder{} for _, element := range l.Elements { if err := r.renderUnorderedListElement(ctx, content, element); err != nil { return "", errors.Wrap(err, "unable to render unordered list") } } roles, err := r.renderElementRoles(ctx, l.Attributes) if err != nil { return "", errors.Wrap(err, "unable to render unordered list roles") } title, err := r.renderElementTitle(ctx, l.Attributes) if err != nil { return "", errors.Wrap(err, "unable to render callout list roles") } return r.execute(r.unorderedList, struct { Context *context ID string Title string Roles string Style string Checklist bool Items []types.ListElement Content string }{ Context: ctx, ID: r.renderElementID(l.Attributes), Title: title, Checklist: checkList, Items: l.Elements, Content: content.String(), Roles: roles, Style: r.renderElementStyle(l.Attributes), }) } func (r *sgmlRenderer) renderUnorderedListElement(ctx *context, w io.Writer, element types.ListElement) error { content, err := r.renderListElements(ctx, element.GetElements()) if err != nil { return errors.Wrap(err, "unable to render unordered list element content") } tmpl, err := r.unorderedListElement() if err != nil { return errors.Wrap(err, "unable to load unordered list element template") } if err := tmpl.Execute(w, struct { Context *context Content string }{ Context: ctx, Content: string(content), }); err != nil { return errors.Wrap(err, "unable to render unordered list element") } return nil } // ------------------------------------------------------- // Labelled Lists // ------------------------------------------------------- func (r *sgmlRenderer) renderLabeledList(ctx *context, l *types.List) (string, error) { tmpl, itemTmpl, err := r.getLabeledListTmpl(l) if err != nil { return "", errors.Wrap(err, "unable to render labeled list") } content := &strings.Builder{} cont := false for _, element := range l.Elements { e, ok := element.(*types.LabeledListElement) if !ok { return "", errors.Errorf("unable to render labeled list element of type '%T'", element) } if cont, err = r.renderLabeledListItem(ctx, itemTmpl, content, cont, e); err != nil { return "", errors.Wrap(err, "unable to render labeled list") } } roles, err := r.renderElementRoles(ctx, l.Attributes) if err != nil { return "", errors.Wrap(err, "unable to render labeled list roles") } title, err := r.renderElementTitle(ctx, l.Attributes) if err != nil { return "", errors.Wrap(err, "unable to render labeled list roles") } result := &strings.Builder{} if err := tmpl.Execute(result, struct { Context *context ID string Title string Roles string Content string Items []types.ListElement }{ Context: ctx, ID: r.renderElementID(l.Attributes), Title: title, Roles: roles, Content: content.String(), Items: l.Elements, }); err != nil { return "", errors.Wrap(err, "unable to render labeled list") } return result.String(), nil } func (r *sgmlRenderer) getLabeledListTmpl(l *types.List) (*texttemplate.Template, *texttemplate.Template, error) { if layout, ok := l.Attributes[types.AttrStyle]; ok { switch layout { case "qanda": listTmpl, err := r.qAndAList() if err != nil { return nil, nil, errors.Wrap(err, "unable to load q&A list template") } listElementTmpl, err := r.qAndAListElement() if err != nil { return nil, nil, errors.Wrap(err, "unable to load q&A list element template") } return listTmpl, listElementTmpl, nil case "horizontal": listTmpl, err := r.labeledListHorizontal() if err != nil { return nil, nil, errors.Wrap(err, "unable to load horizontal list template") } listElementTmpl, err := r.labeledListHorizontalElement() if err != nil { return nil, nil, errors.Wrap(err, "unable to load horizontal list element template") } return listTmpl, listElementTmpl, nil default: return nil, nil, errors.Errorf("unsupported labeled list layout: %s", layout) } } listTmpl, err := r.labeledList() if err != nil { return nil, nil, errors.Wrap(err, "unable to load labeled list template") } listElementTmpl, err := r.labeledListElement() if err != nil { return nil, nil, errors.Wrap(err, "unable to load labeld list element template") } return listTmpl, listElementTmpl, nil } func (r *sgmlRenderer) renderLabeledListItem(ctx *context, tmpl *texttemplate.Template, w io.Writer, continuation bool, element *types.LabeledListElement) (bool, error) { term, err := r.renderInlineElements(ctx, element.Term) if err != nil { return false, errors.Wrap(err, "unable to render labeled list term") } content, err := r.renderListElements(ctx, element.Elements) if err != nil { return false, errors.Wrap(err, "unable to render labeled list content") } err = tmpl.Execute(w, struct { Context *context Term string Content string Continuation bool }{ Context: ctx, Term: string(term), Continuation: continuation, Content: string(content), }) return content == "", err } // ------------------------------------------------------- // Callout Lists // ------------------------------------------------------- func (r *sgmlRenderer) renderCalloutList(ctx *context, l *types.List) (string, error) { content := &strings.Builder{} for _, element := range l.Elements { e, ok := element.(*types.CalloutListElement) if !ok { return "", errors.Errorf("unable to render callout list element of type '%T'", element) } rendererElement, err := r.renderCalloutListElement(ctx, e) if err != nil { return "", errors.Wrap(err, "unable to render callout list element") } content.WriteString(rendererElement) } roles, err := r.renderElementRoles(ctx, l.Attributes) if err != nil { return "", errors.Wrap(err, "unable to render callout list roles") } title, err := r.renderElementTitle(ctx, l.Attributes) if err != nil { return "", errors.Wrap(err, "unable to render callout list roles") } return r.execute(r.calloutList, struct { Context *context ID string Title string Roles string Content string Items []types.ListElement }{ Context: ctx, ID: r.renderElementID(l.Attributes), Title: title, Roles: roles, Content: content.String(), Items: l.Elements, }) } func (r *sgmlRenderer) renderCalloutListElement(ctx *context, element *types.CalloutListElement) (string, error) { content, err := r.renderListElements(ctx, element.Elements) if err != nil { return "", errors.Wrap(err, "unable to render callout list element content") } return r.execute(r.calloutListElement, struct { Context *context Ref int Content string }{ Context: ctx, Ref: element.Ref, Content: string(content), }) }
{ "content_hash": "245ffb7c6d093cf47a74698c566fc309", "timestamp": "", "source": "github", "line_count": 362, "max_line_length": 170, "avg_line_length": 30.04696132596685, "alnum_prop": 0.6522938310195826, "repo_name": "bytesparadise/libasciidoc", "id": "3cf5c624c36e465011d1f7d7b052de6ef1c13e24", "size": "10877", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pkg/renderer/sgml/list.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "2135178" }, { "name": "HTML", "bytes": "35739" }, { "name": "Makefile", "bytes": "9435" } ], "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> <parent> <groupId>com.github.scribejava</groupId> <artifactId>scribejava</artifactId> <version>6.5.2-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <groupId>com.github.scribejava</groupId> <artifactId>scribejava-apis</artifactId> <name>ScribeJava APIs</name> <packaging>jar</packaging> <dependencies> <dependency> <groupId>com.github.scribejava</groupId> <artifactId>scribejava-core</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>com.github.scribejava</groupId> <artifactId>scribejava-httpclient-ahc</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>com.github.scribejava</groupId> <artifactId>scribejava-httpclient-ning</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>com.github.scribejava</groupId> <artifactId>scribejava-httpclient-okhttp</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>com.github.scribejava</groupId> <artifactId>scribejava-httpclient-apache</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> </plugin> </plugins> </build> </project>
{ "content_hash": "fcbdc801277425f45b8fdf5f964a5503", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 204, "avg_line_length": 36.950819672131146, "alnum_prop": 0.5891748003549245, "repo_name": "fernandezpablo85/scribe-java", "id": "fbcbf7f41d32d7d63c12cb4e51824cb76e2fbb57", "size": "2254", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scribejava-apis/pom.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "381851" } ], "symlink_target": "" }
This is the tool used to create those awesome Color Wheels available at https://twitter.com/gamecolorwheel, https://www.instagram.com/gamecolorwheel and https://www.facebook.com/gamecolorwheel. Just go crazy with it. ## Instructions 1. [Download](https://github.com/Josephblt/GameColorWheelCreator/releases/download/1.1/GameColorWheelCreator.exe) 2. Run 3. Have fun!
{ "content_hash": "c0998fe658c5389d42626beb060d82ac", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 216, "avg_line_length": 61.333333333333336, "alnum_prop": 0.7989130434782609, "repo_name": "Josephblt/GameColorWheelCreator", "id": "bd35058754dcb0f5c8b9998b4189791a9421ba8f", "size": "395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "22573" } ], "symlink_target": "" }
package debop4s.core.reflect; import com.google.common.collect.Lists; import debop4s.core.Guard; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.List; /** * AccessClassLoader * * @author 배성혁 ( sunghyouk.bae@gmail.com ) * @since 13. 1. 21 */ class AccessClassLoader extends ClassLoader { private static final Logger log = LoggerFactory.getLogger(AccessClassLoader.class); private static final List<AccessClassLoader> accessClassLoaders = Lists.newArrayList(); /** AccessClassLoger를 생성합니다. */ static AccessClassLoader get(final Class type) { log.trace("AccessClassLoader를 생성합니다. kind=[{}]", type); ClassLoader parent = type.getClassLoader(); // com.google.common.collect.Iterables 를 사용하여 변경해 보세요. synchronized (accessClassLoaders) { for (AccessClassLoader loader : accessClassLoaders) { if (loader.getParent() == parent) return loader; } AccessClassLoader loader = new AccessClassLoader(parent); accessClassLoaders.add(loader); return loader; } } private AccessClassLoader(ClassLoader parent) { super(parent); } protected synchronized Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException { Guard.shouldNotBeEmpty(name, "name"); if (name.equals(FieldAccess.class.getName())) return FieldAccess.class; if (name.equals(MethodAccess.class.getName())) return MethodAccess.class; if (name.equals(ConstructorAccess.class.getName())) return ConstructorAccess.class; // all other classes come from the ClassLoader return super.loadClass(name, resolve); } Class<?> defineClass(final String name, final byte[] bytes) throws ClassFormatError { Guard.shouldNotBeEmpty(name, "name"); Guard.shouldNotBeNull(bytes, "bytes"); try { Method method = ClassLoader.class .getDeclaredMethod("defineClass", new Class[] { String.class, byte[].class, int.class, int.class }); method.setAccessible(true); // NOTE: 꼭 Integer.valueOf() 를 써야 합니다. // return (Class) method.invoke(getParent(), name, bytes, Integer.valueOf(0), Integer.valueOf(bytes.length)); } catch (Exception ignored) { } return defineClass(name, bytes, 0, bytes.length); } }
{ "content_hash": "336183d5a9fe8b3e77680234976ea128", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 119, "avg_line_length": 35.63380281690141, "alnum_prop": 0.6466403162055336, "repo_name": "debop/debop4s", "id": "13e087c73afb6b03681b597120ce9c0f6cd0f408", "size": "2596", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "debop4s-core/src/main/scala/debop4s/core/reflect/AccessClassLoader.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "888295" }, { "name": "Scala", "bytes": "2466233" } ], "symlink_target": "" }
package com.pentaho.big.data.bundles.impl.shim.hdfs; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsAction; import org.apache.hadoop.fs.permission.FsPermission; import org.junit.Before; import org.junit.Test; import org.pentaho.bigdata.api.hdfs.HadoopFileStatus; import org.pentaho.bigdata.api.hdfs.HadoopFileSystemPath; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Created by bryan on 8/3/15. */ public class HadoopFileSystemImplTest { private FileSystem fileSystem; private HadoopFileSystemImpl hadoopFileSystem; private HadoopFileSystemPath hadoopFileSystemPath; private FSDataOutputStream outputStream; private String pathString; private FSDataInputStream inputStream; private HadoopFileSystemPath hadoopFileSystemPath2; private String pathString2; private Configuration configuration; @Before public void setup() { fileSystem = mock( FileSystem.class ); configuration = mock( Configuration.class ); when( fileSystem.getConf() ).thenReturn( configuration ); hadoopFileSystem = new HadoopFileSystemImpl( fileSystem ); outputStream = mock( FSDataOutputStream.class ); inputStream = mock( FSDataInputStream.class ); hadoopFileSystemPath = mock( HadoopFileSystemPath.class ); hadoopFileSystemPath2 = mock( HadoopFileSystemPath.class ); pathString = "test/path"; pathString2 = "test/path2"; when( hadoopFileSystemPath.getPath() ).thenReturn( pathString ); when( hadoopFileSystemPath2.getPath() ).thenReturn( pathString2 ); } @Test public void testAppend() throws IOException { when( fileSystem.append( eq( new Path( pathString ) ) ) ).thenReturn( outputStream ); assertEquals( outputStream, hadoopFileSystem.append( hadoopFileSystemPath ) ); } @Test public void testCreate() throws IOException { when( fileSystem.create( eq( new Path( pathString ) ) ) ).thenReturn( outputStream ); assertEquals( outputStream, hadoopFileSystem.create( hadoopFileSystemPath ) ); } @Test public void testDelete() throws IOException { when( fileSystem.delete( eq( new Path( pathString ) ), eq( false ) ) ).thenReturn( true ).thenReturn( false ); assertEquals( true, hadoopFileSystem.delete( hadoopFileSystemPath, false ) ); assertEquals( false, hadoopFileSystem.delete( hadoopFileSystemPath, false ) ); } @Test public void testGetFileStatus() throws IOException { FileStatus fileStatus = mock( FileStatus.class ); long len = 12345L; when( fileStatus.getLen() ).thenReturn( len ); when( fileSystem.getFileStatus( eq( new Path( pathString ) ) ) ).thenReturn( fileStatus ); assertEquals( len, hadoopFileSystem.getFileStatus( hadoopFileSystemPath ).getLen() ); } @Test public void testMkdirs() throws IOException { when( fileSystem.mkdirs( eq( new Path( pathString ) ) ) ).thenReturn( true ).thenReturn( false ); assertEquals( true, hadoopFileSystem.mkdirs( hadoopFileSystemPath ) ); assertEquals( false, hadoopFileSystem.mkdirs( hadoopFileSystemPath ) ); } @Test public void testOpen() throws IOException { when( fileSystem.open( eq( new Path( pathString ) ) ) ).thenReturn( inputStream ); assertEquals( inputStream, hadoopFileSystem.open( hadoopFileSystemPath ) ); } @Test public void testRename() throws IOException { when( fileSystem.rename( eq( new Path( pathString ) ), eq( new Path( pathString2 ) ) ) ).thenReturn( true ) .thenReturn( false ); assertEquals( true, hadoopFileSystem.rename( hadoopFileSystemPath, hadoopFileSystemPath2 ) ); assertEquals( false, hadoopFileSystem.rename( hadoopFileSystemPath, hadoopFileSystemPath2 ) ); } @Test public void testSetTimes() throws IOException { long mtime = 1L; long atime = 2L; hadoopFileSystem.setTimes( hadoopFileSystemPath, mtime, atime ); verify( fileSystem ).setTimes( eq( new Path( pathString ) ), eq( mtime ), eq( atime ) ); } @Test public void testListStatusNullStatuses() throws IOException { when( fileSystem.listStatus( eq( new Path( pathString ) ) ) ).thenReturn( null ); assertNull( hadoopFileSystem.listStatus( hadoopFileSystemPath ) ); } @Test public void testListStatus() throws IOException { FileStatus fileStatus = mock( FileStatus.class ); long len = 54321L; when( fileStatus.getLen() ).thenReturn( len ); when( fileSystem.listStatus( eq( new Path( pathString ) ) ) ).thenReturn( new FileStatus[] { fileStatus } ); HadoopFileStatus[] hadoopFileStatuses = hadoopFileSystem.listStatus( hadoopFileSystemPath ); assertEquals( 1, hadoopFileStatuses.length ); assertEquals( len, hadoopFileStatuses[ 0 ].getLen() ); } @Test public void testGetPath() { assertEquals( pathString, hadoopFileSystem.getPath( pathString ).getPath() ); } @Test public void testMakeQualified() { when( hadoopFileSystemPath.toString() ).thenReturn( pathString ); when( fileSystem.makeQualified( eq( new Path( pathString ) ) ) ).thenReturn( new Path( pathString2 ) ); assertEquals( pathString2, hadoopFileSystem.makeQualified( hadoopFileSystemPath ).getPath() ); } @Test( expected = IllegalArgumentException.class ) public void testChmodIllegalOwnerUp() throws IOException { hadoopFileSystem.chmod( hadoopFileSystemPath, 800 ); } @Test( expected = IllegalArgumentException.class ) public void testChmodIllegalOwnerDown() throws IOException { hadoopFileSystem.chmod( hadoopFileSystemPath, -100 ); } @Test( expected = IllegalArgumentException.class ) public void testChmodIllegalGroupUp() throws IOException { hadoopFileSystem.chmod( hadoopFileSystemPath, 80 ); } @Test( expected = IllegalArgumentException.class ) public void testChmodIllegalGroupDown() throws IOException { hadoopFileSystem.chmod( hadoopFileSystemPath, -10 ); } @Test( expected = IllegalArgumentException.class ) public void testChmodIllegalOtherUp() throws IOException { hadoopFileSystem.chmod( hadoopFileSystemPath, 8 ); } @Test( expected = IllegalArgumentException.class ) public void testChmodIllegalOtherDown() throws IOException { hadoopFileSystem.chmod( hadoopFileSystemPath, -1 ); } @Test public void testChmod() throws IOException { when( hadoopFileSystemPath.toString() ).thenReturn( pathString ); hadoopFileSystem.chmod( hadoopFileSystemPath, 753 ); verify( fileSystem ).setPermission( eq( new Path( pathString ) ), eq( new FsPermission( FsAction.ALL, FsAction.READ_EXECUTE, FsAction.WRITE_EXECUTE ) ) ); } @Test public void testExists() throws IOException { when( hadoopFileSystemPath.toString() ).thenReturn( pathString ); when( fileSystem.exists( eq( new Path( pathString ) ) ) ).thenReturn( true ).thenReturn( false ); assertTrue( hadoopFileSystem.exists( hadoopFileSystemPath ) ); assertFalse( hadoopFileSystem.exists( hadoopFileSystemPath ) ); } @Test public void testResolvePath() throws IOException { when( hadoopFileSystemPath.toString() ).thenReturn( pathString ); FileStatus fileStatus = mock( FileStatus.class ); when( fileStatus.getPath() ).thenReturn( new Path( pathString2 ) ); when( fileSystem.getFileStatus( eq( new Path( pathString ) ) ) ).thenReturn( fileStatus ); assertEquals( pathString2, hadoopFileSystem.resolvePath( hadoopFileSystemPath ).getPath() ); } @Test public void testGetFsDefaultName() { String value = "result"; String fake = "fake"; when( configuration.get( "fs.default.name" ) ).thenReturn( fake ); when( configuration.get( "fs.defaultFS", fake ) ).thenReturn( value ); assertEquals( value, hadoopFileSystem.getFsDefaultName() ); } @Test public void testGetProperty() throws Exception { String value = "value"; String defValue = "defValue"; String name = "name"; when( configuration.get( eq( name ) ) ).thenReturn( value ); when( configuration.get( eq( name ), eq( (String) null ) ) ).thenReturn( value ); when( configuration.get( eq( name ), eq( defValue ) ) ).thenReturn( defValue ); assertEquals( value, hadoopFileSystem.getProperty( name, null ) ); assertEquals( defValue, hadoopFileSystem.getProperty( name, defValue ) ); } @Test public void testSetProperty() throws Exception { String value = "value"; String name = "name"; hadoopFileSystem.setProperty( name, value ); verify( configuration ).set( name, value ); } }
{ "content_hash": "dd815978f3e24cad1268a75c1f481a07", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 114, "avg_line_length": 39.209606986899566, "alnum_prop": 0.730816349259383, "repo_name": "bytekast/big-data-plugin", "id": "9271942dd1f3e7cd55691945ae8c45b8a303bcab", "size": "9873", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "impl/shim/hdfs/src/test/java/com/pentaho/big/data/bundles/impl/shim/hdfs/HadoopFileSystemImplTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "3231395" }, { "name": "PigLatin", "bytes": "11262" } ], "symlink_target": "" }
package config import ( runtime "k8s.io/apimachinery/pkg/runtime" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ActiveDirectoryConfig) DeepCopyInto(out *ActiveDirectoryConfig) { *out = *in out.AllUsersQuery = in.AllUsersQuery if in.UserNameAttributes != nil { in, out := &in.UserNameAttributes, &out.UserNameAttributes *out = make([]string, len(*in)) copy(*out, *in) } if in.GroupMembershipAttributes != nil { in, out := &in.GroupMembershipAttributes, &out.GroupMembershipAttributes *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ActiveDirectoryConfig. func (in *ActiveDirectoryConfig) DeepCopy() *ActiveDirectoryConfig { if in == nil { return nil } out := new(ActiveDirectoryConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AdmissionConfig) DeepCopyInto(out *AdmissionConfig) { *out = *in if in.PluginConfig != nil { in, out := &in.PluginConfig, &out.PluginConfig *out = make(map[string]*AdmissionPluginConfig, len(*in)) for key, val := range *in { if val == nil { (*out)[key] = nil } else { (*out)[key] = new(AdmissionPluginConfig) val.DeepCopyInto((*out)[key]) } } } if in.PluginOrderOverride != nil { in, out := &in.PluginOrderOverride, &out.PluginOrderOverride *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AdmissionConfig. func (in *AdmissionConfig) DeepCopy() *AdmissionConfig { if in == nil { return nil } out := new(AdmissionConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AdmissionPluginConfig) DeepCopyInto(out *AdmissionPluginConfig) { *out = *in if in.Configuration == nil { out.Configuration = nil } else { out.Configuration = in.Configuration.DeepCopyObject() } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AdmissionPluginConfig. func (in *AdmissionPluginConfig) DeepCopy() *AdmissionPluginConfig { if in == nil { return nil } out := new(AdmissionPluginConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AggregatorConfig) DeepCopyInto(out *AggregatorConfig) { *out = *in out.ProxyClientInfo = in.ProxyClientInfo return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AggregatorConfig. func (in *AggregatorConfig) DeepCopy() *AggregatorConfig { if in == nil { return nil } out := new(AggregatorConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AllowAllPasswordIdentityProvider) DeepCopyInto(out *AllowAllPasswordIdentityProvider) { *out = *in out.TypeMeta = in.TypeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AllowAllPasswordIdentityProvider. func (in *AllowAllPasswordIdentityProvider) DeepCopy() *AllowAllPasswordIdentityProvider { if in == nil { return nil } out := new(AllowAllPasswordIdentityProvider) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *AllowAllPasswordIdentityProvider) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in AllowedRegistries) DeepCopyInto(out *AllowedRegistries) { { in := &in *out = make(AllowedRegistries, len(*in)) copy(*out, *in) return } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AllowedRegistries. func (in AllowedRegistries) DeepCopy() AllowedRegistries { if in == nil { return nil } out := new(AllowedRegistries) in.DeepCopyInto(out) return *out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AuditConfig) DeepCopyInto(out *AuditConfig) { *out = *in if in.PolicyConfiguration == nil { out.PolicyConfiguration = nil } else { out.PolicyConfiguration = in.PolicyConfiguration.DeepCopyObject() } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AuditConfig. func (in *AuditConfig) DeepCopy() *AuditConfig { if in == nil { return nil } out := new(AuditConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AugmentedActiveDirectoryConfig) DeepCopyInto(out *AugmentedActiveDirectoryConfig) { *out = *in out.AllUsersQuery = in.AllUsersQuery if in.UserNameAttributes != nil { in, out := &in.UserNameAttributes, &out.UserNameAttributes *out = make([]string, len(*in)) copy(*out, *in) } if in.GroupMembershipAttributes != nil { in, out := &in.GroupMembershipAttributes, &out.GroupMembershipAttributes *out = make([]string, len(*in)) copy(*out, *in) } out.AllGroupsQuery = in.AllGroupsQuery if in.GroupNameAttributes != nil { in, out := &in.GroupNameAttributes, &out.GroupNameAttributes *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AugmentedActiveDirectoryConfig. func (in *AugmentedActiveDirectoryConfig) DeepCopy() *AugmentedActiveDirectoryConfig { if in == nil { return nil } out := new(AugmentedActiveDirectoryConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *BasicAuthPasswordIdentityProvider) DeepCopyInto(out *BasicAuthPasswordIdentityProvider) { *out = *in out.TypeMeta = in.TypeMeta out.RemoteConnectionInfo = in.RemoteConnectionInfo return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BasicAuthPasswordIdentityProvider. func (in *BasicAuthPasswordIdentityProvider) DeepCopy() *BasicAuthPasswordIdentityProvider { if in == nil { return nil } out := new(BasicAuthPasswordIdentityProvider) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *BasicAuthPasswordIdentityProvider) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *BuildControllerConfig) DeepCopyInto(out *BuildControllerConfig) { *out = *in out.ImageTemplateFormat = in.ImageTemplateFormat if in.AdmissionPluginConfig != nil { in, out := &in.AdmissionPluginConfig, &out.AdmissionPluginConfig *out = make(map[string]*AdmissionPluginConfig, len(*in)) for key, val := range *in { if val == nil { (*out)[key] = nil } else { (*out)[key] = new(AdmissionPluginConfig) val.DeepCopyInto((*out)[key]) } } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildControllerConfig. func (in *BuildControllerConfig) DeepCopy() *BuildControllerConfig { if in == nil { return nil } out := new(BuildControllerConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CertInfo) DeepCopyInto(out *CertInfo) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertInfo. func (in *CertInfo) DeepCopy() *CertInfo { if in == nil { return nil } out := new(CertInfo) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ClientConnectionOverrides) DeepCopyInto(out *ClientConnectionOverrides) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClientConnectionOverrides. func (in *ClientConnectionOverrides) DeepCopy() *ClientConnectionOverrides { if in == nil { return nil } out := new(ClientConnectionOverrides) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ClusterNetworkEntry) DeepCopyInto(out *ClusterNetworkEntry) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterNetworkEntry. func (in *ClusterNetworkEntry) DeepCopy() *ClusterNetworkEntry { if in == nil { return nil } out := new(ClusterNetworkEntry) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ControllerConfig) DeepCopyInto(out *ControllerConfig) { *out = *in if in.Controllers != nil { in, out := &in.Controllers, &out.Controllers *out = make([]string, len(*in)) copy(*out, *in) } if in.Election != nil { in, out := &in.Election, &out.Election if *in == nil { *out = nil } else { *out = new(ControllerElectionConfig) **out = **in } } in.ServiceServingCert.DeepCopyInto(&out.ServiceServingCert) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControllerConfig. func (in *ControllerConfig) DeepCopy() *ControllerConfig { if in == nil { return nil } out := new(ControllerConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ControllerElectionConfig) DeepCopyInto(out *ControllerElectionConfig) { *out = *in out.LockResource = in.LockResource return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControllerElectionConfig. func (in *ControllerElectionConfig) DeepCopy() *ControllerElectionConfig { if in == nil { return nil } out := new(ControllerElectionConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DNSConfig) DeepCopyInto(out *DNSConfig) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNSConfig. func (in *DNSConfig) DeepCopy() *DNSConfig { if in == nil { return nil } out := new(DNSConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DefaultAdmissionConfig) DeepCopyInto(out *DefaultAdmissionConfig) { *out = *in out.TypeMeta = in.TypeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DefaultAdmissionConfig. func (in *DefaultAdmissionConfig) DeepCopy() *DefaultAdmissionConfig { if in == nil { return nil } out := new(DefaultAdmissionConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *DefaultAdmissionConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DenyAllPasswordIdentityProvider) DeepCopyInto(out *DenyAllPasswordIdentityProvider) { *out = *in out.TypeMeta = in.TypeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DenyAllPasswordIdentityProvider. func (in *DenyAllPasswordIdentityProvider) DeepCopy() *DenyAllPasswordIdentityProvider { if in == nil { return nil } out := new(DenyAllPasswordIdentityProvider) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *DenyAllPasswordIdentityProvider) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DeployerControllerConfig) DeepCopyInto(out *DeployerControllerConfig) { *out = *in out.ImageTemplateFormat = in.ImageTemplateFormat return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeployerControllerConfig. func (in *DeployerControllerConfig) DeepCopy() *DeployerControllerConfig { if in == nil { return nil } out := new(DeployerControllerConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DockerConfig) DeepCopyInto(out *DockerConfig) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DockerConfig. func (in *DockerConfig) DeepCopy() *DockerConfig { if in == nil { return nil } out := new(DockerConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DockerPullSecretControllerConfig) DeepCopyInto(out *DockerPullSecretControllerConfig) { *out = *in if in.RegistryURLs != nil { in, out := &in.RegistryURLs, &out.RegistryURLs *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DockerPullSecretControllerConfig. func (in *DockerPullSecretControllerConfig) DeepCopy() *DockerPullSecretControllerConfig { if in == nil { return nil } out := new(DockerPullSecretControllerConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *EtcdConfig) DeepCopyInto(out *EtcdConfig) { *out = *in in.ServingInfo.DeepCopyInto(&out.ServingInfo) in.PeerServingInfo.DeepCopyInto(&out.PeerServingInfo) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EtcdConfig. func (in *EtcdConfig) DeepCopy() *EtcdConfig { if in == nil { return nil } out := new(EtcdConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *EtcdConnectionInfo) DeepCopyInto(out *EtcdConnectionInfo) { *out = *in if in.URLs != nil { in, out := &in.URLs, &out.URLs *out = make([]string, len(*in)) copy(*out, *in) } out.ClientCert = in.ClientCert return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EtcdConnectionInfo. func (in *EtcdConnectionInfo) DeepCopy() *EtcdConnectionInfo { if in == nil { return nil } out := new(EtcdConnectionInfo) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *EtcdStorageConfig) DeepCopyInto(out *EtcdStorageConfig) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EtcdStorageConfig. func (in *EtcdStorageConfig) DeepCopy() *EtcdStorageConfig { if in == nil { return nil } out := new(EtcdStorageConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in ExtendedArguments) DeepCopyInto(out *ExtendedArguments) { { in := &in *out = make(ExtendedArguments, len(*in)) for key, val := range *in { if val == nil { (*out)[key] = nil } else { (*out)[key] = make([]string, len(val)) copy((*out)[key], val) } } return } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExtendedArguments. func (in ExtendedArguments) DeepCopy() ExtendedArguments { if in == nil { return nil } out := new(ExtendedArguments) in.DeepCopyInto(out) return *out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GitHubIdentityProvider) DeepCopyInto(out *GitHubIdentityProvider) { *out = *in out.TypeMeta = in.TypeMeta out.ClientSecret = in.ClientSecret if in.Organizations != nil { in, out := &in.Organizations, &out.Organizations *out = make([]string, len(*in)) copy(*out, *in) } if in.Teams != nil { in, out := &in.Teams, &out.Teams *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GitHubIdentityProvider. func (in *GitHubIdentityProvider) DeepCopy() *GitHubIdentityProvider { if in == nil { return nil } out := new(GitHubIdentityProvider) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *GitHubIdentityProvider) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GitLabIdentityProvider) DeepCopyInto(out *GitLabIdentityProvider) { *out = *in out.TypeMeta = in.TypeMeta out.ClientSecret = in.ClientSecret if in.Legacy != nil { in, out := &in.Legacy, &out.Legacy if *in == nil { *out = nil } else { *out = new(bool) **out = **in } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GitLabIdentityProvider. func (in *GitLabIdentityProvider) DeepCopy() *GitLabIdentityProvider { if in == nil { return nil } out := new(GitLabIdentityProvider) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *GitLabIdentityProvider) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GoogleIdentityProvider) DeepCopyInto(out *GoogleIdentityProvider) { *out = *in out.TypeMeta = in.TypeMeta out.ClientSecret = in.ClientSecret return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GoogleIdentityProvider. func (in *GoogleIdentityProvider) DeepCopy() *GoogleIdentityProvider { if in == nil { return nil } out := new(GoogleIdentityProvider) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *GoogleIdentityProvider) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GrantConfig) DeepCopyInto(out *GrantConfig) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GrantConfig. func (in *GrantConfig) DeepCopy() *GrantConfig { if in == nil { return nil } out := new(GrantConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GroupResource) DeepCopyInto(out *GroupResource) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GroupResource. func (in *GroupResource) DeepCopy() *GroupResource { if in == nil { return nil } out := new(GroupResource) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HPAControllerConfig) DeepCopyInto(out *HPAControllerConfig) { *out = *in out.SyncPeriod = in.SyncPeriod out.UpscaleForbiddenWindow = in.UpscaleForbiddenWindow out.DownscaleForbiddenWindow = in.DownscaleForbiddenWindow return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HPAControllerConfig. func (in *HPAControllerConfig) DeepCopy() *HPAControllerConfig { if in == nil { return nil } out := new(HPAControllerConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HTPasswdPasswordIdentityProvider) DeepCopyInto(out *HTPasswdPasswordIdentityProvider) { *out = *in out.TypeMeta = in.TypeMeta return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTPasswdPasswordIdentityProvider. func (in *HTPasswdPasswordIdentityProvider) DeepCopy() *HTPasswdPasswordIdentityProvider { if in == nil { return nil } out := new(HTPasswdPasswordIdentityProvider) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *HTPasswdPasswordIdentityProvider) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HTTPServingInfo) DeepCopyInto(out *HTTPServingInfo) { *out = *in in.ServingInfo.DeepCopyInto(&out.ServingInfo) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPServingInfo. func (in *HTTPServingInfo) DeepCopy() *HTTPServingInfo { if in == nil { return nil } out := new(HTTPServingInfo) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IdentityProvider) DeepCopyInto(out *IdentityProvider) { *out = *in if in.Provider == nil { out.Provider = nil } else { out.Provider = in.Provider.DeepCopyObject() } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IdentityProvider. func (in *IdentityProvider) DeepCopy() *IdentityProvider { if in == nil { return nil } out := new(IdentityProvider) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ImageConfig) DeepCopyInto(out *ImageConfig) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImageConfig. func (in *ImageConfig) DeepCopy() *ImageConfig { if in == nil { return nil } out := new(ImageConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ImageImportControllerConfig) DeepCopyInto(out *ImageImportControllerConfig) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImageImportControllerConfig. func (in *ImageImportControllerConfig) DeepCopy() *ImageImportControllerConfig { if in == nil { return nil } out := new(ImageImportControllerConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ImagePolicyConfig) DeepCopyInto(out *ImagePolicyConfig) { *out = *in if in.AllowedRegistriesForImport != nil { in, out := &in.AllowedRegistriesForImport, &out.AllowedRegistriesForImport if *in == nil { *out = nil } else { *out = new(AllowedRegistries) if **in != nil { in, out := *in, *out *out = make([]RegistryLocation, len(*in)) copy(*out, *in) } } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImagePolicyConfig. func (in *ImagePolicyConfig) DeepCopy() *ImagePolicyConfig { if in == nil { return nil } out := new(ImagePolicyConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IngressControllerConfig) DeepCopyInto(out *IngressControllerConfig) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressControllerConfig. func (in *IngressControllerConfig) DeepCopy() *IngressControllerConfig { if in == nil { return nil } out := new(IngressControllerConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *JenkinsPipelineConfig) DeepCopyInto(out *JenkinsPipelineConfig) { *out = *in if in.AutoProvisionEnabled != nil { in, out := &in.AutoProvisionEnabled, &out.AutoProvisionEnabled if *in == nil { *out = nil } else { *out = new(bool) **out = **in } } if in.Parameters != nil { in, out := &in.Parameters, &out.Parameters *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JenkinsPipelineConfig. func (in *JenkinsPipelineConfig) DeepCopy() *JenkinsPipelineConfig { if in == nil { return nil } out := new(JenkinsPipelineConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *KeystonePasswordIdentityProvider) DeepCopyInto(out *KeystonePasswordIdentityProvider) { *out = *in out.TypeMeta = in.TypeMeta out.RemoteConnectionInfo = in.RemoteConnectionInfo return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KeystonePasswordIdentityProvider. func (in *KeystonePasswordIdentityProvider) DeepCopy() *KeystonePasswordIdentityProvider { if in == nil { return nil } out := new(KeystonePasswordIdentityProvider) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *KeystonePasswordIdentityProvider) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *KubeletConnectionInfo) DeepCopyInto(out *KubeletConnectionInfo) { *out = *in out.ClientCert = in.ClientCert return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KubeletConnectionInfo. func (in *KubeletConnectionInfo) DeepCopy() *KubeletConnectionInfo { if in == nil { return nil } out := new(KubeletConnectionInfo) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *KubernetesMasterConfig) DeepCopyInto(out *KubernetesMasterConfig) { *out = *in if in.DisabledAPIGroupVersions != nil { in, out := &in.DisabledAPIGroupVersions, &out.DisabledAPIGroupVersions *out = make(map[string][]string, len(*in)) for key, val := range *in { if val == nil { (*out)[key] = nil } else { (*out)[key] = make([]string, len(val)) copy((*out)[key], val) } } } out.ProxyClientInfo = in.ProxyClientInfo if in.APIServerArguments != nil { in, out := &in.APIServerArguments, &out.APIServerArguments *out = make(ExtendedArguments, len(*in)) for key, val := range *in { if val == nil { (*out)[key] = nil } else { (*out)[key] = make([]string, len(val)) copy((*out)[key], val) } } } if in.ControllerArguments != nil { in, out := &in.ControllerArguments, &out.ControllerArguments *out = make(ExtendedArguments, len(*in)) for key, val := range *in { if val == nil { (*out)[key] = nil } else { (*out)[key] = make([]string, len(val)) copy((*out)[key], val) } } } if in.SchedulerArguments != nil { in, out := &in.SchedulerArguments, &out.SchedulerArguments *out = make(ExtendedArguments, len(*in)) for key, val := range *in { if val == nil { (*out)[key] = nil } else { (*out)[key] = make([]string, len(val)) copy((*out)[key], val) } } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KubernetesMasterConfig. func (in *KubernetesMasterConfig) DeepCopy() *KubernetesMasterConfig { if in == nil { return nil } out := new(KubernetesMasterConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LDAPAttributeMapping) DeepCopyInto(out *LDAPAttributeMapping) { *out = *in if in.ID != nil { in, out := &in.ID, &out.ID *out = make([]string, len(*in)) copy(*out, *in) } if in.PreferredUsername != nil { in, out := &in.PreferredUsername, &out.PreferredUsername *out = make([]string, len(*in)) copy(*out, *in) } if in.Name != nil { in, out := &in.Name, &out.Name *out = make([]string, len(*in)) copy(*out, *in) } if in.Email != nil { in, out := &in.Email, &out.Email *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LDAPAttributeMapping. func (in *LDAPAttributeMapping) DeepCopy() *LDAPAttributeMapping { if in == nil { return nil } out := new(LDAPAttributeMapping) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LDAPPasswordIdentityProvider) DeepCopyInto(out *LDAPPasswordIdentityProvider) { *out = *in out.TypeMeta = in.TypeMeta out.BindPassword = in.BindPassword in.Attributes.DeepCopyInto(&out.Attributes) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LDAPPasswordIdentityProvider. func (in *LDAPPasswordIdentityProvider) DeepCopy() *LDAPPasswordIdentityProvider { if in == nil { return nil } out := new(LDAPPasswordIdentityProvider) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *LDAPPasswordIdentityProvider) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LDAPQuery) DeepCopyInto(out *LDAPQuery) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LDAPQuery. func (in *LDAPQuery) DeepCopy() *LDAPQuery { if in == nil { return nil } out := new(LDAPQuery) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LDAPSyncConfig) DeepCopyInto(out *LDAPSyncConfig) { *out = *in out.TypeMeta = in.TypeMeta out.BindPassword = in.BindPassword if in.LDAPGroupUIDToOpenShiftGroupNameMapping != nil { in, out := &in.LDAPGroupUIDToOpenShiftGroupNameMapping, &out.LDAPGroupUIDToOpenShiftGroupNameMapping *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.RFC2307Config != nil { in, out := &in.RFC2307Config, &out.RFC2307Config if *in == nil { *out = nil } else { *out = new(RFC2307Config) (*in).DeepCopyInto(*out) } } if in.ActiveDirectoryConfig != nil { in, out := &in.ActiveDirectoryConfig, &out.ActiveDirectoryConfig if *in == nil { *out = nil } else { *out = new(ActiveDirectoryConfig) (*in).DeepCopyInto(*out) } } if in.AugmentedActiveDirectoryConfig != nil { in, out := &in.AugmentedActiveDirectoryConfig, &out.AugmentedActiveDirectoryConfig if *in == nil { *out = nil } else { *out = new(AugmentedActiveDirectoryConfig) (*in).DeepCopyInto(*out) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LDAPSyncConfig. func (in *LDAPSyncConfig) DeepCopy() *LDAPSyncConfig { if in == nil { return nil } out := new(LDAPSyncConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *LDAPSyncConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LeaderElectionConfig) DeepCopyInto(out *LeaderElectionConfig) { *out = *in out.LeaseDuration = in.LeaseDuration out.RenewDeadline = in.RenewDeadline out.RetryPeriod = in.RetryPeriod return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LeaderElectionConfig. func (in *LeaderElectionConfig) DeepCopy() *LeaderElectionConfig { if in == nil { return nil } out := new(LeaderElectionConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LocalQuota) DeepCopyInto(out *LocalQuota) { *out = *in if in.PerFSGroup != nil { in, out := &in.PerFSGroup, &out.PerFSGroup if *in == nil { *out = nil } else { x := (*in).DeepCopy() *out = &x } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LocalQuota. func (in *LocalQuota) DeepCopy() *LocalQuota { if in == nil { return nil } out := new(LocalQuota) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MasterAuthConfig) DeepCopyInto(out *MasterAuthConfig) { *out = *in if in.RequestHeader != nil { in, out := &in.RequestHeader, &out.RequestHeader if *in == nil { *out = nil } else { *out = new(RequestHeaderAuthenticationOptions) (*in).DeepCopyInto(*out) } } if in.WebhookTokenAuthenticators != nil { in, out := &in.WebhookTokenAuthenticators, &out.WebhookTokenAuthenticators *out = make([]WebhookTokenAuthenticator, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MasterAuthConfig. func (in *MasterAuthConfig) DeepCopy() *MasterAuthConfig { if in == nil { return nil } out := new(MasterAuthConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MasterClients) DeepCopyInto(out *MasterClients) { *out = *in if in.OpenShiftLoopbackClientConnectionOverrides != nil { in, out := &in.OpenShiftLoopbackClientConnectionOverrides, &out.OpenShiftLoopbackClientConnectionOverrides if *in == nil { *out = nil } else { *out = new(ClientConnectionOverrides) **out = **in } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MasterClients. func (in *MasterClients) DeepCopy() *MasterClients { if in == nil { return nil } out := new(MasterClients) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MasterConfig) DeepCopyInto(out *MasterConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ServingInfo.DeepCopyInto(&out.ServingInfo) in.AuthConfig.DeepCopyInto(&out.AuthConfig) out.AggregatorConfig = in.AggregatorConfig if in.CORSAllowedOrigins != nil { in, out := &in.CORSAllowedOrigins, &out.CORSAllowedOrigins *out = make([]string, len(*in)) copy(*out, *in) } if in.APILevels != nil { in, out := &in.APILevels, &out.APILevels *out = make([]string, len(*in)) copy(*out, *in) } in.AdmissionConfig.DeepCopyInto(&out.AdmissionConfig) in.ControllerConfig.DeepCopyInto(&out.ControllerConfig) out.EtcdStorageConfig = in.EtcdStorageConfig in.EtcdClientInfo.DeepCopyInto(&out.EtcdClientInfo) out.KubeletClientInfo = in.KubeletClientInfo in.KubernetesMasterConfig.DeepCopyInto(&out.KubernetesMasterConfig) if in.EtcdConfig != nil { in, out := &in.EtcdConfig, &out.EtcdConfig if *in == nil { *out = nil } else { *out = new(EtcdConfig) (*in).DeepCopyInto(*out) } } if in.OAuthConfig != nil { in, out := &in.OAuthConfig, &out.OAuthConfig if *in == nil { *out = nil } else { *out = new(OAuthConfig) (*in).DeepCopyInto(*out) } } if in.DNSConfig != nil { in, out := &in.DNSConfig, &out.DNSConfig if *in == nil { *out = nil } else { *out = new(DNSConfig) **out = **in } } in.ServiceAccountConfig.DeepCopyInto(&out.ServiceAccountConfig) in.MasterClients.DeepCopyInto(&out.MasterClients) out.ImageConfig = in.ImageConfig in.ImagePolicyConfig.DeepCopyInto(&out.ImagePolicyConfig) in.PolicyConfig.DeepCopyInto(&out.PolicyConfig) in.ProjectConfig.DeepCopyInto(&out.ProjectConfig) out.RoutingConfig = in.RoutingConfig in.NetworkConfig.DeepCopyInto(&out.NetworkConfig) out.VolumeConfig = in.VolumeConfig in.JenkinsPipelineConfig.DeepCopyInto(&out.JenkinsPipelineConfig) in.AuditConfig.DeepCopyInto(&out.AuditConfig) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MasterConfig. func (in *MasterConfig) DeepCopy() *MasterConfig { if in == nil { return nil } out := new(MasterConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *MasterConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MasterNetworkConfig) DeepCopyInto(out *MasterNetworkConfig) { *out = *in if in.ClusterNetworks != nil { in, out := &in.ClusterNetworks, &out.ClusterNetworks *out = make([]ClusterNetworkEntry, len(*in)) copy(*out, *in) } if in.ExternalIPNetworkCIDRs != nil { in, out := &in.ExternalIPNetworkCIDRs, &out.ExternalIPNetworkCIDRs *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MasterNetworkConfig. func (in *MasterNetworkConfig) DeepCopy() *MasterNetworkConfig { if in == nil { return nil } out := new(MasterNetworkConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MasterVolumeConfig) DeepCopyInto(out *MasterVolumeConfig) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MasterVolumeConfig. func (in *MasterVolumeConfig) DeepCopy() *MasterVolumeConfig { if in == nil { return nil } out := new(MasterVolumeConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NamedCertificate) DeepCopyInto(out *NamedCertificate) { *out = *in if in.Names != nil { in, out := &in.Names, &out.Names *out = make([]string, len(*in)) copy(*out, *in) } out.CertInfo = in.CertInfo return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NamedCertificate. func (in *NamedCertificate) DeepCopy() *NamedCertificate { if in == nil { return nil } out := new(NamedCertificate) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NetworkControllerConfig) DeepCopyInto(out *NetworkControllerConfig) { *out = *in if in.ClusterNetworks != nil { in, out := &in.ClusterNetworks, &out.ClusterNetworks *out = make([]ClusterNetworkEntry, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NetworkControllerConfig. func (in *NetworkControllerConfig) DeepCopy() *NetworkControllerConfig { if in == nil { return nil } out := new(NetworkControllerConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NodeAuthConfig) DeepCopyInto(out *NodeAuthConfig) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeAuthConfig. func (in *NodeAuthConfig) DeepCopy() *NodeAuthConfig { if in == nil { return nil } out := new(NodeAuthConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NodeConfig) DeepCopyInto(out *NodeConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ServingInfo.DeepCopyInto(&out.ServingInfo) if in.MasterClientConnectionOverrides != nil { in, out := &in.MasterClientConnectionOverrides, &out.MasterClientConnectionOverrides if *in == nil { *out = nil } else { *out = new(ClientConnectionOverrides) **out = **in } } if in.DNSNameservers != nil { in, out := &in.DNSNameservers, &out.DNSNameservers *out = make([]string, len(*in)) copy(*out, *in) } out.NetworkConfig = in.NetworkConfig out.ImageConfig = in.ImageConfig if in.PodManifestConfig != nil { in, out := &in.PodManifestConfig, &out.PodManifestConfig if *in == nil { *out = nil } else { *out = new(PodManifestConfig) **out = **in } } out.AuthConfig = in.AuthConfig out.DockerConfig = in.DockerConfig if in.KubeletArguments != nil { in, out := &in.KubeletArguments, &out.KubeletArguments *out = make(ExtendedArguments, len(*in)) for key, val := range *in { if val == nil { (*out)[key] = nil } else { (*out)[key] = make([]string, len(val)) copy((*out)[key], val) } } } if in.ProxyArguments != nil { in, out := &in.ProxyArguments, &out.ProxyArguments *out = make(ExtendedArguments, len(*in)) for key, val := range *in { if val == nil { (*out)[key] = nil } else { (*out)[key] = make([]string, len(val)) copy((*out)[key], val) } } } in.VolumeConfig.DeepCopyInto(&out.VolumeConfig) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeConfig. func (in *NodeConfig) DeepCopy() *NodeConfig { if in == nil { return nil } out := new(NodeConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *NodeConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NodeNetworkConfig) DeepCopyInto(out *NodeNetworkConfig) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeNetworkConfig. func (in *NodeNetworkConfig) DeepCopy() *NodeNetworkConfig { if in == nil { return nil } out := new(NodeNetworkConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NodeVolumeConfig) DeepCopyInto(out *NodeVolumeConfig) { *out = *in in.LocalQuota.DeepCopyInto(&out.LocalQuota) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeVolumeConfig. func (in *NodeVolumeConfig) DeepCopy() *NodeVolumeConfig { if in == nil { return nil } out := new(NodeVolumeConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *OAuthConfig) DeepCopyInto(out *OAuthConfig) { *out = *in if in.MasterCA != nil { in, out := &in.MasterCA, &out.MasterCA if *in == nil { *out = nil } else { *out = new(string) **out = **in } } if in.IdentityProviders != nil { in, out := &in.IdentityProviders, &out.IdentityProviders *out = make([]IdentityProvider, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } out.GrantConfig = in.GrantConfig if in.SessionConfig != nil { in, out := &in.SessionConfig, &out.SessionConfig if *in == nil { *out = nil } else { *out = new(SessionConfig) **out = **in } } in.TokenConfig.DeepCopyInto(&out.TokenConfig) if in.Templates != nil { in, out := &in.Templates, &out.Templates if *in == nil { *out = nil } else { *out = new(OAuthTemplates) **out = **in } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OAuthConfig. func (in *OAuthConfig) DeepCopy() *OAuthConfig { if in == nil { return nil } out := new(OAuthConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *OAuthTemplates) DeepCopyInto(out *OAuthTemplates) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OAuthTemplates. func (in *OAuthTemplates) DeepCopy() *OAuthTemplates { if in == nil { return nil } out := new(OAuthTemplates) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *OpenIDClaims) DeepCopyInto(out *OpenIDClaims) { *out = *in if in.ID != nil { in, out := &in.ID, &out.ID *out = make([]string, len(*in)) copy(*out, *in) } if in.PreferredUsername != nil { in, out := &in.PreferredUsername, &out.PreferredUsername *out = make([]string, len(*in)) copy(*out, *in) } if in.Name != nil { in, out := &in.Name, &out.Name *out = make([]string, len(*in)) copy(*out, *in) } if in.Email != nil { in, out := &in.Email, &out.Email *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OpenIDClaims. func (in *OpenIDClaims) DeepCopy() *OpenIDClaims { if in == nil { return nil } out := new(OpenIDClaims) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *OpenIDIdentityProvider) DeepCopyInto(out *OpenIDIdentityProvider) { *out = *in out.TypeMeta = in.TypeMeta out.ClientSecret = in.ClientSecret if in.ExtraScopes != nil { in, out := &in.ExtraScopes, &out.ExtraScopes *out = make([]string, len(*in)) copy(*out, *in) } if in.ExtraAuthorizeParameters != nil { in, out := &in.ExtraAuthorizeParameters, &out.ExtraAuthorizeParameters *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } out.URLs = in.URLs in.Claims.DeepCopyInto(&out.Claims) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OpenIDIdentityProvider. func (in *OpenIDIdentityProvider) DeepCopy() *OpenIDIdentityProvider { if in == nil { return nil } out := new(OpenIDIdentityProvider) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *OpenIDIdentityProvider) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *OpenIDURLs) DeepCopyInto(out *OpenIDURLs) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OpenIDURLs. func (in *OpenIDURLs) DeepCopy() *OpenIDURLs { if in == nil { return nil } out := new(OpenIDURLs) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *OpenshiftControllerConfig) DeepCopyInto(out *OpenshiftControllerConfig) { *out = *in out.TypeMeta = in.TypeMeta if in.ClientConnectionOverrides != nil { in, out := &in.ClientConnectionOverrides, &out.ClientConnectionOverrides if *in == nil { *out = nil } else { *out = new(ClientConnectionOverrides) **out = **in } } if in.ServingInfo != nil { in, out := &in.ServingInfo, &out.ServingInfo if *in == nil { *out = nil } else { *out = new(HTTPServingInfo) (*in).DeepCopyInto(*out) } } out.LeaderElection = in.LeaderElection if in.Controllers != nil { in, out := &in.Controllers, &out.Controllers *out = make([]string, len(*in)) copy(*out, *in) } out.HPA = in.HPA out.ResourceQuota = in.ResourceQuota in.ServiceServingCert.DeepCopyInto(&out.ServiceServingCert) out.Deployer = in.Deployer in.Build.DeepCopyInto(&out.Build) in.ServiceAccount.DeepCopyInto(&out.ServiceAccount) in.DockerPullSecret.DeepCopyInto(&out.DockerPullSecret) in.Network.DeepCopyInto(&out.Network) out.Ingress = in.Ingress out.ImageImport = in.ImageImport out.SecurityAllocator = in.SecurityAllocator return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OpenshiftControllerConfig. func (in *OpenshiftControllerConfig) DeepCopy() *OpenshiftControllerConfig { if in == nil { return nil } out := new(OpenshiftControllerConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *OpenshiftControllerConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PodManifestConfig) DeepCopyInto(out *PodManifestConfig) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodManifestConfig. func (in *PodManifestConfig) DeepCopy() *PodManifestConfig { if in == nil { return nil } out := new(PodManifestConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PolicyConfig) DeepCopyInto(out *PolicyConfig) { *out = *in in.UserAgentMatchingConfig.DeepCopyInto(&out.UserAgentMatchingConfig) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PolicyConfig. func (in *PolicyConfig) DeepCopy() *PolicyConfig { if in == nil { return nil } out := new(PolicyConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ProjectConfig) DeepCopyInto(out *ProjectConfig) { *out = *in if in.SecurityAllocator != nil { in, out := &in.SecurityAllocator, &out.SecurityAllocator if *in == nil { *out = nil } else { *out = new(SecurityAllocator) **out = **in } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProjectConfig. func (in *ProjectConfig) DeepCopy() *ProjectConfig { if in == nil { return nil } out := new(ProjectConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RFC2307Config) DeepCopyInto(out *RFC2307Config) { *out = *in out.AllGroupsQuery = in.AllGroupsQuery if in.GroupNameAttributes != nil { in, out := &in.GroupNameAttributes, &out.GroupNameAttributes *out = make([]string, len(*in)) copy(*out, *in) } if in.GroupMembershipAttributes != nil { in, out := &in.GroupMembershipAttributes, &out.GroupMembershipAttributes *out = make([]string, len(*in)) copy(*out, *in) } out.AllUsersQuery = in.AllUsersQuery if in.UserNameAttributes != nil { in, out := &in.UserNameAttributes, &out.UserNameAttributes *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RFC2307Config. func (in *RFC2307Config) DeepCopy() *RFC2307Config { if in == nil { return nil } out := new(RFC2307Config) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RegistryLocation) DeepCopyInto(out *RegistryLocation) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RegistryLocation. func (in *RegistryLocation) DeepCopy() *RegistryLocation { if in == nil { return nil } out := new(RegistryLocation) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RemoteConnectionInfo) DeepCopyInto(out *RemoteConnectionInfo) { *out = *in out.ClientCert = in.ClientCert return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RemoteConnectionInfo. func (in *RemoteConnectionInfo) DeepCopy() *RemoteConnectionInfo { if in == nil { return nil } out := new(RemoteConnectionInfo) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RequestHeaderAuthenticationOptions) DeepCopyInto(out *RequestHeaderAuthenticationOptions) { *out = *in if in.ClientCommonNames != nil { in, out := &in.ClientCommonNames, &out.ClientCommonNames *out = make([]string, len(*in)) copy(*out, *in) } if in.UsernameHeaders != nil { in, out := &in.UsernameHeaders, &out.UsernameHeaders *out = make([]string, len(*in)) copy(*out, *in) } if in.GroupHeaders != nil { in, out := &in.GroupHeaders, &out.GroupHeaders *out = make([]string, len(*in)) copy(*out, *in) } if in.ExtraHeaderPrefixes != nil { in, out := &in.ExtraHeaderPrefixes, &out.ExtraHeaderPrefixes *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RequestHeaderAuthenticationOptions. func (in *RequestHeaderAuthenticationOptions) DeepCopy() *RequestHeaderAuthenticationOptions { if in == nil { return nil } out := new(RequestHeaderAuthenticationOptions) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RequestHeaderIdentityProvider) DeepCopyInto(out *RequestHeaderIdentityProvider) { *out = *in out.TypeMeta = in.TypeMeta if in.ClientCommonNames != nil { in, out := &in.ClientCommonNames, &out.ClientCommonNames *out = make([]string, len(*in)) copy(*out, *in) } if in.Headers != nil { in, out := &in.Headers, &out.Headers *out = make([]string, len(*in)) copy(*out, *in) } if in.PreferredUsernameHeaders != nil { in, out := &in.PreferredUsernameHeaders, &out.PreferredUsernameHeaders *out = make([]string, len(*in)) copy(*out, *in) } if in.NameHeaders != nil { in, out := &in.NameHeaders, &out.NameHeaders *out = make([]string, len(*in)) copy(*out, *in) } if in.EmailHeaders != nil { in, out := &in.EmailHeaders, &out.EmailHeaders *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RequestHeaderIdentityProvider. func (in *RequestHeaderIdentityProvider) DeepCopy() *RequestHeaderIdentityProvider { if in == nil { return nil } out := new(RequestHeaderIdentityProvider) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *RequestHeaderIdentityProvider) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ResourceQuotaControllerConfig) DeepCopyInto(out *ResourceQuotaControllerConfig) { *out = *in out.SyncPeriod = in.SyncPeriod out.MinResyncPeriod = in.MinResyncPeriod return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceQuotaControllerConfig. func (in *ResourceQuotaControllerConfig) DeepCopy() *ResourceQuotaControllerConfig { if in == nil { return nil } out := new(ResourceQuotaControllerConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RoutingConfig) DeepCopyInto(out *RoutingConfig) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RoutingConfig. func (in *RoutingConfig) DeepCopy() *RoutingConfig { if in == nil { return nil } out := new(RoutingConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SecurityAllocator) DeepCopyInto(out *SecurityAllocator) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SecurityAllocator. func (in *SecurityAllocator) DeepCopy() *SecurityAllocator { if in == nil { return nil } out := new(SecurityAllocator) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ServiceAccountConfig) DeepCopyInto(out *ServiceAccountConfig) { *out = *in if in.ManagedNames != nil { in, out := &in.ManagedNames, &out.ManagedNames *out = make([]string, len(*in)) copy(*out, *in) } if in.PublicKeyFiles != nil { in, out := &in.PublicKeyFiles, &out.PublicKeyFiles *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceAccountConfig. func (in *ServiceAccountConfig) DeepCopy() *ServiceAccountConfig { if in == nil { return nil } out := new(ServiceAccountConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ServiceAccountControllerConfig) DeepCopyInto(out *ServiceAccountControllerConfig) { *out = *in if in.ManagedNames != nil { in, out := &in.ManagedNames, &out.ManagedNames *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceAccountControllerConfig. func (in *ServiceAccountControllerConfig) DeepCopy() *ServiceAccountControllerConfig { if in == nil { return nil } out := new(ServiceAccountControllerConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ServiceServingCert) DeepCopyInto(out *ServiceServingCert) { *out = *in if in.Signer != nil { in, out := &in.Signer, &out.Signer if *in == nil { *out = nil } else { *out = new(CertInfo) **out = **in } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceServingCert. func (in *ServiceServingCert) DeepCopy() *ServiceServingCert { if in == nil { return nil } out := new(ServiceServingCert) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ServingInfo) DeepCopyInto(out *ServingInfo) { *out = *in out.ServerCert = in.ServerCert if in.NamedCertificates != nil { in, out := &in.NamedCertificates, &out.NamedCertificates *out = make([]NamedCertificate, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.CipherSuites != nil { in, out := &in.CipherSuites, &out.CipherSuites *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServingInfo. func (in *ServingInfo) DeepCopy() *ServingInfo { if in == nil { return nil } out := new(ServingInfo) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SessionConfig) DeepCopyInto(out *SessionConfig) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SessionConfig. func (in *SessionConfig) DeepCopy() *SessionConfig { if in == nil { return nil } out := new(SessionConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SessionSecret) DeepCopyInto(out *SessionSecret) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SessionSecret. func (in *SessionSecret) DeepCopy() *SessionSecret { if in == nil { return nil } out := new(SessionSecret) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SessionSecrets) DeepCopyInto(out *SessionSecrets) { *out = *in out.TypeMeta = in.TypeMeta if in.Secrets != nil { in, out := &in.Secrets, &out.Secrets *out = make([]SessionSecret, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SessionSecrets. func (in *SessionSecrets) DeepCopy() *SessionSecrets { if in == nil { return nil } out := new(SessionSecrets) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *SessionSecrets) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *StringSource) DeepCopyInto(out *StringSource) { *out = *in out.StringSourceSpec = in.StringSourceSpec return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StringSource. func (in *StringSource) DeepCopy() *StringSource { if in == nil { return nil } out := new(StringSource) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *StringSourceSpec) DeepCopyInto(out *StringSourceSpec) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StringSourceSpec. func (in *StringSourceSpec) DeepCopy() *StringSourceSpec { if in == nil { return nil } out := new(StringSourceSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TokenConfig) DeepCopyInto(out *TokenConfig) { *out = *in if in.AccessTokenInactivityTimeoutSeconds != nil { in, out := &in.AccessTokenInactivityTimeoutSeconds, &out.AccessTokenInactivityTimeoutSeconds if *in == nil { *out = nil } else { *out = new(int32) **out = **in } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TokenConfig. func (in *TokenConfig) DeepCopy() *TokenConfig { if in == nil { return nil } out := new(TokenConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *UserAgentDenyRule) DeepCopyInto(out *UserAgentDenyRule) { *out = *in in.UserAgentMatchRule.DeepCopyInto(&out.UserAgentMatchRule) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UserAgentDenyRule. func (in *UserAgentDenyRule) DeepCopy() *UserAgentDenyRule { if in == nil { return nil } out := new(UserAgentDenyRule) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *UserAgentMatchRule) DeepCopyInto(out *UserAgentMatchRule) { *out = *in if in.HTTPVerbs != nil { in, out := &in.HTTPVerbs, &out.HTTPVerbs *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UserAgentMatchRule. func (in *UserAgentMatchRule) DeepCopy() *UserAgentMatchRule { if in == nil { return nil } out := new(UserAgentMatchRule) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *UserAgentMatchingConfig) DeepCopyInto(out *UserAgentMatchingConfig) { *out = *in if in.RequiredClients != nil { in, out := &in.RequiredClients, &out.RequiredClients *out = make([]UserAgentMatchRule, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.DeniedClients != nil { in, out := &in.DeniedClients, &out.DeniedClients *out = make([]UserAgentDenyRule, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UserAgentMatchingConfig. func (in *UserAgentMatchingConfig) DeepCopy() *UserAgentMatchingConfig { if in == nil { return nil } out := new(UserAgentMatchingConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *WebhookTokenAuthenticator) DeepCopyInto(out *WebhookTokenAuthenticator) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WebhookTokenAuthenticator. func (in *WebhookTokenAuthenticator) DeepCopy() *WebhookTokenAuthenticator { if in == nil { return nil } out := new(WebhookTokenAuthenticator) in.DeepCopyInto(out) return out }
{ "content_hash": "f1e5a80a12edbcd55afeca53b8bb64af", "timestamp": "", "source": "github", "line_count": 2301, "max_line_length": 123, "avg_line_length": 29.291177748804866, "alnum_prop": 0.7260196738824019, "repo_name": "legionus/origin", "id": "314661bbb8aa523459f162a6a297c49e951dc34f", "size": "67481", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pkg/cmd/server/apis/config/zz_generated.deepcopy.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "1842" }, { "name": "DIGITAL Command Language", "bytes": "117" }, { "name": "Go", "bytes": "18908374" }, { "name": "Groovy", "bytes": "5288" }, { "name": "HTML", "bytes": "74732" }, { "name": "Makefile", "bytes": "21890" }, { "name": "Protocol Buffer", "bytes": "635763" }, { "name": "Python", "bytes": "33408" }, { "name": "Roff", "bytes": "2049" }, { "name": "Ruby", "bytes": "484" }, { "name": "Shell", "bytes": "2159344" }, { "name": "Smarty", "bytes": "626" } ], "symlink_target": "" }
// Copyright 2013 Jon Skeet. All rights reserved. Use of this source code is governed by the Apache License 2.0, as found in the LICENSE.txt file. using System; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; namespace FunWithAwaiters { public static class AsyncStateMachineExtensions { public static int GetState(this IAsyncStateMachine stateMachine) { return (int) stateMachine.GetStateField().GetValue(stateMachine); } public static void SetState(this IAsyncStateMachine stateMachine, int state) { stateMachine.GetStateField().SetValue(stateMachine, state); } public static Action GetActionForState(this IAsyncStateMachine stateMachine, int state) { return () => { stateMachine.SetState(state); stateMachine.MoveNext(); }; } private static FieldInfo GetStateField(this IAsyncStateMachine stateMachine) { return stateMachine.GetType().GetField("<>1__state"); } public static void SaveTo(this IAsyncStateMachine stateMachine, string file) { using (var stream = File.Create(file)) { SerializationUtil.SerializeFields(stateMachine, stream, ShouldSerialize); } } public static void LoadFrom(this IAsyncStateMachine target, string file) { using (var stream = File.OpenRead(file)) { SerializationUtil.DeserializeFields(target, stream); } } public static void SaveTo(this IAsyncStateMachine stateMachine, Stream stream) { SerializationUtil.SerializeFields(stateMachine, stream, ShouldSerialize); } public static void LoadFrom(this IAsyncStateMachine target, Stream stream) { SerializationUtil.DeserializeFields(target, stream); } // This is all down to experimentation... private static bool ShouldSerialize(FieldInfo field) { if (typeof(ITransient).IsAssignableFrom(field.FieldType)) { return false; } string name = field.Name; // Parameters end up just with the same name as the original. // Local variables end up with the identifier in the angle brackets, e.g. <foo> if (!name.StartsWith("<>")) { return true; } // <>1__state will hold the state, which we do want to serialize. // <>7__wrap* holds things like extra variables for iterators and using statements. // <>t__builder holds the AsyncTaskMethodBuilder (or whatever) - we don't want that // <>u__%awaiter* holds awaiters // (More TBD?) return char.IsDigit(name[2]); } } }
{ "content_hash": "d4c2cb3486481b22f618ae3d05a762a4", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 147, "avg_line_length": 34.752941176470586, "alnum_prop": 0.5995260663507109, "repo_name": "RaySingerNZ/DemoCode", "id": "bce834c2f4b6acb554b2d9a7a626460fe171d796", "size": "2956", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Abusing CSharp/Code/FunWithAwaiters/AsyncStateMachineExtensions.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "201739" } ], "symlink_target": "" }
/* * Powered By [柳丰] * Web Site: http://www.trend.com.cn */ package com.trend.hbny.model; import java.util.ArrayList; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import com.trend.hbny.model.E288Power; import com.trend.hbny.model.RDayGenerator; import com.trend.hbny.model.RDayLine; import com.trend.hbny.model.RDayRemark; import com.trend.hbny.model.RDayStation; import javax.persistence.*; import java.util.*; import javacommon.base.*; import javacommon.util.*; import cn.org.rapid_framework.util.*; import cn.org.rapid_framework.web.util.*; import cn.org.rapid_framework.page.*; import cn.org.rapid_framework.page.impl.*; import com.trend.hbny.model.*; import com.trend.hbny.dao.*; import com.trend.hbny.service.*; /** * @author neolf email:neolf(a)foxmail.com * @version 1.0 * @since 1.0 */ public class RHbnyDailyProduction extends BaseEntity { //alias public static final String TABLE_ALIAS = "RHbnyDailyProduction"; public static final String ALIAS_ID = "id"; public static final String ALIAS_CO_NO = "coNo"; public static final String ALIAS_RPT_NO = "rptNo"; public static final String ALIAS_RPT_DATE = "rptDate"; public static final String ALIAS_COMPANY = "company"; public static final String ALIAS_POWER_STATION = "powerStation"; public static final String ALIAS_L_G_FLAG = "lGFlag"; public static final String ALIAS_METER_NO = "meterNo"; public static final String ALIAS_NAME = "name"; public static final String ALIAS_DAY_P = "dayP"; public static final String ALIAS_MONTH_P = "monthP"; public static final String ALIAS_YEAR_P = "yearP"; public static final String ALIAS_R_DAY_GENERATOR = "rDayGenerator"; public static final String ALIAS_E_LINE_BASICINFO = "eLineBasicinfo"; /* ublic static final String ALIAS_CO_NO = "coNo"; public static final String ALIAS_COMPANY = "公司"; public static final String ALIAS_POWERSTATION = "电厂"; public static final String ALIAS_NAME = "名称"; public static final String ALIAS_L_G_FLAG = "线路标志"; public static final String ALIAS_DATATIME = "实时时间"; */ //date formats public static final String FORMAT_RPT_DATE = DATE_TIME_FORMAT; //columns START private Integer id; private String coNo; private String rptNo; private java.util.Date rptDate; private String company; private String powerStation; private String lGFlag; private String meterNo; private String name; private Double dayP; private Double monthP; private Double yearP; private List<RDayGenerator> rDayGeneratorList; private List<ELineBasicinfo> eLineBasicinfoList; //columns END //注意: spring_jdbc的MetadataCreateUtils.fromTable(Entity.class) 可以读取JPA annotation的标注信息 //现支持 @Id,@Column,@Table标注 /* public RHbnyDailyProduction(){ } public RHbnyDailyProduction( java.lang.Integer id ){ this.id = id; } */ public RHbnyDailyProduction(){ //@TODO rDayGeneratorList = new ArrayList<RDayGenerator>(); eLineBasicinfoList = new ArrayList<ELineBasicinfo>(); } @Id public java.lang.Integer getId() { return this.id; } public void setId(java.lang.Integer value) { this.id = value; } public java.lang.String getCoNo() { return this.coNo; } public void setCoNo(java.lang.String value) { this.coNo = value; } public java.lang.String getRptNo() { return this.rptNo; } public void setRptNo(java.lang.String value) { this.rptNo = value; } @Transient public String getRptDateString() { return date2String(getRptDate(), FORMAT_RPT_DATE); } public void setRptDateString(String value) { setRptDate(string2Date(value, FORMAT_RPT_DATE,java.util.Date.class)); } public java.util.Date getRptDate() { return this.rptDate; } public void setRptDate(java.util.Date value) { this.rptDate = value; } public java.lang.String getCompany() { return this.company; } public void setCompany(java.lang.String value) { this.company = value; } public java.lang.String getPowerStation() { return this.powerStation; } public void setPowerStation(java.lang.String value) { this.powerStation = value; } public java.lang.String getlGFlag() { return this.lGFlag; } public void setlGFlag(java.lang.String value) { this.lGFlag = value; } public java.lang.String getMeterNo() { return this.meterNo; } public void setMeterNo(java.lang.String value) { this.meterNo = value; } public java.lang.String getName() { return this.name; } public void setName(java.lang.String value) { this.name = value; } public java.lang.Double getDayP() { return this.dayP; } public void setDayP(java.lang.Double value) { this.dayP = value; } public java.lang.Double getMonthP() { return this.monthP; } public void setMonthP(java.lang.Double value) { this.monthP = value; } public java.lang.Double getYearP() { return this.yearP; } public void setYearP(java.lang.Double value) { this.yearP = value; } public List<RDayGenerator> getrDayGeneratorList() { return this.rDayGeneratorList; } public List<RDayGenerator> getrDayGenerator() { return this.rDayGeneratorList; } public void setrDayGeneratorList (List<RDayGenerator> value) { this.rDayGeneratorList = value; } public List<ELineBasicinfo> geteLineBasicinfoList() { return this.eLineBasicinfoList; } public List<ELineBasicinfo> geteLineBasicinfo() { return this.eLineBasicinfoList; } public void seteLineBasicinfoList (List<ELineBasicinfo> value) { this.eLineBasicinfoList = value; } public String toString() { return new ToStringBuilder(this) .append("Id",getId()) .append("CoNo",getCoNo()) .append("RptNo",getRptNo()) .append("RptDate",getRptDate()) .append("Company",getCompany()) .append("PowerStation",getPowerStation()) .append("LGFlag",getlGFlag()) .append("MeterNo",getMeterNo()) .append("Name",getName()) .append("DayP",getDayP()) .append("MonthP",getMonthP()) .append("YearP",getYearP()) .append("RDayGenerator",getrDayGenerator()) .append("ELineBasicinfo",geteLineBasicinfo()) .toString(); } public int hashCode() { return new HashCodeBuilder() .append(getId()) .append(getCoNo()) .append(getRptNo()) .append(getRptDate()) .append(getCompany()) .append(getPowerStation()) .append(getlGFlag()) .append(getMeterNo()) .append(getName()) .append(getDayP()) .append(getMonthP()) .append(getYearP()) .append(getrDayGenerator()) .append(geteLineBasicinfo()) .toHashCode(); } public boolean equals(Object obj) { if(obj instanceof RHbnyDailyProduction == false) return false; if(this == obj) return true; RHbnyDailyProduction other = (RHbnyDailyProduction)obj; return new EqualsBuilder() .append(getId(),other.getId()) .append(getCoNo(),other.getCoNo()) .append(getRptNo(),other.getRptNo()) .append(getRptDate(),other.getRptDate()) .append(getCompany(),other.getCompany()) .append(getPowerStation(),other.getPowerStation()) .append(getlGFlag(),other.getlGFlag()) .append(getMeterNo(),other.getMeterNo()) .append(getName(),other.getName()) .append(getDayP(),other.getDayP()) .append(getMonthP(),other.getMonthP()) .append(getYearP(),other.getYearP()) .append(getrDayGenerator(),other.getrDayGenerator()) .append(geteLineBasicinfo(),other.geteLineBasicinfo()) .isEquals(); } }
{ "content_hash": "f4db079e4348eb11bfe29226e3eec0ec", "timestamp": "", "source": "github", "line_count": 304, "max_line_length": 86, "avg_line_length": 24.917763157894736, "alnum_prop": 0.7036303630363037, "repo_name": "neolfdev/dlscxx", "id": "1b1be6b398467eeeee49d8b21fae0caf2dbcc8cc", "size": "7643", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java_view/src/com/trend/hbny/model/RHbnyDailyProduction.java", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "400" }, { "name": "C#", "bytes": "2785" }, { "name": "Java", "bytes": "2084580" }, { "name": "JavaScript", "bytes": "4007143" }, { "name": "PHP", "bytes": "24990" }, { "name": "Python", "bytes": "7875" }, { "name": "Ruby", "bytes": "2587" }, { "name": "Shell", "bytes": "6460" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('www', '0001_initial'), ] operations = [ migrations.RenameField( model_name='person', old_name='institution', new_name='affiliation', ), migrations.RenameField( model_name='person', old_name='subinstitution', new_name='subaffiliation1', ), migrations.AddField( model_name='person', name='subaffiliation2', field=models.CharField(blank=True, max_length=100), ), ]
{ "content_hash": "7c4b4e67e73033444bf743e2e00077ac", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 63, "avg_line_length": 24.5, "alnum_prop": 0.5510204081632653, "repo_name": "openpsych/django", "id": "806af00a7e1d3f83f20e9909ee4459f6cc38d56b", "size": "757", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "www/migrations/0002_auto_20160808_0140.py", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "156335" }, { "name": "HTML", "bytes": "33437" }, { "name": "JavaScript", "bytes": "1047" }, { "name": "Python", "bytes": "33357" }, { "name": "Ruby", "bytes": "170" } ], "symlink_target": "" }
Polymer('core-selection', { /** * If true, multiple selections are allowed. * * @attribute multi * @type boolean * @default false */ multi: false, ready: function() { this.clear(); }, clear: function() { this.selection = []; }, /** * Retrieves the selected item(s). * @method getSelection * @returns Returns the selected item(s). If the multi property is true, * getSelection will return an array, otherwise it will return * the selected item or undefined if there is no selection. */ getSelection: function() { return this.multi ? this.selection : this.selection[0]; }, /** * Indicates if a given item is selected. * @method isSelected * @param {any} item The item whose selection state should be checked. * @returns Returns true if `item` is selected. */ isSelected: function(item) { return this.selection.indexOf(item) >= 0; }, setItemSelected: function(item, isSelected) { if (item !== undefined && item !== null) { if (isSelected) { this.selection.push(item); } else { var i = this.selection.indexOf(item); if (i >= 0) { this.selection.splice(i, 1); } } this.fire("core-select", {isSelected: isSelected, item: item}); } }, /** * Set the selection state for a given `item`. If the multi property * is true, then the selected state of `item` will be toggled; otherwise * the `item` will be selected. * @method select * @param {any} item: The item to select. */ select: function(item) { if (this.multi) { this.toggle(item); } else if (this.getSelection() !== item) { this.setItemSelected(this.getSelection(), false); this.setItemSelected(item, true); } }, /** * Toggles the selection state for `item`. * @method toggle * @param {any} item: The item to toggle. */ toggle: function(item) { this.setItemSelected(item, !this.isSelected(item)); } }); ; Polymer('core-selector', { /** * Gets or sets the selected element. Default to use the index * of the item element. * * If you want a specific attribute value of the element to be * used instead of index, set "valueattr" to that attribute name. * * Example: * * <core-selector valueattr="label" selected="foo"> * <div label="foo"></div> * <div label="bar"></div> * <div label="zot"></div> * </core-selector> * * In multi-selection this should be an array of values. * * Example: * * <core-selector id="selector" valueattr="label" multi> * <div label="foo"></div> * <div label="bar"></div> * <div label="zot"></div> * </core-selector> * * this.$.selector.selected = ['foo', 'zot']; * * @attribute selected * @type Object * @default null */ selected: null, /** * If true, multiple selections are allowed. * * @attribute multi * @type boolean * @default false */ multi: false, /** * Specifies the attribute to be used for "selected" attribute. * * @attribute valueattr * @type string * @default 'name' */ valueattr: 'name', /** * Specifies the CSS class to be used to add to the selected element. * * @attribute selectedClass * @type string * @default 'core-selected' */ selectedClass: 'core-selected', /** * Specifies the property to be used to set on the selected element * to indicate its active state. * * @attribute selectedProperty * @type string * @default '' */ selectedProperty: '', /** * Specifies the attribute to set on the selected element to indicate * its active state. * * @attribute selectedAttribute * @type string * @default 'active' */ selectedAttribute: 'active', /** * Returns the currently selected element. In multi-selection this returns * an array of selected elements. * * @attribute selectedItem * @type Object * @default null */ selectedItem: null, /** * In single selection, this returns the model associated with the * selected element. * * @attribute selectedModel * @type Object * @default null */ selectedModel: null, /** * In single selection, this returns the selected index. * * @attribute selectedIndex * @type number * @default -1 */ selectedIndex: -1, /** * The target element that contains items. If this is not set * core-selector is the container. * * @attribute target * @type Object * @default null */ target: null, /** * This can be used to query nodes from the target node to be used for * selection items. Note this only works if the 'target' property is set. * * Example: * * <core-selector target="{{$.myForm}}" itemsSelector="input[type=radio]"></core-selector> * <form id="myForm"> * <label><input type="radio" name="color" value="red"> Red</label> <br> * <label><input type="radio" name="color" value="green"> Green</label> <br> * <label><input type="radio" name="color" value="blue"> Blue</label> <br> * <p>color = {{color}}</p> * </form> * * @attribute itemsSelector * @type string * @default '' */ itemsSelector: '', /** * The event that would be fired from the item element to indicate * it is being selected. * * @attribute activateEvent * @type string * @default 'tap' */ activateEvent: 'tap', /** * Set this to true to disallow changing the selection via the * `activateEvent`. * * @attribute notap * @type boolean * @default false */ notap: false, ready: function() { this.activateListener = this.activateHandler.bind(this); this.observer = new MutationObserver(this.updateSelected.bind(this)); if (!this.target) { this.target = this; } }, get items() { if (!this.target) { return []; } var nodes = this.target !== this ? (this.itemsSelector ? this.target.querySelectorAll(this.itemsSelector) : this.target.children) : this.$.items.getDistributedNodes(); return Array.prototype.filter.call(nodes || [], function(n) { return n && n.localName !== 'template'; }); }, targetChanged: function(old) { if (old) { this.removeListener(old); this.observer.disconnect(); this.clearSelection(); } if (this.target) { this.addListener(this.target); this.observer.observe(this.target, {childList: true}); this.updateSelected(); } }, addListener: function(node) { Polymer.addEventListener(node, this.activateEvent, this.activateListener); }, removeListener: function(node) { Polymer.removeEventListener(node, this.activateEvent, this.activateListener); }, get selection() { return this.$.selection.getSelection(); }, selectedChanged: function() { this.updateSelected(); }, updateSelected: function() { this.validateSelected(); if (this.multi) { this.clearSelection(); this.selected && this.selected.forEach(function(s) { this.valueToSelection(s); }, this); } else { this.valueToSelection(this.selected); } }, validateSelected: function() { // convert to an array for multi-selection if (this.multi && !Array.isArray(this.selected) && this.selected !== null && this.selected !== undefined) { this.selected = [this.selected]; } }, clearSelection: function() { if (this.multi) { this.selection.slice().forEach(function(s) { this.$.selection.setItemSelected(s, false); }, this); } else { this.$.selection.setItemSelected(this.selection, false); } this.selectedItem = null; this.$.selection.clear(); }, valueToSelection: function(value) { var item = (value === null || value === undefined) ? null : this.items[this.valueToIndex(value)]; this.$.selection.select(item); }, updateSelectedItem: function() { this.selectedItem = this.selection; }, selectedItemChanged: function() { if (this.selectedItem) { var t = this.selectedItem.templateInstance; this.selectedModel = t ? t.model : undefined; } else { this.selectedModel = null; } this.selectedIndex = this.selectedItem ? parseInt(this.valueToIndex(this.selected)) : -1; }, valueToIndex: function(value) { // find an item with value == value and return it's index for (var i=0, items=this.items, c; (c=items[i]); i++) { if (this.valueForNode(c) == value) { return i; } } // if no item found, the value itself is probably the index return value; }, valueForNode: function(node) { return node[this.valueattr] || node.getAttribute(this.valueattr); }, // events fired from <core-selection> object selectionSelect: function(e, detail) { this.updateSelectedItem(); if (detail.item) { this.applySelection(detail.item, detail.isSelected); } }, applySelection: function(item, isSelected) { if (this.selectedClass) { item.classList.toggle(this.selectedClass, isSelected); } if (this.selectedProperty) { item[this.selectedProperty] = isSelected; } if (this.selectedAttribute && item.setAttribute) { if (isSelected) { item.setAttribute(this.selectedAttribute, ''); } else { item.removeAttribute(this.selectedAttribute); } } }, // event fired from host activateHandler: function(e) { if (!this.notap) { var i = this.findDistributedTarget(e.target, this.items); if (i >= 0) { var item = this.items[i]; var s = this.valueForNode(item) || i; if (this.multi) { if (this.selected) { this.addRemoveSelected(s); } else { this.selected = [s]; } } else { this.selected = s; } this.asyncFire('core-activate', {item: item}); } } }, addRemoveSelected: function(value) { var i = this.selected.indexOf(value); if (i >= 0) { this.selected.splice(i, 1); } else { this.selected.push(value); } this.valueToSelection(value); }, findDistributedTarget: function(target, nodes) { // find first ancestor of target (including itself) that // is in nodes, if any while (target && target != this) { var i = Array.prototype.indexOf.call(nodes, target); if (i >= 0) { return i; } target = target.parentNode; } } }); ; (function() { var waveMaxRadius = 150; // // INK EQUATIONS // function waveRadiusFn(touchDownMs, touchUpMs, anim) { // Convert from ms to s. var touchDown = touchDownMs / 1000; var touchUp = touchUpMs / 1000; var totalElapsed = touchDown + touchUp; var ww = anim.width, hh = anim.height; // use diagonal size of container to avoid floating point math sadness var waveRadius = Math.min(Math.sqrt(ww * ww + hh * hh), waveMaxRadius) * 1.1 + 5; var duration = 1.1 - .2 * (waveRadius / waveMaxRadius); var tt = (totalElapsed / duration); var size = waveRadius * (1 - Math.pow(80, -tt)); return Math.abs(size); } function waveOpacityFn(td, tu, anim) { // Convert from ms to s. var touchDown = td / 1000; var touchUp = tu / 1000; var totalElapsed = touchDown + touchUp; if (tu <= 0) { // before touch up return anim.initialOpacity; } return Math.max(0, anim.initialOpacity - touchUp * anim.opacityDecayVelocity); } function waveOuterOpacityFn(td, tu, anim) { // Convert from ms to s. var touchDown = td / 1000; var touchUp = tu / 1000; // Linear increase in background opacity, capped at the opacity // of the wavefront (waveOpacity). var outerOpacity = touchDown * 0.3; var waveOpacity = waveOpacityFn(td, tu, anim); return Math.max(0, Math.min(outerOpacity, waveOpacity)); } // Determines whether the wave should be completely removed. function waveDidFinish(wave, radius, anim) { var waveOpacity = waveOpacityFn(wave.tDown, wave.tUp, anim); // If the wave opacity is 0 and the radius exceeds the bounds // of the element, then this is finished. if (waveOpacity < 0.01 && radius >= Math.min(wave.maxRadius, waveMaxRadius)) { return true; } return false; }; function waveAtMaximum(wave, radius, anim) { var waveOpacity = waveOpacityFn(wave.tDown, wave.tUp, anim); if (waveOpacity >= anim.initialOpacity && radius >= Math.min(wave.maxRadius, waveMaxRadius)) { return true; } return false; } // // DRAWING // function drawRipple(ctx, x, y, radius, innerColor, outerColor) { if (outerColor) { ctx.fillStyle = outerColor; ctx.fillRect(0,0,ctx.canvas.width, ctx.canvas.height); } ctx.beginPath(); ctx.arc(x, y, radius, 0, 2 * Math.PI, false); ctx.fillStyle = innerColor; ctx.fill(); } // // SETUP // function createWave(elem) { var elementStyle = window.getComputedStyle(elem); var fgColor = elementStyle.color; var wave = { waveColor: fgColor, maxRadius: 0, isMouseDown: false, mouseDownStart: 0.0, mouseUpStart: 0.0, tDown: 0, tUp: 0 }; return wave; } function removeWaveFromScope(scope, wave) { if (scope.waves) { var pos = scope.waves.indexOf(wave); scope.waves.splice(pos, 1); } }; // Shortcuts. var pow = Math.pow; var now = Date.now; if (window.performance && performance.now) { now = performance.now.bind(performance); } function cssColorWithAlpha(cssColor, alpha) { var parts = cssColor.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); if (typeof alpha == 'undefined') { alpha = 1; } if (!parts) { return 'rgba(255, 255, 255, ' + alpha + ')'; } return 'rgba(' + parts[1] + ', ' + parts[2] + ', ' + parts[3] + ', ' + alpha + ')'; } function dist(p1, p2) { return Math.sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2)); } function distanceFromPointToFurthestCorner(point, size) { var tl_d = dist(point, {x: 0, y: 0}); var tr_d = dist(point, {x: size.w, y: 0}); var bl_d = dist(point, {x: 0, y: size.h}); var br_d = dist(point, {x: size.w, y: size.h}); return Math.max(tl_d, tr_d, bl_d, br_d); } Polymer('paper-ripple', { /** * The initial opacity set on the wave. * * @attribute initialOpacity * @type number * @default 0.25 */ initialOpacity: 0.25, /** * How fast (opacity per second) the wave fades out. * * @attribute opacityDecayVelocity * @type number * @default 0.8 */ opacityDecayVelocity: 0.8, backgroundFill: true, pixelDensity: 2, eventDelegates: { down: 'downAction', up: 'upAction' }, attached: function() { // create the canvas element manually becase ios // does not render the canvas element if it is not created in the // main document (component templates are created in a // different document). See: // https://bugs.webkit.org/show_bug.cgi?id=109073. if (!this.$.canvas) { var canvas = document.createElement('canvas'); canvas.id = 'canvas'; this.shadowRoot.appendChild(canvas); this.$.canvas = canvas; } }, ready: function() { this.waves = []; }, setupCanvas: function() { this.$.canvas.setAttribute('width', this.$.canvas.clientWidth * this.pixelDensity + "px"); this.$.canvas.setAttribute('height', this.$.canvas.clientHeight * this.pixelDensity + "px"); var ctx = this.$.canvas.getContext('2d'); ctx.scale(this.pixelDensity, this.pixelDensity); if (!this._loop) { this._loop = this.animate.bind(this, ctx); } }, downAction: function(e) { this.setupCanvas(); var wave = createWave(this.$.canvas); this.cancelled = false; wave.isMouseDown = true; wave.tDown = 0.0; wave.tUp = 0.0; wave.mouseUpStart = 0.0; wave.mouseDownStart = now(); var width = this.$.canvas.width / 2; // Retina canvas var height = this.$.canvas.height / 2; var rect = this.getBoundingClientRect(); var touchX = e.x - rect.left; var touchY = e.y - rect.top; wave.startPosition = {x:touchX, y:touchY}; if (this.classList.contains("recenteringTouch")) { wave.endPosition = {x: width / 2, y: height / 2}; wave.slideDistance = dist(wave.startPosition, wave.endPosition); } wave.containerSize = Math.max(width, height); wave.maxRadius = distanceFromPointToFurthestCorner(wave.startPosition, {w: width, h: height}); this.waves.push(wave); requestAnimationFrame(this._loop); }, upAction: function() { for (var i = 0; i < this.waves.length; i++) { // Declare the next wave that has mouse down to be mouse'ed up. var wave = this.waves[i]; if (wave.isMouseDown) { wave.isMouseDown = false wave.mouseUpStart = now(); wave.mouseDownStart = 0; wave.tUp = 0.0; break; } } this._loop && requestAnimationFrame(this._loop); }, cancel: function() { this.cancelled = true; }, animate: function(ctx) { var shouldRenderNextFrame = false; // Clear the canvas ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); var deleteTheseWaves = []; // The oldest wave's touch down duration var longestTouchDownDuration = 0; var longestTouchUpDuration = 0; // Save the last known wave color var lastWaveColor = null; // wave animation values var anim = { initialOpacity: this.initialOpacity, opacityDecayVelocity: this.opacityDecayVelocity, height: ctx.canvas.height, width: ctx.canvas.width } for (var i = 0; i < this.waves.length; i++) { var wave = this.waves[i]; if (wave.mouseDownStart > 0) { wave.tDown = now() - wave.mouseDownStart; } if (wave.mouseUpStart > 0) { wave.tUp = now() - wave.mouseUpStart; } // Determine how long the touch has been up or down. var tUp = wave.tUp; var tDown = wave.tDown; longestTouchDownDuration = Math.max(longestTouchDownDuration, tDown); longestTouchUpDuration = Math.max(longestTouchUpDuration, tUp); // Obtain the instantenous size and alpha of the ripple. var radius = waveRadiusFn(tDown, tUp, anim); var waveAlpha = waveOpacityFn(tDown, tUp, anim); var waveColor = cssColorWithAlpha(wave.waveColor, waveAlpha); lastWaveColor = wave.waveColor; // Position of the ripple. var x = wave.startPosition.x; var y = wave.startPosition.y; // Ripple gravitational pull to the center of the canvas. if (wave.endPosition) { // This translates from the origin to the center of the view based on the max dimension of var translateFraction = Math.min(1, radius / wave.containerSize * 2 / Math.sqrt(2) ); x += translateFraction * (wave.endPosition.x - wave.startPosition.x); y += translateFraction * (wave.endPosition.y - wave.startPosition.y); } // If we do a background fill fade too, work out the correct color. var bgFillColor = null; if (this.backgroundFill) { var bgFillAlpha = waveOuterOpacityFn(tDown, tUp, anim); bgFillColor = cssColorWithAlpha(wave.waveColor, bgFillAlpha); } // Draw the ripple. drawRipple(ctx, x, y, radius, waveColor, bgFillColor); // Determine whether there is any more rendering to be done. var maximumWave = waveAtMaximum(wave, radius, anim); var waveDissipated = waveDidFinish(wave, radius, anim); var shouldKeepWave = !waveDissipated || maximumWave; var shouldRenderWaveAgain = !waveDissipated && !maximumWave; shouldRenderNextFrame = shouldRenderNextFrame || shouldRenderWaveAgain; if (!shouldKeepWave || this.cancelled) { deleteTheseWaves.push(wave); } } if (shouldRenderNextFrame) { requestAnimationFrame(this._loop); } for (var i = 0; i < deleteTheseWaves.length; ++i) { var wave = deleteTheseWaves[i]; removeWaveFromScope(this, wave); } if (!this.waves.length) { // If there is nothing to draw, clear any drawn waves now because // we're not going to get another requestAnimationFrame any more. ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); this._loop = null; } } }); })(); ; Polymer('paper-tab', { /** * If true, ink ripple effect is disabled. * * @attribute noink * @type boolean * @default false */ noink: false }); ; Polymer('paper-tabs', { /** * If true, ink effect is disabled. * * @attribute noink * @type boolean * @default false */ noink: false, /** * If true, the bottom bar to indicate the selected tab will not be shown. * * @attribute nobar * @type boolean * @default false */ nobar: false, activateEvent: 'down', nostretch: false, selectedIndexChanged: function(old) { var s = this.$.selectionBar.style; if (!this.selectedItem) { s.width = 0; s.left = 0; return; } var w = 100 / this.items.length; if (this.nostretch || old === null || old === -1) { s.width = w + '%'; s.left = this.selectedIndex * w + '%'; return; } var m = 5; this.$.selectionBar.classList.add('expand'); if (old < this.selectedIndex) { s.width = w + w * (this.selectedIndex - old) - m + '%'; } else { s.width = w + w * (old - this.selectedIndex) - m + '%'; s.left = this.selectedIndex * w + m + '%'; } }, barTransitionEnd: function() { var cl = this.$.selectionBar.classList; if (cl.contains('expand')) { cl.remove('expand'); cl.add('contract'); var s = this.$.selectionBar.style; var w = 100 / this.items.length; s.width = w + '%'; s.left = this.selectedIndex * w + '%'; } else if (cl.contains('contract')) { cl.remove('contract'); } } }); ; Polymer('core-pages');; (function() { var SKIP_ID = 'meta'; var metaData = {}, metaArray = {}; Polymer('core-meta', { /** * The type of meta-data. All meta-data with the same type with be * stored together. * * @attribute type * @type string * @default 'default' */ type: 'default', alwaysPrepare: true, ready: function() { this.register(this.id); }, get metaArray() { var t = this.type; if (!metaArray[t]) { metaArray[t] = []; } return metaArray[t]; }, get metaData() { var t = this.type; if (!metaData[t]) { metaData[t] = {}; } return metaData[t]; }, register: function(id, old) { if (id && id !== SKIP_ID) { this.unregister(this, old); this.metaData[id] = this; this.metaArray.push(this); } }, unregister: function(meta, id) { delete this.metaData[id || meta.id]; var i = this.metaArray.indexOf(meta); if (i >= 0) { this.metaArray.splice(i, 1); } }, /** * Returns a list of all meta-data elements with the same type. * * @property list * @type array * @default [] */ get list() { return this.metaArray; }, /** * Retrieves meta-data by ID. * * @method byId * @param {String} id The ID of the meta-data to be returned. * @returns Returns meta-data. */ byId: function(id) { return this.metaData[id]; } }); })(); ; Polymer('core-transition', { type: 'transition', /** * Run the animation. * * @method go * @param {Node} node The node to apply the animation on * @param {Object} state State info */ go: function(node, state) { this.complete(node); }, /** * Set up the animation. This may include injecting a stylesheet, * applying styles, creating a web animations object, etc.. This * * @method setup * @param {Node} node The animated node */ setup: function(node) { }, /** * Tear down the animation. * * @method teardown * @param {Node} node The animated node */ teardown: function(node) { }, /** * Called when the animation completes. This function also fires the * `core-transitionend` event. * * @method complete * @param {Node} node The animated node */ complete: function(node) { this.fire('core-transitionend', null, node); }, /** * Utility function to listen to an event on a node once. * * @method listenOnce * @param {Node} node The animated node * @param {string} event Name of an event * @param {Function} fn Event handler * @param {Array} args Additional arguments to pass to `fn` */ listenOnce: function(node, event, fn, args) { var self = this; var listener = function() { fn.apply(self, args); node.removeEventListener(event, listener, false); } node.addEventListener(event, listener, false); } }); ; Polymer('core-key-helper', { ENTER_KEY: 13, ESCAPE_KEY: 27 }); ; (function() { Polymer('core-overlay-layer', { publish: { opened: false }, openedChanged: function() { this.classList.toggle('core-opened', this.opened); }, /** * Adds an element to the overlay layer */ addElement: function(element) { if (!this.parentNode) { document.querySelector('body').appendChild(this); } if (element.parentNode !== this) { element.__contents = []; var ip$ = element.querySelectorAll('content'); for (var i=0, l=ip$.length, n; (i<l) && (n = ip$[i]); i++) { this.moveInsertedElements(n); this.cacheDomLocation(n); n.parentNode.removeChild(n); element.__contents.push(n); } this.cacheDomLocation(element); this.updateEventController(element); var h = this.makeHost(); h.shadowRoot.appendChild(element); element.__host = h; } }, makeHost: function() { var h = document.createElement('overlay-host'); h.createShadowRoot(); this.appendChild(h); return h; }, moveInsertedElements: function(insertionPoint) { var n$ = insertionPoint.getDistributedNodes(); var parent = insertionPoint.parentNode; insertionPoint.__contents = []; for (var i=0, l=n$.length, n; (i<l) && (n=n$[i]); i++) { this.cacheDomLocation(n); this.updateEventController(n); insertionPoint.__contents.push(n); parent.appendChild(n); } }, updateEventController: function(element) { element.eventController = this.element.findController(element); }, /** * Removes an element from the overlay layer */ removeElement: function(element) { element.eventController = null; this.replaceElement(element); var h = element.__host; if (h) { h.parentNode.removeChild(h); } }, replaceElement: function(element) { if (element.__contents) { for (var i=0, c$=element.__contents, c; (c=c$[i]); i++) { this.replaceElement(c); } element.__contents = null; } if (element.__parentNode) { var n = element.__nextElementSibling && element.__nextElementSibling === element.__parentNode ? element.__nextElementSibling : null; element.__parentNode.insertBefore(element, n); } }, cacheDomLocation: function(element) { element.__nextElementSibling = element.nextElementSibling; element.__parentNode = element.parentNode; } }); })(); ; (function() { Polymer('core-overlay', { publish: { /** * The target element that will be shown when the overlay is * opened. If unspecified, the core-overlay itself is the target. * * @attribute target * @type Object * @default the overlay element */ target: null, /** * A `core-overlay`'s size is guaranteed to be * constrained to the window size. To achieve this, the sizingElement * is sized with a max-height/width. By default this element is the * target element, but it can be specifically set to a specific element * inside the target if that is more appropriate. This is useful, for * example, when a region inside the overlay should scroll if needed. * * @attribute sizingTarget * @type Object * @default the target element */ sizingTarget: null, /** * Set opened to true to show an overlay and to false to hide it. * A `core-overlay` may be made initially opened by setting its * `opened` attribute. * @attribute opened * @type boolean * @default false */ opened: false, /** * If true, the overlay has a backdrop darkening the rest of the screen. * The backdrop element is attached to the document body and may be styled * with the class `core-overlay-backdrop`. When opened the `core-opened` * class is applied. * * @attribute backdrop * @type boolean * @default false */ backdrop: false, /** * If true, the overlay is guaranteed to display above page content. * * @attribute layered * @type boolean * @default false */ layered: false, /** * By default an overlay will close automatically if the user * taps outside it or presses the escape key. Disable this * behavior by setting the `autoCloseDisabled` property to true. * @attribute autoCloseDisabled * @type boolean * @default false */ autoCloseDisabled: false, /** * This property specifies an attribute on elements that should * close the overlay on tap. Should not set `closeSelector` if this * is set. * * @attribute closeAttribute * @type string * @default "core-overlay-toggle" */ closeAttribute: 'core-overlay-toggle', /** * This property specifies a selector matching elements that should * close the overlay on tap. Should not set `closeAttribute` if this * is set. * * @attribute closeSelector * @type string * @default "" */ closeSelector: '', /** * A `core-overlay` target's size is constrained to the window size. * The `margin` property specifies a pixel amount around the overlay * that will be reserved. It's useful for ensuring that, for example, * a shadow displayed outside the target will always be visible. * * @attribute margin * @type number * @default 0 */ margin: 0, /** * The transition property specifies a string which identifies a * <a href="../core-transition/">`core-transition`</a> element that * will be used to help the overlay open and close. The default * `core-transition-fade` will cause the overlay to fade in and out. * * @attribute transition * @type string * @default 'core-transition-fade' */ transition: 'core-transition-fade' }, captureEventName: 'tap', targetListeners: { 'tap': 'tapHandler', 'keydown': 'keydownHandler', 'core-transitionend': 'transitionend' }, registerCallback: function(element) { this.layer = document.createElement('core-overlay-layer'); this.keyHelper = document.createElement('core-key-helper'); this.meta = document.createElement('core-transition'); this.scrim = document.createElement('div'); this.scrim.className = 'core-overlay-backdrop'; }, ready: function() { this.target = this.target || this; // flush to ensure styles are installed before paint Platform.flush(); }, /** * Toggle the opened state of the overlay. * @method toggle */ toggle: function() { this.opened = !this.opened; }, /** * Open the overlay. This is equivalent to setting the `opened` * property to true. * @method open */ open: function() { this.opened = true; }, /** * Close the overlay. This is equivalent to setting the `opened` * property to false. * @method close */ close: function() { this.opened = false; }, domReady: function() { this.ensureTargetSetup(); }, targetChanged: function(old) { if (this.target) { // really make sure tabIndex is set if (this.target.tabIndex < 0) { this.target.tabIndex = -1; } this.addElementListenerList(this.target, this.targetListeners); this.target.style.display = 'none'; } if (old) { this.removeElementListenerList(old, this.targetListeners); var transition = this.getTransition(); if (transition) { transition.teardown(old); } else { old.style.position = ''; old.style.outline = ''; } old.style.display = ''; } }, // NOTE: wait to call this until we're as sure as possible that target // is styled. ensureTargetSetup: function() { if (!this.target || this.target.__overlaySetup) { return; } this.target.__overlaySetup = true; this.target.style.display = ''; var transition = this.getTransition(); if (transition) { transition.setup(this.target); } var computed = getComputedStyle(this.target); this.targetStyle = { position: computed.position === 'static' ? 'fixed' : computed.position } if (!transition) { this.target.style.position = this.targetStyle.position; this.target.style.outline = 'none'; } this.target.style.display = 'none'; }, openedChanged: function() { this.transitioning = true; this.ensureTargetSetup(); this.prepareRenderOpened(); // continue styling after delay so display state can change // without aborting transitions // note: we wait a full frame so that transition changes executed // during measuring do not cause transition this.async(function() { this.target.style.display = ''; this.async('renderOpened'); }); this.fire('core-overlay-open', this.opened); }, // tasks which must occur before opening; e.g. making the element visible prepareRenderOpened: function() { if (this.opened) { addOverlay(this); } this.prepareBackdrop(); // async so we don't auto-close immediately via a click. this.async(function() { if (!this.autoCloseDisabled) { this.enableElementListener(this.opened, document, this.captureEventName, 'captureHandler', true); } }); this.enableElementListener(this.opened, window, 'resize', 'resizeHandler'); if (this.opened) { // TODO(sorvell): force SD Polyfill to render forcePolyfillRender(this.target); if (!this._shouldPosition) { this.target.style.position = 'absolute'; var computed = getComputedStyle(this.target); var t = (computed.top === 'auto' && computed.bottom === 'auto'); var l = (computed.left === 'auto' && computed.right === 'auto'); this.target.style.position = this.targetStyle.position; this._shouldPosition = {top: t, left: l}; } // if we are showing, then take care when measuring this.prepareMeasure(this.target); this.updateTargetDimensions(); this.finishMeasure(this.target); if (this.layered) { this.layer.addElement(this.target); this.layer.opened = this.opened; } } }, // tasks which cause the overlay to actually open; typically play an // animation renderOpened: function() { var transition = this.getTransition(); if (transition) { transition.go(this.target, {opened: this.opened}); } else { this.transitionend(); } this.renderBackdropOpened(); }, // finishing tasks; typically called via a transition transitionend: function(e) { // make sure this is our transition event. if (e && e.target !== this.target) { return; } this.transitioning = false; if (!this.opened) { this.resetTargetDimensions(); this.target.style.display = 'none'; this.completeBackdrop(); removeOverlay(this); if (this.layered) { if (!currentOverlay()) { this.layer.opened = this.opened; } this.layer.removeElement(this.target); } } this.applyFocus(); }, prepareBackdrop: function() { if (this.backdrop && this.opened) { if (!this.scrim.parentNode) { document.body.appendChild(this.scrim); this.scrim.style.zIndex = currentOverlayZ() - 1; } trackBackdrop(this); } }, renderBackdropOpened: function() { if (this.backdrop && getBackdrops().length < 2) { this.scrim.classList.toggle('core-opened', this.opened); } }, completeBackdrop: function() { if (this.backdrop) { trackBackdrop(this); if (getBackdrops().length === 0) { this.scrim.parentNode.removeChild(this.scrim); } } }, prepareMeasure: function(target) { target.style.transition = target.style.webkitTransition = 'none'; target.style.transform = target.style.webkitTransform = 'none'; target.style.display = ''; }, finishMeasure: function(target) { target.style.display = 'none'; target.style.transform = target.style.webkitTransform = ''; target.style.transition = target.style.webkitTransition = ''; }, getTransition: function() { return this.meta.byId(this.transition); }, getFocusNode: function() { return this.target.querySelector('[autofocus]') || this.target; }, applyFocus: function() { var focusNode = this.getFocusNode(); if (this.opened) { focusNode.focus(); } else { focusNode.blur(); if (currentOverlay() == this) { console.warn('Current core-overlay is attempting to focus itself as next! (bug)'); } else { focusOverlay(); } } }, updateTargetDimensions: function() { this.positionTarget(); this.sizeTarget(); // if (this.layered) { var rect = this.target.getBoundingClientRect(); this.target.style.top = rect.top + 'px'; this.target.style.left = rect.left + 'px'; this.target.style.right = this.target.style.bottom = 'auto'; } }, sizeTarget: function() { var sizer = this.sizingTarget || this.target; var rect = sizer.getBoundingClientRect(); var mt = rect.top === this.margin ? this.margin : this.margin * 2; var ml = rect.left === this.margin ? this.margin : this.margin * 2; var h = window.innerHeight - rect.top - mt; var w = window.innerWidth - rect.left - ml; sizer.style.maxHeight = h + 'px'; sizer.style.maxWidth = w + 'px'; sizer.style.boxSizing = 'border-box'; }, positionTarget: function() { // vertically and horizontally center if not positioned if (this._shouldPosition.top) { var t = Math.max((window.innerHeight - this.target.offsetHeight - this.margin*2) / 2, this.margin); this.target.style.top = t + 'px'; } if (this._shouldPosition.left) { var l = Math.max((window.innerWidth - this.target.offsetWidth - this.margin*2) / 2, this.margin); this.target.style.left = l + 'px'; } }, resetTargetDimensions: function() { this.target.style.top = this.target.style.left = ''; this.target.style.right = this.target.style.bottom = ''; this.target.style.width = this.target.style.height = ''; this._shouldPosition = null; }, tapHandler: function(e) { // closeSelector takes precedence since closeAttribute has a default non-null value. if (e.target && (this.closeSelector && e.target.matches(this.closeSelector)) || (this.closeAttribute && e.target.hasAttribute(this.closeAttribute))) { this.toggle(); } else { if (this.autoCloseJob) { this.autoCloseJob.stop(); this.autoCloseJob = null; } } }, // We use the traditional approach of capturing events on document // to to determine if the overlay needs to close. However, due to // ShadowDOM event retargeting, the event target is not useful. Instead // of using it, we attempt to close asynchronously and prevent the close // if a tap event is immediately heard on the target. // TODO(sorvell): This approach will not work with modal. For // this we need a scrim. captureHandler: function(e) { if (!this.autoCloseDisabled && (currentOverlay() == this)) { this.autoCloseJob = this.job(this.autoCloseJob, function() { this.close(); }); } }, keydownHandler: function(e) { if (!this.autoCloseDisabled && (e.keyCode == this.keyHelper.ESCAPE_KEY)) { this.close(); e.stopPropagation(); } }, /** * Extensions of core-overlay should implement the `resizeHandler` * method to adjust the size and position of the overlay when the * browser window resizes. * @method resizeHandler */ resizeHandler: function() { this.updateTargetDimensions(); }, // TODO(sorvell): these utility methods should not be here. addElementListenerList: function(node, events) { for (var i in events) { this.addElementListener(node, i, events[i]); } }, removeElementListenerList: function(node, events) { for (var i in events) { this.removeElementListener(node, i, events[i]); } }, enableElementListener: function(enable, node, event, methodName, capture) { if (enable) { this.addElementListener(node, event, methodName, capture); } else { this.removeElementListener(node, event, methodName, capture); } }, addElementListener: function(node, event, methodName, capture) { var fn = this._makeBoundListener(methodName); if (node && fn) { Polymer.addEventListener(node, event, fn, capture); } }, removeElementListener: function(node, event, methodName, capture) { var fn = this._makeBoundListener(methodName); if (node && fn) { Polymer.removeEventListener(node, event, fn, capture); } }, _makeBoundListener: function(methodName) { var self = this, method = this[methodName]; if (!method) { return; } var bound = '_bound' + methodName; if (!this[bound]) { this[bound] = function(e) { method.call(self, e); } } return this[bound]; }, }); function forcePolyfillRender(target) { if (window.ShadowDOMPolyfill) { target.offsetHeight; } } // TODO(sorvell): This should be an element with private state so it can // be independent of overlay. // track overlays for z-index and focus managemant var overlays = []; function addOverlay(overlay) { var z0 = currentOverlayZ(); overlays.push(overlay); var z1 = currentOverlayZ(); if (z1 <= z0) { applyOverlayZ(overlay, z0); } } function removeOverlay(overlay) { var i = overlays.indexOf(overlay); if (i >= 0) { overlays.splice(i, 1); setZ(overlay, ''); } } function applyOverlayZ(overlay, aboveZ) { setZ(overlay.target, aboveZ + 2); } function setZ(element, z) { element.style.zIndex = z; } function currentOverlay() { return overlays[overlays.length-1]; } var DEFAULT_Z = 10; function currentOverlayZ() { var z; var current = currentOverlay(); if (current) { var z1 = window.getComputedStyle(current.target).zIndex; if (!isNaN(z1)) { z = Number(z1); } } return z || DEFAULT_Z; } function focusOverlay() { var current = currentOverlay(); // We have to be careful to focus the next overlay _after_ any current // transitions are complete (due to the state being toggled prior to the // transition). Otherwise, we risk infinite recursion when a transitioning // (closed) overlay becomes the current overlay. // // NOTE: We make the assumption that any overlay that completes a transition // will call into focusOverlay to kick the process back off. Currently: // transitionend -> applyFocus -> focusOverlay. if (current && !current.transitioning) { current.applyFocus(); } } var backdrops = []; function trackBackdrop(element) { if (element.opened) { backdrops.push(element); } else { var i = backdrops.indexOf(element); if (i >= 0) { backdrops.splice(i, 1); } } } function getBackdrops() { return backdrops; } })(); ; Polymer('core-transition-css', { /** * The class that will be applied to all animated nodes. * * @attribute baseClass * @type string * @default "core-transition" */ baseClass: 'core-transition', /** * The class that will be applied to nodes in the opened state. * * @attribute openedClass * @type string * @default "core-opened" */ openedClass: 'core-opened', /** * The class that will be applied to nodes in the closed state. * * @attribute closedClass * @type string * @default "core-closed" */ closedClass: 'core-closed', /** * Event to listen to for animation completion. * * @attribute completeEventName * @type string * @default "transitionEnd" */ completeEventName: 'transitionend', publish: { /** * A secondary configuration attribute for the animation. The class * `<baseClass>-<transitionType` is applied to the animated node during * `setup`. * * @attribute transitionType * @type string */ transitionType: null }, registerCallback: function(element) { this.transitionStyle = element.templateContent().firstElementChild; }, // template is just for loading styles, we don't need a shadowRoot fetchTemplate: function() { return null; }, go: function(node, state) { if (state.opened !== undefined) { this.transitionOpened(node, state.opened); } }, setup: function(node) { if (!node._hasTransitionStyle) { if (!node.shadowRoot) { node.createShadowRoot().innerHTML = '<content></content>'; } this.installScopeStyle(this.transitionStyle, 'transition', node.shadowRoot); node._hasTransitionStyle = true; } node.classList.add(this.baseClass); if (this.transitionType) { node.classList.add(this.baseClass + '-' + this.transitionType); } }, teardown: function(node) { node.classList.remove(this.baseClass); if (this.transitionType) { node.classList.remove(this.baseClass + '-' + this.transitionType); } }, transitionOpened: function(node, opened) { this.listenOnce(node, this.completeEventName, function() { node.classList.toggle(this.revealedClass, opened); if (!opened) { node.classList.remove(this.closedClass); } this.complete(node); }); node.classList.toggle(this.openedClass, opened); node.classList.toggle(this.closedClass, !opened); } }); ; Polymer('core-media-query', { /** * The Boolean return value of the media query * * @attribute queryMatches * @type Boolean * @default false */ queryMatches: false, /** * The CSS media query to evaulate * * @attribute query * @type string * @default '' */ query: '', ready: function() { this._mqHandler = this.queryHandler.bind(this); this._mq = null; }, queryChanged: function() { if (this._mq) { this._mq.removeListener(this._mqHandler); } var query = this.query; if (query[0] !== '(') { query = '(' + this.query + ')'; } this._mq = window.matchMedia(query); this._mq.addListener(this._mqHandler); this.queryHandler(this._mq); }, queryHandler: function(mq) { this.queryMatches = mq.matches; this.asyncFire('core-media-change', mq); } }); ; (function() { var currentToast; Polymer('paper-toast', { /** * The text shows in a toast. * * @attribute text * @type string * @default '' */ text: '', /** * The duration in milliseconds to show the toast. * * @attribute duration * @type number * @default 3000 */ duration: 3000, /** * Set opened to true to show the toast and to false to hide it. * * @attribute opened * @type boolean * @default false */ opened: false, /** * Min-width when the toast changes to narrow layout. In narrow layout, * the toast fits at the bottom of the screen when opened. * * @attribute responsiveWidth * @type string * @default '480px' */ responsiveWidth: '480px', /** * If true, the toast can't be swiped. * * @attribute swipeDisabled * @type boolean * @default false */ swipeDisabled: false, eventDelegates: { trackstart: 'trackStart', track: 'track', trackend: 'trackEnd', transitionend: 'transitionEnd' }, narrowModeChanged: function() { this.classList.toggle('fit-bottom', this.narrowMode); }, openedChanged: function() { if (this.opened) { this.dismissJob = this.job(this.dismissJob, this.dismiss, this.duration); } else { this.dismissJob && this.dismissJob.stop(); this.dismiss(); } }, /** * Toggle the opened state of the toast. * @method toggle */ toggle: function() { this.opened = !this.opened; }, /** * Show the toast for the specified duration * @method show */ show: function() { if (currentToast) { currentToast.dismiss(); } currentToast = this; this.opened = true; }, /** * Dismiss the toast and hide it. * @method dismiss */ dismiss: function() { if (this.dragging) { this.shouldDismiss = true; } else { this.opened = false; if (currentToast === this) { currentToast = null; } } }, trackStart: function(e) { if (!this.swipeDisabled) { e.preventTap(); this.vertical = e.yDirection; this.w = this.offsetWidth; this.h = this.offsetHeight; this.dragging = true; this.classList.add('dragging'); } }, track: function(e) { if (this.dragging) { var s = this.style; if (this.vertical) { var y = e.dy; s.opacity = (this.h - Math.abs(y)) / this.h; s.webkitTransform = s.transform = 'translate3d(0, ' + y + 'px, 0)'; } else { var x = e.dx; s.opacity = (this.w - Math.abs(x)) / this.w; s.webkitTransform = s.transform = 'translate3d(' + x + 'px, 0, 0)'; } } }, trackEnd: function(e) { if (this.dragging) { this.classList.remove('dragging'); this.style.opacity = null; this.style.webkitTransform = this.style.transform = null; var cl = this.classList; if (this.vertical) { cl.toggle('fade-out-down', e.yDirection === 1 && e.dy > 0); cl.toggle('fade-out-up', e.yDirection === -1 && e.dy < 0); } else { cl.toggle('fade-out-right', e.xDirection === 1 && e.dx > 0); cl.toggle('fade-out-left', e.xDirection === -1 && e.dx < 0); } this.dragging = false; } }, transitionEnd: function() { var cl = this.classList; if (cl.contains('fade-out-right') || cl.contains('fade-out-left') || cl.contains('fade-out-down') || cl.contains('fade-out-up')) { this.dismiss(); cl.remove('fade-out-right', 'fade-out-left', 'fade-out-down', 'fade-out-up'); } else if (this.shouldDismiss) { this.dismiss(); } this.shouldDismiss = false; } }); })(); ; Polymer('core-range', { /** * The number that represents the current value. * * @attribute value * @type number * @default 0 */ value: 0, /** * The number that indicates the minimum value of the range. * * @attribute min * @type number * @default 0 */ min: 0, /** * The number that indicates the maximum value of the range. * * @attribute max * @type number * @default 100 */ max: 100, /** * Specifies the value granularity of the range's value. * * @attribute step * @type number * @default 1 */ step: 1, /** * Returns the ratio of the value. * * @attribute ratio * @type number * @default 0 */ ratio: 0, observe: { 'value min max step': 'update' }, calcRatio: function(value) { return (this.clampValue(value) - this.min) / (this.max - this.min); }, clampValue: function(value) { return Math.min(this.max, Math.max(this.min, this.calcStep(value))); }, calcStep: function(value) { return this.step ? (Math.round(value / this.step) / (1 / this.step)) : value; }, validateValue: function() { var v = this.clampValue(this.value); this.value = this.oldValue = isNaN(v) ? this.oldValue : v; return this.value !== v; }, update: function() { this.validateValue(); this.ratio = this.calcRatio(this.value) * 100; } }); ; Polymer('paper-progress', { /** * The number that represents the current secondary progress. * * @attribute secondaryProgress * @type number * @default 0 */ secondaryProgress: 0, step: 0, observe: { 'value secondaryProgress min max': 'update' }, update: function() { this.super(); this.secondaryProgress = this.clampValue(this.secondaryProgress); this.secondaryRatio = this.calcRatio(this.secondaryProgress) * 100; } }); ; Polymer('core-input', { publish: { /** * Placeholder text that hints to the user what can be entered in * the input. * * @attribute placeholder * @type string * @default '' */ placeholder: '', /** * If true, this input cannot be focused and the user cannot change * its value. * * @attribute disabled * @type boolean * @default false */ disabled: false, /** * If true, the user cannot modify the value of the input. * * @attribute readonly * @type boolean * @default false */ readonly: false, /** * If true, this input will automatically gain focus on page load. * * @attribute autofocus * @type boolean * @default false */ autofocus: false, /** * If true, this input accepts multi-line input like a `<textarea>` * * @attribute multiline * @type boolean * @default false */ multiline: false, /** * (multiline only) The height of this text input in rows. The input * will scroll internally if more input is entered beyond the size * of the component. This property is meaningless if multiline is * false. You can also set this property to "fit" and size the * component with CSS to make the input fit the CSS size. * * @attribute rows * @type number|'fit' * @default 'fit' */ rows: 'fit', /** * The current value of this input. Changing inputValue programmatically * will cause value to be out of sync. Instead, change value directly * or call commit() after changing inputValue. * * @attribute inputValue * @type string * @default '' */ inputValue: '', /** * The value of the input committed by the user, either by changing the * inputValue and blurring the input, or by hitting the `enter` key. * * @attribute value * @type string * @default '' */ value: '', /** * Set the input type. Not supported for `multiline`. * * @attribute type * @type string * @default text */ type: 'text', /** * If true, the input is invalid if its value is null. * * @attribute required * @type boolean * @default false */ required: false, /** * A regular expression to validate the input value against. See * https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation#Validation-related_attributes * for more info. Not supported if `multiline` is true. * * @attribute pattern * @type string * @default '.*' */ // FIXME(yvonne): The default is set to .* because we can't bind to pattern such // that the attribute is unset if pattern is null. pattern: '.*', /** * If set, the input is invalid if the value is less than this property. See * https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation#Validation-related_attributes * for more info. Not supported if `multiline` is true. * * @attribute min */ min: null, /** * If set, the input is invalid if the value is greater than this property. See * https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation#Validation-related_attributes * for more info. Not supported if `multiline` is true. * * @attribute max */ max: null, /** * If set, the input is invalid if the value is not `min` plus an integral multiple * of this property. See * https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation#Validation-related_attributes * for more info. Not supported if `multiline` is true. * * @attribute step */ step: null, /** * The maximum length of the input value. * * @attribute maxlength * @type number */ maxlength: null, /** * If this property is true, the text input's inputValue failed validation. * * @attribute invalid * @type boolean * @default false */ invalid: false }, ready: function() { this.handleTabindex(this.getAttribute('tabindex')); }, invalidChanged: function() { this.classList.toggle('invalid', this.invalid); this.fire('input-'+ (this.invalid ? 'invalid' : 'valid'), {value: this.inputValue}); }, inputValueChanged: function() { this.updateValidity_(); }, valueChanged: function() { this.inputValue = this.value; }, requiredChanged: function() { this.updateValidity_(); }, attributeChanged: function(attr, oldVal, curVal) { if (attr === 'tabindex') { this.handleTabindex(curVal); } }, handleTabindex: function(tabindex) { if (tabindex > 0) { this.$.input.setAttribute('tabindex', -1); } else { this.$.input.removeAttribute('tabindex'); } }, /** * Commits the inputValue to value. * * @method commit */ commit: function() { this.value = this.inputValue; }, updateValidity_: function() { if (this.$.input.willValidate) { this.invalid = !this.$.input.validity.valid; } }, keydownAction: function() { // for type = number, the value is the empty string unless the input is a valid number. // FIXME(yvonne): check other types if (this.type === 'number') { this.async(function() { this.updateValidity_(); }); } }, inputChangeAction: function() { this.commit(); if (!window.ShadowDOMPolyfill) { // re-fire event that does not bubble across shadow roots this.fire('change', null, this); } }, focusAction: function(e) { if (this.getAttribute('tabindex') > 0) { // Forward focus to the inner input if tabindex is set on the element // This will not cause an infinite loop because focus will not fire on the <input> // again if it's already focused. this.$.input.focus(); } }, inputFocusAction: function(e) { if (window.ShadowDOMPolyfill) { // re-fire non-bubbling event if polyfill this.fire('focus', null, this, false); } }, inputBlurAction: function() { if (window.ShadowDOMPolyfill) { // re-fire non-bubbling event this.fire('blur', null, this, false); } }, blur: function() { // forward blur method to the internal input / textarea element this.$.input.blur(); }, click: function() { // forward click method to the internal input / textarea element this.$.input.click(); }, focus: function() { // forward focus method to the internal input / textarea element this.$.input.focus(); }, select: function() { // forward select method to the internal input / textarea element this.$.input.focus(); }, setSelectionRange: function(selectionStart, selectionEnd, selectionDirection) { // forward setSelectionRange method to the internal input / textarea element this.$.input.setSelectionRange(selectionStart, selectionEnd, selectionDirection); }, setRangeText: function(replacement, start, end, selectMode) { // forward setRangeText method to the internal input element if (!this.multiline) { this.$.input.setRangeText(replacement, start, end, selectMode); } }, stepDown: function(n) { // forward stepDown method to the internal input element if (!this.multiline) { this.$.input.stepDown(n); } }, stepUp: function(n) { // forward stepUp method to the internal input element if (!this.multiline) { this.$.input.stepUp(n); } }, get willValidate() { return this.$.input.willValidate; }, get validity() { return this.$.input.validity; }, get validationMessage() { return this.$.input.validationMessage; }, checkValidity: function() { var r = this.$.input.checkValidity(); this.updateValidity_(); return r; }, setCustomValidity: function(message) { this.$.input.setCustomValidity(message); this.updateValidity_(); } }); ; (function() { window.CoreStyle = window.CoreStyle || { g: {}, list: {}, refMap: {} }; Polymer('core-style', { /** * The `id` property should be set if the `core-style` is a producer * of styles. In this case, the `core-style` should have text content * that is cssText. * * @attribute id * @type string * @default '' */ publish: { /** * The `ref` property should be set if the `core-style` element is a * consumer of styles. Set it to the `id` of the desired `core-style` * element. * * @attribute ref * @type string * @default '' */ ref: '' }, // static g: CoreStyle.g, refMap: CoreStyle.refMap, /** * The `list` is a map of all `core-style` producers stored by `id`. It * should be considered readonly. It's useful for nesting one `core-style` * inside another. * * @attribute list * @type object (readonly) * @default {map of all `core-style` producers} */ list: CoreStyle.list, // if we have an id, we provide style // if we have a ref, we consume/require style ready: function() { if (this.id) { this.provide(); } else { this.registerRef(this.ref); if (!window.ShadowDOMPolyfill) { this.require(); } } }, // can't shim until attached if using SD polyfill because need to find host attached: function() { if (!this.id && window.ShadowDOMPolyfill) { this.require(); } }, /****** producer stuff *******/ provide: function() { this.register(); // we want to do this asap, especially so we can do so before definitions // that use this core-style are registered. if (this.textContent) { this._completeProvide(); } else { this.async(this._completeProvide); } }, register: function() { var i = this.list[this.id]; if (i) { if (!Array.isArray(i)) { this.list[this.id] = [i]; } this.list[this.id].push(this); } else { this.list[this.id] = this; } }, // stamp into a shadowRoot so we can monitor dom of the bound output _completeProvide: function() { this.createShadowRoot(); this.domObserver = new MutationObserver(this.domModified.bind(this)) .observe(this.shadowRoot, {subtree: true, characterData: true, childList: true}); this.provideContent(); }, provideContent: function() { this.ensureTemplate(); this.shadowRoot.textContent = ''; this.shadowRoot.appendChild(this.instanceTemplate(this.template)); this.cssText = this.shadowRoot.textContent; }, ensureTemplate: function() { if (!this.template) { this.template = this.querySelector('template:not([repeat]):not([bind])'); // move content into the template if (!this.template) { this.template = document.createElement('template'); var n = this.firstChild; while (n) { this.template.content.appendChild(n.cloneNode(true)); n = n.nextSibling; } } } }, domModified: function() { this.cssText = this.shadowRoot.textContent; this.notify(); }, // notify instances that reference this element notify: function() { var s$ = this.refMap[this.id]; if (s$) { for (var i=0, s; (s=s$[i]); i++) { s.require(); } } }, /****** consumer stuff *******/ registerRef: function(ref) { //console.log('register', ref); this.refMap[this.ref] = this.refMap[this.ref] || []; this.refMap[this.ref].push(this); }, applyRef: function(ref) { this.ref = ref; this.registerRef(this.ref); this.require(); }, require: function() { var cssText = this.cssTextForRef(this.ref); //console.log('require', this.ref, cssText); if (cssText) { this.ensureStyleElement(); // do nothing if cssText has not changed if (this.styleElement._cssText === cssText) { return; } this.styleElement._cssText = cssText; if (window.ShadowDOMPolyfill) { this.styleElement.textContent = cssText; cssText = Platform.ShadowCSS.shimStyle(this.styleElement, this.getScopeSelector()); } this.styleElement.textContent = cssText; } }, cssTextForRef: function(ref) { var s$ = this.byId(ref); var cssText = ''; if (s$) { if (Array.isArray(s$)) { var p = []; for (var i=0, l=s$.length, s; (i<l) && (s=s$[i]); i++) { p.push(s.cssText); } cssText = p.join('\n\n'); } else { cssText = s$.cssText; } } if (s$ && !cssText) { console.warn('No styles provided for ref:', ref); } return cssText; }, byId: function(id) { return this.list[id]; }, ensureStyleElement: function() { if (!this.styleElement) { this.styleElement = window.ShadowDOMPolyfill ? this.makeShimStyle() : this.makeRootStyle(); } if (!this.styleElement) { console.warn(this.localName, 'could not setup style.'); } }, makeRootStyle: function() { var style = document.createElement('style'); this.appendChild(style); return style; }, makeShimStyle: function() { var host = this.findHost(this); if (host) { var name = host.localName; var style = document.querySelector('style[' + name + '=' + this.ref +']'); if (!style) { style = document.createElement('style'); style.setAttribute(name, this.ref); document.head.appendChild(style); } return style; } }, getScopeSelector: function() { if (!this._scopeSelector) { var selector = '', host = this.findHost(this); if (host) { var typeExtension = host.hasAttribute('is'); var name = typeExtension ? host.getAttribute('is') : host.localName; selector = Platform.ShadowCSS.makeScopeSelector(name, typeExtension); } this._scopeSelector = selector; } return this._scopeSelector; }, findHost: function(node) { while (node.parentNode) { node = node.parentNode; } return node.host || wrap(document.documentElement); }, /* filters! */ // TODO(dfreedm): add more filters! cycle: function(rgb, amount) { if (rgb.match('#')) { var o = this.hexToRgb(rgb); if (!o) { return rgb; } rgb = 'rgb(' + o.r + ',' + o.b + ',' + o.g + ')'; } function cycleChannel(v) { return Math.abs((Number(v) - amount) % 255); } return rgb.replace(/rgb\(([^,]*),([^,]*),([^,]*)\)/, function(m, a, b, c) { return 'rgb(' + cycleChannel(a) + ',' + cycleChannel(b) + ', ' + cycleChannel(c) + ')'; }); }, hexToRgb: function(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } }); })(); ; (function() { var paperInput = CoreStyle.g.paperInput = CoreStyle.g.paperInput || {}; paperInput.focusedColor = '#4059a9'; paperInput.invalidColor = '#d34336'; Polymer('paper-input', { /** * The label for this input. It normally appears as grey text inside * the text input and disappears once the user enters text. * * @attribute label * @type string * @default '' */ label: '', /** * If true, the label will "float" above the text input once the * user enters text instead of disappearing. * * @attribute floatingLabel * @type boolean * @default false */ floatingLabel: false, /** * (multiline only) If set to a non-zero value, the height of this * text input will grow with the value changes until it is maxRows * rows tall. If the maximum size does not fit the value, the text * input will scroll internally. * * @attribute maxRows * @type number * @default 0 */ maxRows: 0, /** * The message to display if the input value fails validation. If this * is unset or the empty string, a default message is displayed depending * on the type of validation error. * * @attribute error * @type string */ error: '', focused: false, pressed: false, attached: function() { if (this.multiline) { this.resizeInput(); window.requestAnimationFrame(function() { this.$.underlineContainer.classList.add('animating'); }.bind(this)); } }, resizeInput: function() { var height = this.$.inputClone.getBoundingClientRect().height; var bounded = this.maxRows > 0 || this.rows > 0; if (bounded) { var minHeight = this.$.minInputHeight.getBoundingClientRect().height; var maxHeight = this.$.maxInputHeight.getBoundingClientRect().height; height = Math.max(minHeight, Math.min(height, maxHeight)); } this.$.inputContainer.style.height = height + 'px'; this.$.underlineContainer.style.top = height + 'px'; }, prepareLabelTransform: function() { var toRect = this.$.floatedLabelSpan.getBoundingClientRect(); var fromRect = this.$.labelSpan.getBoundingClientRect(); if (toRect.width !== 0) { this.$.label.cachedTransform = 'scale(' + (toRect.width / fromRect.width) + ') ' + 'translateY(' + (toRect.bottom - fromRect.bottom) + 'px)'; } }, toggleLabel: function(force) { var v = force !== undefined ? force : this.inputValue; if (!this.floatingLabel) { this.$.label.classList.toggle('hidden', v); } if (this.floatingLabel && !this.focused) { this.$.label.classList.toggle('hidden', v); this.$.floatedLabel.classList.toggle('hidden', !v); } }, rowsChanged: function() { if (this.multiline && !isNaN(parseInt(this.rows))) { this.$.minInputHeight.innerHTML = ''; for (var i = 0; i < this.rows; i++) { this.$.minInputHeight.appendChild(document.createElement('br')); } this.resizeInput(); } }, maxRowsChanged: function() { if (this.multiline && !isNaN(parseInt(this.maxRows))) { this.$.maxInputHeight.innerHTML = ''; for (var i = 0; i < this.maxRows; i++) { this.$.maxInputHeight.appendChild(document.createElement('br')); } this.resizeInput(); } }, inputValueChanged: function() { this.super(); if (this.multiline) { var escaped = this.inputValue.replace(/\n/gm, '<br>'); if (!escaped || escaped.lastIndexOf('<br>') === escaped.length - 4) { escaped += '&nbsp'; } this.$.inputCloneSpan.innerHTML = escaped; this.resizeInput(); } this.toggleLabel(); }, labelChanged: function() { if (this.floatingLabel && this.$.floatedLabel && this.$.label) { // If the element is created programmatically, labelChanged is called before // binding. Run the measuring code in async so the DOM is ready. this.async(function() { this.prepareLabelTransform(); }); } }, placeholderChanged: function() { this.label = this.placeholder; }, inputFocusAction: function() { if (!this.pressed) { if (this.floatingLabel) { this.$.floatedLabel.classList.remove('hidden'); this.$.floatedLabel.classList.add('focused'); this.$.floatedLabel.classList.add('focusedColor'); } this.$.label.classList.add('hidden'); this.$.underlineHighlight.classList.add('focused'); this.$.caret.classList.add('focused'); this.super(arguments); } this.focused = true; }, shouldFloatLabel: function() { // if type = number, the input value is the empty string until a valid number // is entered so we must do some hacks here return this.inputValue || (this.type === 'number' && !this.validity.valid); }, inputBlurAction: function() { this.super(arguments); this.$.underlineHighlight.classList.remove('focused'); this.$.caret.classList.remove('focused'); if (this.floatingLabel) { this.$.floatedLabel.classList.remove('focused'); this.$.floatedLabel.classList.remove('focusedColor'); if (!this.shouldFloatLabel()) { this.$.floatedLabel.classList.add('hidden'); } } // type = number hack. see core-input for more info if (!this.shouldFloatLabel()) { this.$.label.classList.remove('hidden'); this.$.label.classList.add('animating'); this.async(function() { this.$.label.style.webkitTransform = 'none'; this.$.label.style.transform = 'none'; }); } this.focused = false; }, downAction: function(e) { if (this.disabled) { return; } if (this.focused) { return; } this.pressed = true; var rect = this.$.underline.getBoundingClientRect(); var right = e.x - rect.left; this.$.underlineHighlight.style.webkitTransformOriginX = right + 'px'; this.$.underlineHighlight.style.transformOriginX = right + 'px'; this.$.underlineHighlight.classList.remove('focused'); this.underlineAsync = this.async(function() { this.$.underlineHighlight.classList.add('pressed'); }, null, 200); // No caret animation if there is text in the input. if (!this.inputValue) { this.$.caret.classList.remove('focused'); } }, upAction: function(e) { if (this.disabled) { return; } if (!this.pressed) { return; } // if a touchevent caused the up, the synthentic mouseevents will blur // the input, make sure to prevent those from being generated. if (e._source === 'touch') { e.preventDefault(); } if (this.underlineAsync) { clearTimeout(this.underlineAsync); this.underlineAsync = null; } // Focus the input here to bring up the virtual keyboard. this.$.input.focus(); this.pressed = false; this.animating = true; this.$.underlineHighlight.classList.remove('pressed'); this.$.underlineHighlight.classList.add('animating'); this.async(function() { this.$.underlineHighlight.classList.add('focused'); }); // No caret animation if there is text in the input. if (!this.inputValue) { this.$.caret.classList.add('animating'); this.async(function() { this.$.caret.classList.add('focused'); }, null, 100); } if (this.floatingLabel) { this.$.label.classList.add('focusedColor'); this.$.label.classList.add('animating'); if (!this.$.label.cachedTransform) { this.prepareLabelTransform(); } this.$.label.style.webkitTransform = this.$.label.cachedTransform; this.$.label.style.transform = this.$.label.cachedTransform; } }, keydownAction: function() { this.super(); // more type = number hacks. see core-input for more info if (this.type === 'number') { this.async(function() { if (!this.inputValue) { this.toggleLabel(!this.validity.valid); } }); } }, keypressAction: function() { if (this.animating) { this.transitionEndAction(); } }, transitionEndAction: function(e) { this.animating = false; if (this.pressed) { return; } if (this.focused) { if (this.floatingLabel || this.inputValue) { this.$.label.classList.add('hidden'); } if (this.floatingLabel) { this.$.label.classList.remove('focusedColor'); this.$.label.classList.remove('animating'); this.$.floatedLabel.classList.remove('hidden'); this.$.floatedLabel.classList.add('focused'); this.$.floatedLabel.classList.add('focusedColor'); } this.async(function() { this.$.underlineHighlight.classList.remove('animating'); this.$.caret.classList.remove('animating'); }, null, 100); } else { this.$.label.classList.remove('animating'); } } }); }()); ; Polymer('paper-slider', { /** * Fired when the slider's value changes. * * @event change */ /** * Fired when the slider's value changes due to manual interaction. * * Changes to the slider's value due to changes in an underlying * bound variable will not trigger this event. * * @event manual-change */ /** * If true, the slider thumb snaps to tick marks evenly spaced based * on the `step` property value. * * @attribute snaps * @type boolean * @default false */ snaps: false, /** * If true, a pin with numeric value label is shown when the slider thumb * is pressed. Use for settings for which users need to know the exact * value of the setting. * * @attribute pin * @type boolean * @default false */ pin: false, /** * If true, this slider is disabled. A disabled slider cannot be tapped * or dragged to change the slider value. * * @attribute disabled * @type boolean * @default false */ disabled: false, /** * The number that represents the current secondary progress. * * @attribute secondaryProgress * @type number * @default 0 */ secondaryProgress: 0, /** * If true, an input is shown and user can use it to set the slider value. * * @attribute editable * @type boolean * @default false */ editable: false, /** * The immediate value of the slider. This value is updated while the user * is dragging the slider. * * @attribute immediateValue * @type number * @default 0 */ observe: { 'min max step snaps': 'update' }, ready: function() { this.update(); }, update: function() { this.positionKnob(this.calcRatio(this.value)); this.updateMarkers(); }, valueChanged: function() { this.update(); this.fire('change'); }, expandKnob: function() { this.$.sliderKnob.classList.add('expand'); }, resetKnob: function() { this.expandJob && this.expandJob.stop(); this.$.sliderKnob.classList.remove('expand'); }, positionKnob: function(ratio) { this._ratio = ratio; this.immediateValue = this.calcStep(this.calcKnobPosition()) || 0; if (this.snaps) { this._ratio = this.calcRatio(this.immediateValue); } this.$.sliderKnob.style.left = this._ratio * 100 + '%'; }, immediateValueChanged: function() { this.$.sliderKnob.classList.toggle('ring', this.immediateValue <= this.min); }, inputChange: function() { this.value = this.$.input.value; this.fire('manual-change'); }, calcKnobPosition: function() { return (this.max - this.min) * this._ratio + this.min; }, measureWidth: function() { this._w = this.$.sliderBar.offsetWidth; }, trackStart: function(e) { this.measureWidth(); this._x = this._ratio * this._w; this._startx = this._x || 0; this._minx = - this._startx; this._maxx = this._w - this._startx; this.$.sliderKnob.classList.add('dragging'); e.preventTap(); }, trackx: function(e) { var x = Math.min(this._maxx, Math.max(this._minx, e.dx)); this._x = this._startx + x; this._ratio = this._x / this._w; this.immediateValue = this.calcStep(this.calcKnobPosition()) || 0; var s = this.$.sliderKnob.style; s.transform = s.webkitTransform = 'translate3d(' + (this.snaps ? (this.calcRatio(this.immediateValue) * this._w) - this._startx : x) + 'px, 0, 0)'; }, trackEnd: function() { var s = this.$.sliderKnob.style; s.transform = s.webkitTransform = ''; this.$.sliderKnob.classList.remove('dragging'); this.resetKnob(); this.value = this.immediateValue; this.fire('manual-change'); }, bardown: function(e) { this.measureWidth(); this.$.sliderKnob.classList.add('transiting'); var rect = this.$.sliderBar.getBoundingClientRect(); this.positionKnob((e.x - rect.left) / this._w); this.value = this.calcStep(this.calcKnobPosition()); this.expandJob = this.job(this.expandJob, this.expandKnob, 60); this.fire('manual-change'); }, knobTransitionEnd: function() { this.$.sliderKnob.classList.remove('transiting'); }, updateMarkers: function() { this.markers = [], l = (this.max - this.min) / this.step; for (var i = 0; i < l; i++) { this.markers.push(''); } }, increment: function() { this.value = this.clampValue(this.value + this.step); }, decrement: function() { this.value = this.clampValue(this.value - this.step); }, keydown: function(e) { if (this.disabled) { return; } var c = e.keyCode; if (c === 37) { this.decrement(); this.fire('manual-change'); } else if (c === 39) { this.increment(); this.fire('manual-change'); } } }); ; Polymer('spotify-player', { /** * `spotify` is the reference to the Spotify Object * * @attribute spotify * @type JSON */ spotify: null, /** * Update Progress Bar and Player buttons */ observe: { 'spotify.track.time': 'updateProgress', 'spotify.track.length': 'updateProgress', 'spotify.player.status': 'updateStatus' }, /** * Update Progress Bar * @param oldValue Old time or length * @param newValue New time or length */ updateProgress: function(oldValue, newValue) { var time = this.spotify.track.time.split(':'); var timeSeconds = (+time[0]) * 60 + (+time[1]); var length = this.spotify.track.length.split(':'); var lengthSeconds = (+length[0]) * 60 + (+length[1]); if (timeSeconds == 0) { this.$.progress.value = 0; this.$.progress.max = 1; } else { this.$.progress.value = timeSeconds; this.$.progress.max = lengthSeconds; } }, /** * Update Player buttons * @param oldValue Old Player status * @param newValue New Player status */ updateStatus: function (oldValue, newValue) { if (newValue == 'playing') this.shadowRoot.querySelector("#play-pause > i.fa-play").hidden = true; else this.shadowRoot.querySelector("#play-pause > i.fa-play").hidden = false; if (newValue == 'pause') this.shadowRoot.querySelector("#play-pause > i.fa-pause").hidden = true; else this.shadowRoot.querySelector("#play-pause > i.fa-pause").hidden = false; }, /** * Play/Pause Spotify Player */ playAction: function(event, detail, sender) { playPauseTrack(); // TODO: Change call to global function! console.log("playAction!"); }, /** * Change to the previous track */ previousAction: function(event, detail, sender) { previousTrack(); // TODO: Change call to global function! console.log("previousTrack!"); }, /** * Change to the next track */ nextAction: function(event, detail, sender) { nextTrack(); // TODO: Change call to global function! console.log("nextAction!"); }, /** * Open a new tab with Spotify Play */ openSpotifyPlayAction: function(event, detail, sender) { openSpotifyPlay(); // TODO: Change call to global function! console.log("openSpotifyPlay!"); } }); ; (function() { Polymer('core-list', { publish: { /** * Fired when an item element is tapped. * * @event core-activate * @param {Object} detail * @param {Object} detail.item the item element */ /** * * An array of source data for the list to display. * * @attribute data * @type array * @default null */ data: null, /** * * An optional element on which to listen for scroll events. * * @attribute scrollTarget * @type Element * @default core-list */ scrollTarget: null, /** * * The height of a list item. `core-list` currently supports only fixed-height * list items. This height must be specified via the height property. * * @attribute height * @type number * @default 80 */ height: 80, /** * * The number of extra items rendered above the minimum set required to * fill the list's height. * * @attribute extraItems * @type number * @default 30 */ extraItems: 30, /** * * The property set on the list view data to represent selection state. * This should set so that it does not conflict with other data properties. * Note, selection data is not stored on the data in given in the data property. * * @attribute selectedProperty * @type string * @default 'selected' */ selectedProperty: 'selected', // TODO(sorvell): experimental /** * * If true, data is sync'd from the list back to the list's data. * * @attribute sync * @type boolean * @default false */ sync: false, /** * * Set to true to support multiple selection. * * @attribute multi * @type boolean * @default false */ multi: false }, observe: { 'data template scrollTarget': 'initialize' }, ready: function() { this.clearSelection(); this._boundScrollHandler = this.scrollHandler.bind(this); }, attached: function() { this.template = this.querySelector('template'); }, // TODO(sorvell): it'd be nice to dispense with 'data' and just use // template repeat's model. However, we need tighter integration // with TemplateBinding for this. initialize: function() { if (!this.data || !this.template) { return; } var target = this.scrollTarget || this; if (this._target !== target) { if (this._target) { this._target.removeEventListener('scroll', this._boundScrollHandler, false); } this._target = target; this._target.addEventListener('scroll', this._boundScrollHandler, false); } this.initializeViewport(); this.initalizeData(); this.onMutation(this, this.initializeItems); }, // TODO(sorvell): need to handle resizing initializeViewport: function() { this.$.viewport.style.height = this.height * this.data.length + 'px'; this._visibleCount = Math.ceil(this._target.offsetHeight / this.height); this._physicalCount = Math.min(this._visibleCount + this.extraItems, this.data.length); this._physicalHeight = this.height * this._physicalCount; }, // TODO(sorvell): selection currently cannot be maintained when // items are added or deleted. initalizeData: function() { var exampleDatum = this.data[0] || {}; this._propertyNames = Object.getOwnPropertyNames(exampleDatum); this._physicalData = new Array(this._physicalCount); for (var i = 0; i < this._physicalCount; ++i) { this._physicalData[i] = {}; this.updateItem(i, i); } this.template.model = this._physicalData; this.template.setAttribute('repeat', ''); }, initializeItems: function() { this._physicalItems = new Array(this._physicalCount); for (var i = 0, item = this.template.nextElementSibling; item && i < this._physicalCount; ++i, item = item.nextElementSibling) { this._physicalItems[i] = item; item._transformValue = 0; } this.refresh(false); }, updateItem: function(virtualIndex, physicalIndex) { var virtualDatum = this.data[virtualIndex]; var physicalDatum = this._physicalData[physicalIndex]; this.pushItemData(virtualDatum, physicalDatum); physicalDatum._physicalIndex = physicalIndex; physicalDatum._virtualIndex = virtualIndex; if (this.selectedProperty) { physicalDatum[this.selectedProperty] = this._selectedData.get(virtualDatum); } }, pushItemData: function(source, dest) { for (var i = 0; i < this._propertyNames.length; ++i) { var propertyName = this._propertyNames[i]; dest[propertyName] = source[propertyName]; } }, // experimental: push physical data back to this.data. // this is optional when scrolling and needs to be called at other times. syncData: function() { if (this.firstPhysicalIndex === undefined || this.baseVirtualIndex === undefined) { return; } var p, v; for (var i = 0; i < this.firstPhysicalIndex; ++i) { p = this._physicalData[i]; v = this.data[this.baseVirtualIndex + this._physicalCount + i]; this.pushItemData(p, v); } for (var i = this.firstPhysicalIndex; i < this._physicalCount; ++i) { p = this._physicalData[i]; v = this.data[this.baseVirtualIndex + i]; this.pushItemData(p, v); } }, scrollHandler: function(e, detail) { this._scrollTop = e.detail ? e.detail.target.scrollTop : e.target.scrollTop; this.refresh(false); }, /** * Refresh the list at the current scroll position. * * @method refresh */ refresh: function(force) { var firstVisibleIndex = Math.floor(this._scrollTop / this.height); var visibleMidpoint = firstVisibleIndex + this._visibleCount / 2; var firstReifiedIndex = Math.max(0, Math.floor(visibleMidpoint - this._physicalCount / 2)); firstReifiedIndex = Math.min(firstReifiedIndex, this.data.length - this._physicalCount); var firstPhysicalIndex = firstReifiedIndex % this._physicalCount; var baseVirtualIndex = firstReifiedIndex - firstPhysicalIndex; var baseTransformValue = Math.floor(this.height * baseVirtualIndex); var nextTransformValue = Math.floor(baseTransformValue + this._physicalHeight); var baseTransformString = 'translate3d(0,' + baseTransformValue + 'px,0)'; var nextTransformString = 'translate3d(0,' + nextTransformValue + 'px,0)'; // TODO(sorvell): experiemental for sync'ing back to virtual data. if (this.sync) { this.syncData(); } this.firstPhysicalIndex = firstPhysicalIndex; this.baseVirtualIndex = baseVirtualIndex; for (var i = 0; i < firstPhysicalIndex; ++i) { var item = this._physicalItems[i]; if (force || item._transformValue != nextTransformValue) { this.updateItem(baseVirtualIndex + this._physicalCount + i, i); setTransform(item, nextTransformString, nextTransformValue); } } for (var i = firstPhysicalIndex; i < this._physicalCount; ++i) { var item = this._physicalItems[i]; if (force || item._transformValue != baseTransformValue) { this.updateItem(baseVirtualIndex + i, i); setTransform(item, baseTransformString, baseTransformValue); } } }, // list selection tapHandler: function(e) { if (e.target === this) { return; } if (this.sync) { this.syncData(); } var n = e.target; var model = n.templateInstance && n.templateInstance.model; if (model) { var vi = model._virtualIndex, pi = model._physicalIndex; var data = this.data[vi], item = this._physicalItems[pi]; this.$.selection.select(data); this.asyncFire('core-activate', {data: data, item: item}); } }, selectedHandler: function(e, detail) { if (this.selectedProperty) { var i$ = this.indexesForData(detail.item); // TODO(sorvell): we should be relying on selection to store the // selected data but we want to optimize for lookup. this._selectedData.set(detail.item, detail.isSelected); if (i$.physical >= 0) { this.updateItem(i$.virtual, i$.physical); } } }, /** * Select the list item at the given index. * * @method selectItem * @param {number} index */ selectItem: function(index) { var data = this.data[index]; if (data) { this.$.selection.select(data); } }, /** * Set the selected state of the list item at the given index. * * @method setItemSelected * @param {number} index * @param {boolean} isSelected */ setItemSelected: function(index, isSelected) { var data = this.data[index]; if (data) { this.$.selection.setItemSelected(data, isSelected); } }, indexesForData: function(data) { var virtual = this.data.indexOf(data); var physical = this.virtualToPhysicalIndex(virtual); return { virtual: virtual, physical: physical }; }, virtualToPhysicalIndex: function(index) { for (var i=0, l=this._physicalData.length; i<l; i++) { if (this._physicalData[i]._virtualIndex === index) { return i; } } return -1; }, get selection() { return this.$.selection.getSelection(); }, selectedChanged: function() { this.$.selection.select(this.selected); }, clearSelection: function() { this._selectedData = new WeakMap(); if (this.multi) { var s$ = this.selection; for (var i=0, l=s$.length, s; (i<l) && (s=s$[i]); i++) { this.$.selection.setItemSelected(s, false); } } else { this.$.selection.setItemSelected(this.selection, false); } this.$.selection.clear(); }, scrollToItem: function(index) { this.scrollTop = index * this.height; } }); // determine proper transform mechanizm if (document.documentElement.style.transform !== undefined) { function setTransform(element, string, value) { element.style.transform = string; element._transformValue = value; } } else { function setTransform(element, string, value) { element.style.webkitTransform = string; element._transformValue = value; } } })(); ; Polymer('events-list', { /** * `spotify` is the reference to the Spotify Object * * @attribute spotify * @type JSON */ spotify: null });
{ "content_hash": "54de902019bac3520f2cd0b5d9df0d50", "timestamp": "", "source": "github", "line_count": 3701, "max_line_length": 124, "avg_line_length": 28.309646041610375, "alnum_prop": 0.5527802699142917, "repo_name": "andressanchez/hipstogram-extension", "id": "9d7dd8c985876b4124f7f3cd016c729ea14f25ea", "size": "105378", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dist/build.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "30921" }, { "name": "JavaScript", "bytes": "120410" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <GridView android:paddingLeft="10dp" android:paddingTop="15dp" android:horizontalSpacing="10dp" android:verticalSpacing="10dp" android:id="@+id/grid_winter" android:layout_width="wrap_content" android:layout_height="wrap_content" android:numColumns="2" android:gravity="center" > </GridView> </RelativeLayout>
{ "content_hash": "e4c26a1987116fcadb1850691987d7d4", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 77, "avg_line_length": 34.705882352941174, "alnum_prop": 0.6576271186440678, "repo_name": "huangjim/MyViewPager", "id": "54ad96a22ca2ca1b777398670d39201a38b569d5", "size": "590", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/activity_frag_winter.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "275526" } ], "symlink_target": "" }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="LocalizationTarget.cs" company="Fox Council"> // Fox Council // </copyright> // <summary> // Defines a path to a language file and it's short code and display name. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace MineAPI.EditorBase.Localization { using System; /// <summary> /// Defines a path to a language file and it's short code and display name. /// </summary> public class LocalizationTarget { #region Fields /// <summary> /// Display name that is used for the loaded language. /// Used to make presentation of available languages look nice to users. /// </summary> private readonly string _languageDisplayName; /// <summary> /// Full path to the *.lang file within the loaded mod project folder. /// </summary> private readonly string _languageFilePath; /// <summary> /// Short code used to identify the language and used in the filename for the full file path. /// </summary> private readonly string _languageShortcode; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="LocalizationTarget"/> class. /// </summary> /// <param name="langFilePath"> /// The language file path. /// </param> /// <param name="langShortcode"> /// The language shortcode. /// </param> /// <param name="langDisplayName"> /// Display name of the language. /// </param> public LocalizationTarget(string langFilePath, string langShortcode, string langDisplayName) { _languageFilePath = langFilePath; _languageShortcode = langShortcode; _languageDisplayName = langDisplayName; } #endregion #region Public Properties /// <summary> /// Gets the display name of the language. /// </summary> /// <value>The display name of the language.</value> /// <returns>string.</returns> public string LanguageDisplayName { get { return _languageDisplayName; } } /// <summary> /// Gets the language file path. /// </summary> /// <value>The language file path.</value> /// <returns>string.</returns> public string LanguageFilePath { get { return _languageFilePath; } } /// <summary> /// Gets the language shortcode. /// </summary> /// <value>The language shortcode.</value> /// <returns>string.</returns> public string LanguageShortcode { get { return _languageShortcode; } } #endregion #region Public Methods and Operators /// <summary> /// Forces the ToString representation of this object to use the display name so data bindings will look more /// presentable. /// </summary> /// <returns>string.</returns> /// <exception cref="System.Exception">Display name string is null this cannot be!</exception> public override string ToString() { if (string.IsNullOrEmpty(_languageDisplayName)) { throw new Exception("Display name string is null this cannot be!"); } return _languageDisplayName; } #endregion } }
{ "content_hash": "11f359d2608b87179dad394473131a83", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 121, "avg_line_length": 31.161290322580644, "alnum_prop": 0.5131987577639752, "repo_name": "Maxwolf/MC-MineAPI", "id": "19af9e1191715770db0733cf0e949f336d2646ce", "size": "3866", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "MineAPI.EditorBase/Localization/LocalizationTarget.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1555120" }, { "name": "Smalltalk", "bytes": "4425" } ], "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_03) on Tue Nov 06 09:34:23 CST 2012 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class org.eclipse.jetty.http.PathMap (Jetty :: Aggregate :: All core Jetty 8.1.8.v20121106 API)</title> <meta name="date" content="2012-11-06"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.eclipse.jetty.http.PathMap (Jetty :: Aggregate :: All core Jetty 8.1.8.v20121106 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/eclipse/jetty/http//class-usePathMap.html" target="_top">Frames</a></li> <li><a href="PathMap.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.eclipse.jetty.http.PathMap" class="title">Uses of Class<br>org.eclipse.jetty.http.PathMap</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">PathMap</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.eclipse.jetty.rewrite.handler">org.eclipse.jetty.rewrite.handler</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.eclipse.jetty.server.handler">org.eclipse.jetty.server.handler</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.eclipse.jetty.servlets">org.eclipse.jetty.servlets</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.eclipse.jetty.rewrite.handler"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">PathMap</a> in <a href="../../../../../org/eclipse/jetty/rewrite/handler/package-summary.html">org.eclipse.jetty.rewrite.handler</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/eclipse/jetty/rewrite/handler/package-summary.html">org.eclipse.jetty.rewrite.handler</a> that return <a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">PathMap</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">PathMap</a></code></td> <td class="colLast"><span class="strong">LegacyRule.</span><code><strong><a href="../../../../../org/eclipse/jetty/rewrite/handler/LegacyRule.html#getRewrite()">getRewrite</a></strong>()</code> <div class="block">Returns the map of rewriting rules.</div> </td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/eclipse/jetty/rewrite/handler/package-summary.html">org.eclipse.jetty.rewrite.handler</a> with parameters of type <a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">PathMap</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">LegacyRule.</span><code><strong><a href="../../../../../org/eclipse/jetty/rewrite/handler/LegacyRule.html#setRewrite(org.eclipse.jetty.http.PathMap)">setRewrite</a></strong>(<a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">PathMap</a>&nbsp;rewrite)</code> <div class="block">Sets the map of rewriting rules.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.eclipse.jetty.server.handler"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">PathMap</a> in <a href="../../../../../org/eclipse/jetty/server/handler/package-summary.html">org.eclipse.jetty.server.handler</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Method parameters in <a href="../../../../../org/eclipse/jetty/server/handler/package-summary.html">org.eclipse.jetty.server.handler</a> with type arguments of type <a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">PathMap</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected void</code></td> <td class="colLast"><span class="strong">IPAccessHandler.</span><code><strong><a href="../../../../../org/eclipse/jetty/server/handler/IPAccessHandler.html#add(java.lang.String, org.eclipse.jetty.util.IPAddressMap)">add</a></strong>(<a href="http://download.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;entry, <a href="../../../../../org/eclipse/jetty/util/IPAddressMap.html" title="class in org.eclipse.jetty.util">IPAddressMap</a>&lt;<a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">PathMap</a>&gt;&nbsp;patternMap)</code> <div class="block">Helper method to parse the new entry and add it to the specified address pattern map.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected void</code></td> <td class="colLast"><span class="strong">IPAccessHandler.</span><code><strong><a href="../../../../../org/eclipse/jetty/server/handler/IPAccessHandler.html#dump(java.lang.StringBuilder, org.eclipse.jetty.util.IPAddressMap)">dump</a></strong>(<a href="http://download.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html?is-external=true" title="class or interface in java.lang">StringBuilder</a>&nbsp;buf, <a href="../../../../../org/eclipse/jetty/util/IPAddressMap.html" title="class in org.eclipse.jetty.util">IPAddressMap</a>&lt;<a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">PathMap</a>&gt;&nbsp;patternMap)</code> <div class="block">Dump a pattern map into a StringBuilder buffer</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected void</code></td> <td class="colLast"><span class="strong">IPAccessHandler.</span><code><strong><a href="../../../../../org/eclipse/jetty/server/handler/IPAccessHandler.html#set(java.lang.String[], org.eclipse.jetty.util.IPAddressMap)">set</a></strong>(<a href="http://download.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[]&nbsp;entries, <a href="../../../../../org/eclipse/jetty/util/IPAddressMap.html" title="class in org.eclipse.jetty.util">IPAddressMap</a>&lt;<a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">PathMap</a>&gt;&nbsp;patternMap)</code> <div class="block">Helper method to process a list of new entries and replace the content of the specified address pattern map</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.eclipse.jetty.servlets"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">PathMap</a> in <a href="../../../../../org/eclipse/jetty/servlets/package-summary.html">org.eclipse.jetty.servlets</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../org/eclipse/jetty/servlets/package-summary.html">org.eclipse.jetty.servlets</a> with type parameters of type <a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">PathMap</a></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> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../org/eclipse/jetty/util/HostMap.html" title="class in org.eclipse.jetty.util">HostMap</a>&lt;<a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">PathMap</a>&gt;</code></td> <td class="colLast"><span class="strong">ProxyServlet.</span><code><strong><a href="../../../../../org/eclipse/jetty/servlets/ProxyServlet.html#_black">_black</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected <a href="../../../../../org/eclipse/jetty/util/HostMap.html" title="class in org.eclipse.jetty.util">HostMap</a>&lt;<a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">PathMap</a>&gt;</code></td> <td class="colLast"><span class="strong">ProxyServlet.</span><code><strong><a href="../../../../../org/eclipse/jetty/servlets/ProxyServlet.html#_white">_white</a></strong></code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/eclipse/jetty/http/PathMap.html" title="class in org.eclipse.jetty.http">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/eclipse/jetty/http//class-usePathMap.html" target="_top">Frames</a></li> <li><a href="PathMap.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 1995-2012 <a href="http://www.mortbay.com">Mort Bay Consulting</a>. All Rights Reserved.</small></p> </body> </html>
{ "content_hash": "e2e418bb395c9a45b0faec0c6d94d913", "timestamp": "", "source": "github", "line_count": 241, "max_line_length": 410, "avg_line_length": 55.045643153526974, "alnum_prop": 0.6616915422885572, "repo_name": "yayaratta/TP6_MVC", "id": "18ecb69489dbf3966073d267996c00cc3dbd659d", "size": "13266", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "javadoc/org/eclipse/jetty/http/class-use/PathMap.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1706" }, { "name": "HTML", "bytes": "25501" }, { "name": "Java", "bytes": "55668" }, { "name": "JavaScript", "bytes": "28308" }, { "name": "Shell", "bytes": "33033" } ], "symlink_target": "" }
AWS Chrome cross account plugin ===============================
{ "content_hash": "932e694ef4e292890de32b6f53d2c53d", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 31, "avg_line_length": 31.5, "alnum_prop": 0.42857142857142855, "repo_name": "XT-i/chrome-aws-cross-account", "id": "ce7f7b0631d118c6332b764dde32ffe1b140b87f", "size": "63", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "271" }, { "name": "HTML", "bytes": "2125" }, { "name": "JavaScript", "bytes": "4439" } ], "symlink_target": "" }
package net.buycraft.plugin.execution; import com.google.common.collect.Sets; import lombok.RequiredArgsConstructor; import net.buycraft.plugin.IBuycraftPlatform; import net.buycraft.plugin.client.ApiException; import net.buycraft.plugin.data.QueuedCommand; import net.buycraft.plugin.data.responses.QueueInformation; import net.buycraft.plugin.execution.strategy.ToRunQueuedCommand; import java.io.IOException; import java.util.*; import java.util.logging.Level; @RequiredArgsConstructor public class ImmediateExecutionRunner implements Runnable { private final IBuycraftPlatform platform; private final Set<Integer> executingLater = Sets.newConcurrentHashSet(); private final Random random = new Random(); @Override public void run() { if (platform.getApiClient() == null) { return; // no API client } QueueInformation information; do { try { information = platform.getApiClient().retrieveOfflineQueue(); } catch (IOException | ApiException e) { platform.log(Level.SEVERE, "Could not fetch command queue", e); return; } // Filter out commands we're going to execute at a later time. for (Iterator<QueuedCommand> it = information.getCommands().iterator(); it.hasNext(); ) { QueuedCommand command = it.next(); if (executingLater.contains(command.getId())) it.remove(); } // Nothing to do? Then let's exit. if (information.getCommands().isEmpty()) { return; } // Queue commands for later. for (QueuedCommand command : information.getCommands()) { platform.getExecutor().queue(new ToRunQueuedCommand(command.getPlayer(), command, false)); } // Sleep for between 0.5-1.5 seconds to help spread load. try { Thread.sleep(500 + random.nextInt(1000)); } catch (InterruptedException e) { // Shouldn't happen, but in that case just bail out. return; } } while (information.getMeta().isLimited()); } }
{ "content_hash": "696410369487ec64dbc7d4bb8d7f3278", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 106, "avg_line_length": 35.714285714285715, "alnum_prop": 0.6173333333333333, "repo_name": "20zinnm/BuycraftX", "id": "ef2028125d2f9f3778c45a5062acbf171d906284", "size": "2250", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/src/main/java/net/buycraft/plugin/execution/ImmediateExecutionRunner.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "217311" } ], "symlink_target": "" }
<?php namespace App\Services; use Firebase\JWT\JWT; use App\Domain\Users\UserEntity; use App\Domain\Users\UserRepository; class Auth { /** * Generate a random token * * @return string */ public function generateToken() { return bin2hex(openssl_random_pseudo_bytes(16)); } /** * Generate a JWT * * @param JWT $jwt * @param array $data * * @return array */ public function generateJWT(JWT $jwt, $data) { $token = [ 'jti' => base64_encode(mcrypt_create_iv(32)), 'iss' => $_SERVER['APP_PROTOCOL'] . $_SERVER['APP_DOMAIN'], 'aud' => 'http://' . $_SERVER['CLIENT_URL'], 'iat' => time(), 'nbf' => time(), 'exp' => time() + 604800, // one week 'data' => $data ]; $jwt = $jwt->encode($token, $_SERVER['APP_SECRET'], 'HS512'); return ['token' => $jwt]; } /** * Get the decoded JWT * * @param JWT $jwt * @param string $token * * @return array|bool */ public function decodeJWT(JWT $jwt, $token) { try { $token = JWT::decode($token, $_SERVER['APP_SECRET'], ['HS512']); return $token; } catch(\Exception $e){ // log exception return false; } } /** * Hash user password * * @param string $password * * @return string|bool */ public function hashPassword($password) { return password_hash($password, PASSWORD_DEFAULT/*, $_SERVER['APP_PASS_ALGO_CONST']*/); } /** * Validate user password * * @param UserEntity $user * @param UserRepository $userRepository * @param string $password * * @return bool */ public function validatePassword(UserEntity $user, UserRepository $userRepository, $password) { if (password_verify($password, $user->getPassword())) { // Check if a newer hashing algorithm is available or the cost has changed if (password_needs_rehash($user->getPassword(), PASSWORD_DEFAULT)) { $newHash = password_hash($password, PASSWORD_DEFAULT); $user->setPassword($newHash); $userRepository->updateUserPassword($user); echo 'yup'; } return true; } return false; } /** * Validate amount of time since request issued * * @param string $created * * @return bool */ public function validatePasswordResetExpiry($created) { $created = strtotime($created); $now = strtotime(date('Y-m-d H:i:s')); $diff = round(($now - $created) / 60, 2); if (intval($diff) < 60) { return true; } return false; } }
{ "content_hash": "2efc75926e2053c9de76483f635ae518", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 97, "avg_line_length": 25.120689655172413, "alnum_prop": 0.5075497597803706, "repo_name": "dupkey/slim3-api", "id": "82a77474637b3c20387610bcca0d62876b32012b", "size": "2914", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/Services/Auth.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "772" }, { "name": "PHP", "bytes": "82090" }, { "name": "Shell", "bytes": "2841" } ], "symlink_target": "" }
#include "modules/audio_processing/aec3/render_delay_buffer.h" #include <string.h> #include <algorithm> #include <cmath> #include <memory> #include <numeric> #include <vector> #include "absl/types/optional.h" #include "api/array_view.h" #include "api/audio/echo_canceller3_config.h" #include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/aec3_fft.h" #include "modules/audio_processing/aec3/alignment_mixer.h" #include "modules/audio_processing/aec3/block_buffer.h" #include "modules/audio_processing/aec3/decimator.h" #include "modules/audio_processing/aec3/downsampled_render_buffer.h" #include "modules/audio_processing/aec3/fft_buffer.h" #include "modules/audio_processing/aec3/fft_data.h" #include "modules/audio_processing/aec3/render_buffer.h" #include "modules/audio_processing/aec3/spectrum_buffer.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" namespace webrtc { namespace { class RenderDelayBufferImpl final : public RenderDelayBuffer { public: RenderDelayBufferImpl(const EchoCanceller3Config& config, int sample_rate_hz, size_t num_render_channels); RenderDelayBufferImpl() = delete; ~RenderDelayBufferImpl() override; void Reset() override; BufferingEvent Insert( const std::vector<std::vector<std::vector<float>>>& block) override; BufferingEvent PrepareCaptureProcessing() override; bool AlignFromDelay(size_t delay) override; void AlignFromExternalDelay() override; size_t Delay() const override { return ComputeDelay(); } size_t MaxDelay() const override { return blocks_.buffer.size() - 1 - buffer_headroom_; } RenderBuffer* GetRenderBuffer() override { return &echo_remover_buffer_; } const DownsampledRenderBuffer& GetDownsampledRenderBuffer() const override { return low_rate_; } int BufferLatency() const; void SetAudioBufferDelay(int delay_ms) override; bool HasReceivedBufferDelay() override; private: static int instance_count_; std::unique_ptr<ApmDataDumper> data_dumper_; const Aec3Optimization optimization_; const EchoCanceller3Config config_; const float render_linear_amplitude_gain_; const rtc::LoggingSeverity delay_log_level_; size_t down_sampling_factor_; const int sub_block_size_; BlockBuffer blocks_; SpectrumBuffer spectra_; FftBuffer ffts_; absl::optional<size_t> delay_; RenderBuffer echo_remover_buffer_; DownsampledRenderBuffer low_rate_; AlignmentMixer render_mixer_; Decimator render_decimator_; const Aec3Fft fft_; std::vector<float> render_ds_; const int buffer_headroom_; bool last_call_was_render_ = false; int num_api_calls_in_a_row_ = 0; int max_observed_jitter_ = 1; int64_t capture_call_counter_ = 0; int64_t render_call_counter_ = 0; bool render_activity_ = false; size_t render_activity_counter_ = 0; absl::optional<int> external_audio_buffer_delay_; bool external_audio_buffer_delay_verified_after_reset_ = false; size_t min_latency_blocks_ = 0; size_t excess_render_detection_counter_ = 0; int MapDelayToTotalDelay(size_t delay) const; int ComputeDelay() const; void ApplyTotalDelay(int delay); void InsertBlock(const std::vector<std::vector<std::vector<float>>>& block, int previous_write); bool DetectActiveRender(rtc::ArrayView<const float> x) const; bool DetectExcessRenderBlocks(); void IncrementWriteIndices(); void IncrementLowRateReadIndices(); void IncrementReadIndices(); bool RenderOverrun(); bool RenderUnderrun(); }; int RenderDelayBufferImpl::instance_count_ = 0; RenderDelayBufferImpl::RenderDelayBufferImpl(const EchoCanceller3Config& config, int sample_rate_hz, size_t num_render_channels) : data_dumper_( new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))), optimization_(DetectOptimization()), config_(config), render_linear_amplitude_gain_( std::pow(10.0f, config_.render_levels.render_power_gain_db / 20.f)), delay_log_level_(config_.delay.log_warning_on_delay_changes ? rtc::LS_WARNING : rtc::LS_VERBOSE), down_sampling_factor_(config.delay.down_sampling_factor), sub_block_size_(static_cast<int>(down_sampling_factor_ > 0 ? kBlockSize / down_sampling_factor_ : kBlockSize)), blocks_(GetRenderDelayBufferSize(down_sampling_factor_, config.delay.num_filters, config.filter.refined.length_blocks), NumBandsForRate(sample_rate_hz), num_render_channels, kBlockSize), spectra_(blocks_.buffer.size(), num_render_channels), ffts_(blocks_.buffer.size(), num_render_channels), delay_(config_.delay.default_delay), echo_remover_buffer_(&blocks_, &spectra_, &ffts_), low_rate_(GetDownSampledBufferSize(down_sampling_factor_, config.delay.num_filters)), render_mixer_(num_render_channels, config.delay.render_alignment_mixing), render_decimator_(down_sampling_factor_), fft_(), render_ds_(sub_block_size_, 0.f), buffer_headroom_(config.filter.refined.length_blocks) { RTC_DCHECK_EQ(blocks_.buffer.size(), ffts_.buffer.size()); RTC_DCHECK_EQ(spectra_.buffer.size(), ffts_.buffer.size()); for (size_t i = 0; i < blocks_.buffer.size(); ++i) { RTC_DCHECK_EQ(blocks_.buffer[i][0].size(), ffts_.buffer[i].size()); RTC_DCHECK_EQ(spectra_.buffer[i].size(), ffts_.buffer[i].size()); } Reset(); } RenderDelayBufferImpl::~RenderDelayBufferImpl() = default; // Resets the buffer delays and clears the reported delays. void RenderDelayBufferImpl::Reset() { last_call_was_render_ = false; num_api_calls_in_a_row_ = 1; min_latency_blocks_ = 0; excess_render_detection_counter_ = 0; // Initialize the read index to one sub-block before the write index. low_rate_.read = low_rate_.OffsetIndex(low_rate_.write, sub_block_size_); // Check for any external audio buffer delay and whether it is feasible. if (external_audio_buffer_delay_) { const int headroom = 2; size_t audio_buffer_delay_to_set; // Minimum delay is 1 (like the low-rate render buffer). if (*external_audio_buffer_delay_ <= headroom) { audio_buffer_delay_to_set = 1; } else { audio_buffer_delay_to_set = *external_audio_buffer_delay_ - headroom; } audio_buffer_delay_to_set = std::min(audio_buffer_delay_to_set, MaxDelay()); // When an external delay estimate is available, use that delay as the // initial render buffer delay. ApplyTotalDelay(audio_buffer_delay_to_set); delay_ = ComputeDelay(); external_audio_buffer_delay_verified_after_reset_ = false; } else { // If an external delay estimate is not available, use that delay as the // initial delay. Set the render buffer delays to the default delay. ApplyTotalDelay(config_.delay.default_delay); // Unset the delays which are set by AlignFromDelay. delay_ = absl::nullopt; } } // Inserts a new block into the render buffers. RenderDelayBuffer::BufferingEvent RenderDelayBufferImpl::Insert( const std::vector<std::vector<std::vector<float>>>& block) { ++render_call_counter_; if (delay_) { if (!last_call_was_render_) { last_call_was_render_ = true; num_api_calls_in_a_row_ = 1; } else { if (++num_api_calls_in_a_row_ > max_observed_jitter_) { max_observed_jitter_ = num_api_calls_in_a_row_; RTC_LOG_V(delay_log_level_) << "New max number api jitter observed at render block " << render_call_counter_ << ": " << num_api_calls_in_a_row_ << " blocks"; } } } // Increase the write indices to where the new blocks should be written. const int previous_write = blocks_.write; IncrementWriteIndices(); // Allow overrun and do a reset when render overrun occurrs due to more render // data being inserted than capture data is received. BufferingEvent event = RenderOverrun() ? BufferingEvent::kRenderOverrun : BufferingEvent::kNone; // Detect and update render activity. if (!render_activity_) { render_activity_counter_ += DetectActiveRender(block[0][0]) ? 1 : 0; render_activity_ = render_activity_counter_ >= 20; } // Insert the new render block into the specified position. InsertBlock(block, previous_write); if (event != BufferingEvent::kNone) { Reset(); } return event; } // Prepares the render buffers for processing another capture block. RenderDelayBuffer::BufferingEvent RenderDelayBufferImpl::PrepareCaptureProcessing() { RenderDelayBuffer::BufferingEvent event = BufferingEvent::kNone; ++capture_call_counter_; if (delay_) { if (last_call_was_render_) { last_call_was_render_ = false; num_api_calls_in_a_row_ = 1; } else { if (++num_api_calls_in_a_row_ > max_observed_jitter_) { max_observed_jitter_ = num_api_calls_in_a_row_; RTC_LOG_V(delay_log_level_) << "New max number api jitter observed at capture block " << capture_call_counter_ << ": " << num_api_calls_in_a_row_ << " blocks"; } } } if (DetectExcessRenderBlocks()) { // Too many render blocks compared to capture blocks. Risk of delay ending // up before the filter used by the delay estimator. RTC_LOG_V(delay_log_level_) << "Excess render blocks detected at block " << capture_call_counter_; Reset(); event = BufferingEvent::kRenderOverrun; } else if (RenderUnderrun()) { // Don't increment the read indices of the low rate buffer if there is a // render underrun. RTC_LOG_V(delay_log_level_) << "Render buffer underrun detected at block " << capture_call_counter_; IncrementReadIndices(); // Incrementing the buffer index without increasing the low rate buffer // index means that the delay is reduced by one. if (delay_ && *delay_ > 0) delay_ = *delay_ - 1; event = BufferingEvent::kRenderUnderrun; } else { // Increment the read indices in the render buffers to point to the most // recent block to use in the capture processing. IncrementLowRateReadIndices(); IncrementReadIndices(); } echo_remover_buffer_.SetRenderActivity(render_activity_); if (render_activity_) { render_activity_counter_ = 0; render_activity_ = false; } return event; } // Sets the delay and returns a bool indicating whether the delay was changed. bool RenderDelayBufferImpl::AlignFromDelay(size_t delay) { RTC_DCHECK(!config_.delay.use_external_delay_estimator); if (!external_audio_buffer_delay_verified_after_reset_ && external_audio_buffer_delay_ && delay_) { int difference = static_cast<int>(delay) - static_cast<int>(*delay_); RTC_LOG_V(delay_log_level_) << "Mismatch between first estimated delay after reset " "and externally reported audio buffer delay: " << difference << " blocks"; external_audio_buffer_delay_verified_after_reset_ = true; } if (delay_ && *delay_ == delay) { return false; } delay_ = delay; // Compute the total delay and limit the delay to the allowed range. int total_delay = MapDelayToTotalDelay(*delay_); total_delay = std::min(MaxDelay(), static_cast<size_t>(std::max(total_delay, 0))); // Apply the delay to the buffers. ApplyTotalDelay(total_delay); return true; } void RenderDelayBufferImpl::SetAudioBufferDelay(int delay_ms) { if (!external_audio_buffer_delay_) { RTC_LOG_V(delay_log_level_) << "Receiving a first externally reported audio buffer delay of " << delay_ms << " ms."; } // Convert delay from milliseconds to blocks (rounded down). external_audio_buffer_delay_ = delay_ms / 4; } bool RenderDelayBufferImpl::HasReceivedBufferDelay() { return external_audio_buffer_delay_.has_value(); } // Maps the externally computed delay to the delay used internally. int RenderDelayBufferImpl::MapDelayToTotalDelay( size_t external_delay_blocks) const { const int latency_blocks = BufferLatency(); return latency_blocks + static_cast<int>(external_delay_blocks); } // Returns the delay (not including call jitter). int RenderDelayBufferImpl::ComputeDelay() const { const int latency_blocks = BufferLatency(); int internal_delay = spectra_.read >= spectra_.write ? spectra_.read - spectra_.write : spectra_.size + spectra_.read - spectra_.write; return internal_delay - latency_blocks; } // Set the read indices according to the delay. void RenderDelayBufferImpl::ApplyTotalDelay(int delay) { RTC_LOG_V(delay_log_level_) << "Applying total delay of " << delay << " blocks."; blocks_.read = blocks_.OffsetIndex(blocks_.write, -delay); spectra_.read = spectra_.OffsetIndex(spectra_.write, delay); ffts_.read = ffts_.OffsetIndex(ffts_.write, delay); } void RenderDelayBufferImpl::AlignFromExternalDelay() { RTC_DCHECK(config_.delay.use_external_delay_estimator); if (external_audio_buffer_delay_) { int64_t delay = render_call_counter_ - capture_call_counter_ + *external_audio_buffer_delay_; ApplyTotalDelay(delay); } } // Inserts a block into the render buffers. void RenderDelayBufferImpl::InsertBlock( const std::vector<std::vector<std::vector<float>>>& block, int previous_write) { auto& b = blocks_; auto& lr = low_rate_; auto& ds = render_ds_; auto& f = ffts_; auto& s = spectra_; const size_t num_bands = b.buffer[b.write].size(); const size_t num_render_channels = b.buffer[b.write][0].size(); RTC_DCHECK_EQ(block.size(), b.buffer[b.write].size()); for (size_t band = 0; band < num_bands; ++band) { RTC_DCHECK_EQ(block[band].size(), num_render_channels); RTC_DCHECK_EQ(b.buffer[b.write][band].size(), num_render_channels); for (size_t ch = 0; ch < num_render_channels; ++ch) { RTC_DCHECK_EQ(block[band][ch].size(), b.buffer[b.write][band][ch].size()); std::copy(block[band][ch].begin(), block[band][ch].end(), b.buffer[b.write][band][ch].begin()); } } if (render_linear_amplitude_gain_ != 1.f) { for (size_t band = 0; band < num_bands; ++band) { for (size_t ch = 0; ch < num_render_channels; ++ch) { for (size_t k = 0; k < 64; ++k) { b.buffer[b.write][band][ch][k] *= render_linear_amplitude_gain_; } } } } std::array<float, kBlockSize> downmixed_render; render_mixer_.ProduceOutput(b.buffer[b.write][0], downmixed_render); render_decimator_.Decimate(downmixed_render, ds); data_dumper_->DumpWav("aec3_render_decimator_output", ds.size(), ds.data(), 16000 / down_sampling_factor_, 1); std::copy(ds.rbegin(), ds.rend(), lr.buffer.begin() + lr.write); for (size_t channel = 0; channel < b.buffer[b.write][0].size(); ++channel) { fft_.PaddedFft(b.buffer[b.write][0][channel], b.buffer[previous_write][0][channel], &f.buffer[f.write][channel]); f.buffer[f.write][channel].Spectrum(optimization_, s.buffer[s.write][channel]); } } bool RenderDelayBufferImpl::DetectActiveRender( rtc::ArrayView<const float> x) const { const float x_energy = std::inner_product(x.begin(), x.end(), x.begin(), 0.f); return x_energy > (config_.render_levels.active_render_limit * config_.render_levels.active_render_limit) * kFftLengthBy2; } bool RenderDelayBufferImpl::DetectExcessRenderBlocks() { bool excess_render_detected = false; const size_t latency_blocks = static_cast<size_t>(BufferLatency()); // The recently seen minimum latency in blocks. Should be close to 0. min_latency_blocks_ = std::min(min_latency_blocks_, latency_blocks); // After processing a configurable number of blocks the minimum latency is // checked. if (++excess_render_detection_counter_ >= config_.buffering.excess_render_detection_interval_blocks) { // If the minimum latency is not lower than the threshold there have been // more render than capture frames. excess_render_detected = min_latency_blocks_ > config_.buffering.max_allowed_excess_render_blocks; // Reset the counter and let the minimum latency be the current latency. min_latency_blocks_ = latency_blocks; excess_render_detection_counter_ = 0; } data_dumper_->DumpRaw("aec3_latency_blocks", latency_blocks); data_dumper_->DumpRaw("aec3_min_latency_blocks", min_latency_blocks_); data_dumper_->DumpRaw("aec3_excess_render_detected", excess_render_detected); return excess_render_detected; } // Computes the latency in the buffer (the number of unread sub-blocks). int RenderDelayBufferImpl::BufferLatency() const { const DownsampledRenderBuffer& l = low_rate_; int latency_samples = (l.buffer.size() + l.read - l.write) % l.buffer.size(); int latency_blocks = latency_samples / sub_block_size_; return latency_blocks; } // Increments the write indices for the render buffers. void RenderDelayBufferImpl::IncrementWriteIndices() { low_rate_.UpdateWriteIndex(-sub_block_size_); blocks_.IncWriteIndex(); spectra_.DecWriteIndex(); ffts_.DecWriteIndex(); } // Increments the read indices of the low rate render buffers. void RenderDelayBufferImpl::IncrementLowRateReadIndices() { low_rate_.UpdateReadIndex(-sub_block_size_); } // Increments the read indices for the render buffers. void RenderDelayBufferImpl::IncrementReadIndices() { if (blocks_.read != blocks_.write) { blocks_.IncReadIndex(); spectra_.DecReadIndex(); ffts_.DecReadIndex(); } } // Checks for a render buffer overrun. bool RenderDelayBufferImpl::RenderOverrun() { return low_rate_.read == low_rate_.write || blocks_.read == blocks_.write; } // Checks for a render buffer underrun. bool RenderDelayBufferImpl::RenderUnderrun() { return low_rate_.read == low_rate_.write; } } // namespace RenderDelayBuffer* RenderDelayBuffer::Create(const EchoCanceller3Config& config, int sample_rate_hz, size_t num_render_channels) { return new RenderDelayBufferImpl(config, sample_rate_hz, num_render_channels); } } // namespace webrtc
{ "content_hash": "2ec95a353ff74615e23ad5b96755d5a3", "timestamp": "", "source": "github", "line_count": 497, "max_line_length": 80, "avg_line_length": 37.65191146881288, "alnum_prop": 0.6678245070272003, "repo_name": "endlessm/chromium-browser", "id": "10e81d8ec939555310cf3b21959336c81f25ebe9", "size": "19125", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "third_party/webrtc/modules/audio_processing/aec3/render_delay_buffer.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
\documentclass[parskip=half, bibliography=totoc, captions=tableheading, titlepage=firstiscover]{scrartcl} %Ich habe [parskip=half] hinzugefügt %\usepackage[calc]{picture} \usepackage{fixltx2e} \usepackage{tcolorbox} %\pagestyle{headings} \usepackage{scrpage2} \pagestyle{scrheadings} \ifoot[\pagemark]{\pagemark} \ofoot[]{} \cfoot[]{} \usepackage{polyglossia} \setmainlanguage{german} \usepackage{caption} \usepackage{amsmath} \usepackage{amssymb} \usepackage{mathtools} \usepackage{fontspec} \defaultfontfeatures{Ligatures=TeX} \usepackage[ math-style=ISO, bold-style=ISO, sans-style=italic, nabla=upright, ]{unicode-math} \setmathfont{Latin Modern Math} %\setmathfont[range={\mathscr, \mathbfscr}]{XITS Math} %\setmathfont[range=\coloneq]{XITS Math} %\setmathfont[range=\propto]{XITS Math} \usepackage[autostyle]{csquotes} \usepackage[ locale=DE, % deutsche Einstellungen separate-uncertainty=true, % Immer Fehler mit \pm per-mode=symbol-or-fraction, % m/s im Text, sonst Brüche ]{siunitx} %\sisetup{math-stylemicro=\text{µ},text-micro=µ} \usepackage{xfrac} \usepackage[section, below]{placeins} \usepackage[ labelfont=bf, font=small, width=0.9\textwidth, ]{caption} \usepackage{subcaption} \usepackage{graphicx} \usepackage{float} \floatplacement{figure}{h} \floatplacement{table}{h} \usepackage{booktabs} \usepackage{bookmark} \usepackage[shortcuts]{extdash} \usepackage[math]{blindtext} \usepackage{microtype} \usepackage[ backend=biber, ]{biblatex} % Quellendatenbank \addbibresource{lit.bib} \usepackage{hyperref} \usepackage{color} % Das ist Geschmacksfrage \usepackage{makeidx} %Ich habe makeidx hinzugefügt + makeindex \makeindex \usepackage[version=3]{mhchem} % für Thermodynamik-chemische Elemente \usepackage{enumitem} %Ich habe enumitem hinzugefügt \usepackage{expl3} \usepackage{xparse} %\ExplSyntaxOn \NewDocumentCommand \dif {m} { \mathinner{\symup{d} #1} } \newcommand{\map}[1]{\mathup{#1}} \usepackage{subcaption} %\usepackage{showframe} \input{data.tex} \author{Steven Becker \\ steven.becker@tu-dortmund.de \\ und \\ Stefan Grisard \\ stefan.grisard@tu-dortmund.de} \title{\versuch} \subtitle{Versuch \vnr} \date{\vd \\ \va}
{ "content_hash": "6ea8b05081ec6e0c462da08971b72323", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 142, "avg_line_length": 19.31304347826087, "alnum_prop": 0.7492120666366502, "repo_name": "stefangri/s_s_productions", "id": "dde4123cb409de441f9d7f0df351faa53233b683", "size": "2228", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PHY341/V207_Viskosimeter/Protokoll/header.tex", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "16616" }, { "name": "Python", "bytes": "525079" }, { "name": "Shell", "bytes": "681" }, { "name": "TeX", "bytes": "986974" } ], "symlink_target": "" }
<!doctype html> <html ⚡> <head> <meta charset="utf-8"> <title>AMP Analytics</title> <link rel="canonical" href="analytics.amp.html" > <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"> <style amp-custom> .box { background: #ccc; border: 1px solid #aaa; padding: 10px; margin: 10px; } #container { position: absolute; top: 10000px; height: 10px; } </style> <script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script> <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript> <script async src="https://cdn.ampproject.org/v0.js"></script> </head> <body> <div id="container"> Container for analytics tags. Positioned far away from top to make sure that doesn't matter. <amp-analytics id="analytics1"> <script type="application/json"> { "transport": {"beacon": false, "xhrpost": false}, "requests": { "base": "https://example.com/?domain=${canonicalHost}&path=${canonicalPath}&title=${title}&time=${timestamp}&tz=${timezone}&pid=${pageViewId}&_=${random}", "pageview": "${base}&name=${eventName}&type=${eventId}&screenSize=${screenWidth}x${screenHeight}", "event": "${base}&name=${eventName}&scrollY=${scrollTop}&scrollX=${scrollLeft}&height=${availableScreenHeight}&width=${availableScreenWidth}" }, "vars": { "title": "Example Request" }, "triggers": { "defaultPageview": { "on": "visible", "request": "pageview", "vars": { "eventName": "page-loaded", "eventId": "42" } }, "scrollPings": { "on": "scroll", "request": "event", "scrollSpec": { "verticalBoundaries" : [1, 50, 90], "horizontalBoundaries": [100] }, "vars": { "eventName": "scroll" } } } } </script> </amp-analytics> <!-- AT Internet tracking --> <amp-analytics type="atinternet"> <script type="application/json"> { "vars": { "site": "123456", // Site number "log": "logs", // Secured collect log "domain": ".xiti.com", // Collect domain name "title": "pageChapter::pageTitle", // Page label "level2": "10" // Page level 2 }, "triggers": { "defaultPageview": { "on": "visible", "request": "pageview" }, "links": { "on": "click", "selector": "#test1", "request": "click", "vars": { "label": "clickChapter::clickLabel", // Click label "level2Click": "12", // Click level 2 "type": "a" // Click type (a = action, t = download, n = navigation, s exit) } } } } </script> </amp-analytics> <!-- End AT Internet tracking --> <!-- Chartbeat tracking --> <amp-analytics type="chartbeat"> <script type="application/json"> { "vars": { "uid": "12345", "domain": "my-site.com", "sections": "section 1, section 2" } } </script> </amp-analytics> <!-- End Chartbeat example --> <!-- comScore UDM pageview tracking --> <amp-analytics type="comscore"> <script type="application/json"> { "vars": { "c2": "1000001" } } </script> </amp-analytics> <!-- End comScore example --> <amp-analytics type="googleanalytics" id="analytics2"> <script type="application/json"> { "vars": { "account": "UA-YYYY-Y" }, "triggers": { "defaultPageview": { "on": "visible", "request": "pageview", "vars": { "title": "Example Pageview" } }, "clickOnTest1Trigger": { "on": "click", "selector": "#test1", "request": "event", "vars": { "eventCategory": "examples", "eventAction": "clicked-test1" } }, "clickOnTopTrigger": { "on": "click", "selector": "#top", "request": "event", "vars": { "eventCategory": "examples", "eventAction": "clicked-header" } } } } </script> </amp-analytics> <!-- Krux tracking. Ensure you replace KMnP7vhh with your configuration ID. --> <amp-analytics type="krux" config="https://cdn.krxd.net/controltag/amp/KMnP7vhh.json"> <script type="application/json"> { "vars": { "section": "amp", "subsection": "examples" }, "extraUrlParams": { "user.status": "developer", "page.keywords": "amp, mobile, examples" } } </script> </amp-analytics> <!-- Parsely tracking --> <amp-analytics type="parsely"> <script type="application/json"> { "vars": { "apikey": "example.com" } } </script> </amp-analytics> <!-- Quantcast tracking --> <amp-analytics type="quantcast"> <script type="application/json"> { "vars": { "pcode": "p-1234567890abc", "labels": ["Example.label.1", "Example.label.2"] } } </script> </amp-analytics> <!-- End Quantcast example --> <amp-analytics id="analytics3" config="./analytics.config.json"></amp-analytics> <amp-analytics id="analytics4"> <script type="application/json"> { "requests": { "test-ping": "https://my-analytics.com/ping?title=${title}&acct=${account}" }, "vars": { "title": "A page that sends a ping", "account": "12345" }, "triggers": { "timer": { "on": "timer", "timerSpec": { "interval": 5, "max-timer-length": 300 }, "request": "test-ping" } } } </script> </amp-analytics> <!-- comScore UDM pageview tracking --> <amp-analytics type="comscore"> <script type="application/json"> { "vars": { "c2": "1000001" } } </script> </amp-analytics> <!-- End comScore example --> <!-- INFOnline example Important: url needs to point to a copy of amp-analytics-infonline.html on a different subdomain than your AMP files. --> <amp-analytics type="infonline" id="infonline"> <script type="application/json"> { "vars": { "st": "angebotskennung", "co": "comment", "cp": "code" }, "requests": { "url": "https://3p.ampproject.net/custom/amp-analytics-infonline.html" } } </script> </amp-analytics> <!-- End INFOnline example --> </div> <div class="logo"></div> <h1 id="top">AMP Analytics</h1> <span id="test1" class="box"> Click here to generate an event </span> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pellentesque augue quis elementum tempus. Pellentesque sit amet neque bibendum, sagittis purus vitae, pellentesque magna. Vestibulum non viverra metus, eget feugiat lacus. Nulla in maximus orci. Maecenas id turpis vel ipsum vestibulum bibendum ut sit amet magna. Nullam hendrerit ex at est eleifend, nec dignissim nibh rutrum. Aliquam quis tellus et nibh faucibus laoreet in eget turpis. Nam quam nisl, porttitor vel ex eget, dapibus placerat dui. Mauris commodo pellentesque leo, eu tempus quam. In hac habitasse platea dictumst. Suspendisse non ante finibus, luctus augue non, luctus orci. Vestibulum ornare lacinia aliquam. In sollicitudin vehicula vulputate. Sed mi elit, commodo nec sapien nec, pretium bibendum leo. Donec id justo tortor. Ut in mauris dapibus, laoreet metus vitae, dictum nisi. </p> <p> Integer dapibus egestas arcu. Nunc vitae velit congue, placerat augue quis, suscipit nisi. Donec suscipit imperdiet turpis pharetra feugiat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Phasellus aliquam eleifend dolor, at lacinia orci semper vel. Nunc semper sem vel tincidunt posuere. Nunc lobortis velit vitae condimentum mollis. Morbi eu ullamcorper mauris. Pellentesque ac eros maximus, pulvinar sapien vitae, semper nisi. Curabitur imperdiet non mauris vitae sollicitudin. </p> <p> Nam posuere velit euismod risus pulvinar, in sollicitudin sapien consectetur. Vestibulum nec ex odio. Quisque at elit nec nunc ultricies lacinia nec non lorem. Maecenas porttitor consequat mauris, vitae porttitor ligula pellentesque ut. Pellentesque rhoncus diam vel lacus lobortis imperdiet. Sed maximus dictum hendrerit. Vivamus ornare, purus in laoreet sagittis, est ante pretium mauris, vel vulputate arcu erat eget mauris. Suspendisse eu lorem metus. Aliquam tempus aliquet urna, vitae mollis lacus pretium vitae. Etiam semper gravida commodo. Maecenas at pulvinar quam. Nullam dolor ipsum, ornare a sollicitudin et, sodales porttitor neque. </p> <p> Integer in felis at lacus mattis facilisis. Curabitur tincidunt, felis porttitor mollis finibus, tortor elit elementum dolor, vel vulputate lorem dui id ante. Vivamus in velit at lectus blandit gravida vitae quis arcu. Nam et magna magna. Fusce condimentum diam lacus, ac ullamcorper purus malesuada eu. Mauris ullamcorper elit et venenatis faucibus. Nullam lobortis molestie purus quis pellentesque. Sed at libero id nisi rhoncus tincidunt. Praesent vestibulum vehicula tristique. Etiam rutrum, nunc id porta interdum, nulla nisi molestie leo, at fermentum justo dolor at lorem. Duis in egestas sapien. </p> <p> Donec pharetra molestie sollicitudin. Duis mattis eleifend rutrum. Quisque luctus tincidunt lacus, vitae lobortis nisi malesuada ac. Aliquam mattis leo vel elit rutrum, nec consequat massa vestibulum. Maecenas bibendum metus nec ante feugiat, eu faucibus orci mattis. Cras tristique sem non elit congue malesuada. Proin ornare, lacus et porttitor consequat, sapien urna rutrum diam, ac pellentesque ligula est eget nisi. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec ultrices sollicitudin eros a placerat. Proin eget pulvinar est. Donec posuere ultrices odio at ultrices. Suspendisse potenti. Phasellus id orci id purus porttitor consectetur a at erat. Nullam volutpat ultricies nisl id maximus. Morbi porta ex ante, et egestas odio ultricies consequat. </p> <p> </p><ul> <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li> <li>Aliquam in ex porta, imperdiet elit sit amet, condimentum diam.</li> <li>Etiam fermentum nisi at porta pulvinar.</li> </ul> <p></p> <p> </p><ul> <li>Proin mattis neque vel elit posuere molestie.</li> <li>Integer tincidunt sem sed nunc auctor elementum.</li> <li>Integer a felis in ipsum aliquet auctor sit amet a neque.</li> </ul> <p></p> <p> </p><ul> <li>Sed suscipit dolor molestie, rhoncus quam ac, lacinia ex.</li> <li>Curabitur et tellus vel justo ultrices aliquet sed id turpis.</li> <li>Nam finibus risus at justo elementum bibendum.</li> <li>In non lacus non urna congue feugiat at vel diam.</li> </ul> <p></p> <p> </p><ul> <li>Integer hendrerit augue interdum dui venenatis, sit amet tristique mauris cursus.</li> <li>Etiam quis eros viverra, tincidunt justo in, facilisis nunc.</li> <li>Aliquam at lacus faucibus, congue lorem interdum, semper mauris.</li> <li>Ut vulputate erat vel feugiat pharetra.</li> <li>Morbi id augue id orci sagittis tempus.</li> <li>Vestibulum varius libero ac dignissim sodales.</li> </ul> <p></p> <p> </p><ul> <li>Aenean ac sem eget libero varius viverra sit amet vitae nunc.</li> </ul> <p></p> </body> </html>
{ "content_hash": "9a689c017fea25834e743155405f7836", "timestamp": "", "source": "github", "line_count": 325, "max_line_length": 861, "avg_line_length": 35.52307692307692, "alnum_prop": 0.6778692074491122, "repo_name": "Meggin/amphtml", "id": "fd35e20862f90b47df606c102781bb6eca54b6e9", "size": "11547", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/analytics.amp.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "24745" }, { "name": "HTML", "bytes": "159117" }, { "name": "JavaScript", "bytes": "2124465" }, { "name": "Protocol Buffer", "bytes": "16354" }, { "name": "Python", "bytes": "25322" } ], "symlink_target": "" }
var assert = require('assert'); describe('`Array.of` creates an array with the given arguments as elements', () => { it('dont mix it up with `Array(10)`, where the argument is the array length', () => { const arr = Array.of(10); assert.deepEqual(arr, [10]); }); it('puts all arguments into array elements', () => { const arr = Array.of(1, 2); assert.deepEqual(arr, [1, 2]); }); it('takes any kind and number of arguments', () => { const starter = [1, 2]; const end = [3, '4']; const arr = Array.of(starter, ...end); assert.deepEqual(arr, [[1, 2], 3, '4']); }); });
{ "content_hash": "bce8ba4116f2467dcd16da452c9ddfb9", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 87, "avg_line_length": 26.73913043478261, "alnum_prop": 0.5723577235772358, "repo_name": "unboxit/tdd-es6-babel-jest", "id": "0d2763c76d40b33d85755b49f01c4083b363a776", "size": "720", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/array/30-array-of-static-method.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "72027" } ], "symlink_target": "" }
create table list_test(id int not null , test_char char(50), test_varchar varchar(2000), test_bit bit(16), test_varbit bit varying(20), test_nchar nchar(50), test_nvarchar nchar varying(2000), test_string string, test_datetime timestamp, primary key (id, test_string)) PARTITION BY LIST (test_string) ( PARTITION p0 VALUES IN ('aaaaaaaaaa','bbbbbbbbbb','dddddddddd'), PARTITION p1 VALUES IN ('ffffffffff','gggggggggg','hhhhhhhhhh'), PARTITION p2 VALUES IN ('kkkkkkkkkk','llllllllll','mmmmmmmmmm') ); insert into list_test values(10,'www','www',B'101',B'1111',N'www',N'www','wwwwwwwwwww','2007-01-01 09:00:00'); select * from list_test order by 1; drop table list_test;
{ "content_hash": "70479c43cf26cf89e122853649757ecd", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 110, "avg_line_length": 37.6, "alnum_prop": 0.6555851063829787, "repo_name": "CUBRID/cubrid-testcases", "id": "7dc791d4e895066f6a12029f86a878fd42aa6f7b", "size": "857", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "sql/_01_object/_09_partition/_004_manipulation/cases/1373.sql", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PLSQL", "bytes": "682246" }, { "name": "Roff", "bytes": "23262735" }, { "name": "TSQL", "bytes": "5619" }, { "name": "eC", "bytes": "710" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- $Id$ --> <!-- This is a simple xml file that can be used in pipelines where all the --> <!-- work is done in the xsl and they just need a dummy xml to start the --> <!-- pipeline. --> <empty></empty>
{ "content_hash": "86ce68130e088a194fce907eedbb1638", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 78, "avg_line_length": 41.48, "alnum_prop": 0.7309546769527483, "repo_name": "apache/lenya", "id": "74d024a3f8cb23ee78bb757f79c8b381d799a455", "size": "1037", "binary": false, "copies": "4", "ref": "refs/heads/trunk", "path": "org.apache.lenya.webapp/src/main/webapp/lenya/content/util/empty.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "8295" }, { "name": "CSS", "bytes": "30572" }, { "name": "HTML", "bytes": "28814" }, { "name": "Java", "bytes": "2328029" }, { "name": "JavaScript", "bytes": "84684" }, { "name": "NSIS", "bytes": "4675" }, { "name": "Shell", "bytes": "23705" }, { "name": "XSLT", "bytes": "598838" } ], "symlink_target": "" }
package com.sun.jini.test.spec.jeri.proxytrustilfactory; import java.util.logging.Level; import com.sun.jini.qa.harness.QATest; import com.sun.jini.qa.harness.QAConfig; import net.jini.jeri.ProxyTrustILFactory; import net.jini.security.proxytrust.ServerProxyTrust; import net.jini.security.proxytrust.ProxyTrust; import net.jini.security.TrustVerifier; import com.sun.jini.test.spec.jeri.util.FakeProxyTrustILFactory; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.server.ExportException; import java.util.logging.Level; /** * <pre> * Purpose * This test verifies the behavior of the ProxyTrustILFactory * getRemoteInterfaces protected method. * * Test Cases * Test cases are defined by the Actions section below. * * Infrastructure * This test requires the following infrastructure: * 1) FakeProxyTrustILFactory * -a concrete impl of ProxyTrustILFactory used to * access protected methods of ProxyTrustILFactory * 2) FakeRemoteImpl * -a class that implements a Remote and a non-Remote interface * 3) FakeServerProxyTrustImpl * -extends FakeRemoteImpl * -a class that implements ServerProxyTrust and a sub interface * of the Remote interface implmented by FakeRemoteImpl * 4) FakeIllegalServerProxyTrustImpl * -extends FakeServerProxyTrustImpl * -a class that implements an illegal Remote interface * * Actions * The test performs the following steps: * 1) construct a FakeProxyTrustILFactory * 2) call getRemoteInterfaces method with null parameter * and verify NullPointerException is thrown * 3) call getRemoteInterfaces method with an instance * of FakeRemoteImpl and verify ExportException is thrown * 4) call getRemoteInterfaces method with an instance * of FakeIllegalServerProxyTrustImpl and verify * ExportException is thrown * 5) call getRemoteInterfaces method with an instance * of FakeServerProxyTrustImpl and verify an array containing the * FakeServerProxyTrustImpl's Remote interfaces and * ProxyTrust interface is returned * </pre> */ public class AccessorTest extends QATest { interface FakeRemoteInterface extends Remote { public void fakeMethod1() throws RemoteException; } interface FakeRemoteSubInterface extends FakeRemoteInterface { public void fakeMethod1() throws RemoteException; public void fakeMethod2() throws RemoteException; } interface FakeIllegalRemoteInterface extends FakeRemoteInterface { public void fakeMethod1(); } interface FakeInterface { public void fakeMethod3(); } class FakeRemoteImpl implements FakeRemoteInterface, FakeInterface { public void fakeMethod1() throws RemoteException { } public void fakeMethod3() { } } class FakeServerProxyTrustImpl extends FakeRemoteImpl implements FakeRemoteSubInterface, ServerProxyTrust { public void fakeMethod1() throws RemoteException { } public void fakeMethod2() throws RemoteException { } public TrustVerifier getProxyVerifier() throws RemoteException { return null; } } class FakeIllegalServerProxyTrustImpl extends FakeServerProxyTrustImpl implements FakeIllegalRemoteInterface { public void fakeMethod1() { } } // inherit javadoc public void setup(QAConfig sysConfig) throws Exception { } // inherit javadoc public void run() throws Exception { FakeProxyTrustILFactory fakeILFactory = new FakeProxyTrustILFactory(); FakeRemoteImpl fakeRemoteImpl = new FakeRemoteImpl(); FakeServerProxyTrustImpl fakeServerProxyTrustImpl = new FakeServerProxyTrustImpl(); FakeIllegalServerProxyTrustImpl fakeIllegalServerProxyTrustImpl = new FakeIllegalServerProxyTrustImpl(); logger.log(Level.FINE,"================================="); logger.log(Level.FINE,"test case 1: getRemoteInterfaces(null)"); logger.log(Level.FINE,""); try { fakeILFactory.getRemoteInterfaces(null); assertion(false); } catch (NullPointerException ignore) { } logger.log(Level.FINE,"================================="); logger.log(Level.FINE,"test case 2: getRemoteInterfaces" + "(non ServerProxyTrust Remote implementation)"); logger.log(Level.FINE,""); try { fakeILFactory.getRemoteInterfaces(fakeRemoteImpl); assertion(false); } catch (ExportException ignore) { } logger.log(Level.FINE,"================================="); logger.log(Level.FINE,"test case 3: getRemoteInterfaces" + "(ServerProxyTrust with illegal Remote interface)"); logger.log(Level.FINE,""); try { fakeILFactory.getRemoteInterfaces( fakeIllegalServerProxyTrustImpl); assertion(false); } catch (ExportException ignore) { } logger.log(Level.FINE,"================================="); logger.log(Level.FINE,"test case 4: getRemoteInterfaces" + " normal case"); logger.log(Level.FINE,""); Class[] interfaces = fakeILFactory.getRemoteInterfaces( fakeServerProxyTrustImpl); assertion(interfaces.length == 3, "number of interfaces: " + interfaces.length); assertion(interfaces[0] == FakeRemoteInterface.class, "interface[0] is: " + interfaces[0]); assertion(interfaces[1] == FakeRemoteSubInterface.class, "interface[1] is: " + interfaces[1]); assertion(interfaces[2] == ProxyTrust.class, "interface[2] is: " + interfaces[2]); } // inherit javadoc public void tearDown() { } }
{ "content_hash": "947f8c43e06fbb23fbfec3960132b304", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 75, "avg_line_length": 35.36094674556213, "alnum_prop": 0.6589692101740294, "repo_name": "cdegroot/river", "id": "b80c6f899ff49f5e589d0ec424b0957b2c1393aa", "size": "6782", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "qa/src/com/sun/jini/test/spec/jeri/proxytrustilfactory/AccessorTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2047" }, { "name": "Groovy", "bytes": "16876" }, { "name": "Java", "bytes": "22265383" }, { "name": "Shell", "bytes": "117083" } ], "symlink_target": "" }
from yapsy.IPlugin import IPlugin from tidylib import tidy_document from common import PluginType import logging class Tidy_HTML_Validator(IPlugin): category = PluginType.CHECKER id = "tidyHtmlValidator" contentTypes = ["text/html"] def __init__(self): self.__journal = None self.__codes = dict() self.__max_err = 0 self.__max_warn = 0 self.__max_inf = 0 self.__max_unk = 0 self.__severity = dict() self.__severity['Warning'] = 0.5 self.__severity['Error'] = 1.0 self.__severity['Info'] = 0.3 def setJournal(self, journal): self.__journal = journal maxes = {'W': self.__max_warn, 'E': self.__max_err, 'I': self.__max_inf, 'X': self.__max_unk} for dt in journal.getKnownDefectTypes(): # dt[0] type, dt[1] description # parse codes of W{X} or E{Y} -> get max X or Y try: letter = dt[0][0] number = int(dt[0][1:]) if letter in maxes: if number > maxes[letter]: maxes[letter] = number self.__codes[dt[1]] = dt[0] else: logging.getLogger(__name__).warn("Unknown letter: " + letter) except ValueError: continue def check(self, transaction): res = tidy_document(transaction.getContent(), keep_doc=True) lines = res[1].splitlines() # lines is a list of strings that looks like: # line 54 column 37 - Warning: replacing invalid character code 153 for line in lines: if not '-' in line: err_warn, msg = line.split(':', 1) self.__record(transaction, None, err_warn.strip(), msg.strip()) else: try: loc, desc = line.split(' - ', 1) err_warn, msg = desc.split(': ', 1) self.__record(transaction, loc, err_warn.strip(), msg.strip()) except: try: loc, desc = line.split('-') err_warn, msg = desc.split(':', 1) if len(msg.strip()) == 0: logging.getLogger(__name__).warning("No description! Line was: %s" % line) msg = "Generic HTML syntax " + err_warn.to_lower() self.__record(transaction, loc, err_warn.strip(), msg.strip()) except ValueError: logging.getLogger(__name__).exception("Failed to parse result! Line was: %s" % line) def __record(self, transaction, loc, cat, desc): code = self.__get_code(cat, desc) if cat in self.__severity: sev = self.__severity[cat] else: sev = -1.0 self.__journal.foundDefect(transaction.idno, code, desc, [cat, loc], sev) def __generate_code(self, letter, number, desc): code = letter + str(number) self.__codes[desc] = code return code def __get_code(self, cat, desc): code = None if desc in self.__codes: code = self.__codes[desc] else: if cat == 'Warning': num = self.__max_warn self.__max_warn = self.__max_warn + 1 elif cat == 'Error': num = self.__max_err self._max_err = self.__max_err + 1 elif cat == 'Info': num = self.__max_inf self.__max_inf = self.__max_inf + 1 else: log = logging.getLogger(__name__) log.error("Unknown category: " + cat) cat = 'X' num = self.__max_unk self.__max_unk = self.__max_unk + 1 code = self.__generate_code(cat[0], num, desc) return code
{ "content_hash": "4d6db426cff1c93da085b85f2b6f506d", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 108, "avg_line_length": 36.630630630630634, "alnum_prop": 0.46237088047220853, "repo_name": "eghuro/crawlcheck", "id": "3d2d80428ece1f28ed1cb631153d395b4ed51da9", "size": "4066", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/checker/plugin/checkers/tidy_html_validator.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "113212" } ], "symlink_target": "" }
// Copyright © Microsoft Corporation. All Rights Reserved. // This code released under the terms of the // Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.) using System; using System.Collections.ObjectModel; using System.Diagnostics; namespace Microsoft.TeamFoundation.Migration.Tfs2010WitAdapter { /// <summary> /// Revision class; used to represent a single revision. /// </summary> public sealed class MigrationRevision { private string m_author; // Person who created that revision private DateTime m_utcChangeTime; // Time of creation private Collection<MigrationField> m_fields; // Revision's fields private int m_revision; // Revision number (existing revisions only) private Watermark m_source; // Source revision (new revisions only) #region constructors /// <summary> /// Constructor. Initializes new revision. /// </summary> /// <param name="revision">Revision number</param> /// <param name="author">Person who created the revision</param> /// <param name="utcChangeTime">Time when revision was created</param> public MigrationRevision( int revision, string author, DateTime utcChangeTime) { if (revision < 0) { throw new ArgumentException("revision"); } if (string.IsNullOrEmpty(author)) { throw new ArgumentNullException("author"); } m_revision = revision; m_author = author; m_utcChangeTime = utcChangeTime; m_fields = new Collection<MigrationField>(); } /// <summary> /// Constructor for an empty revision, which is used as a baseline. /// </summary> internal MigrationRevision() { m_revision = -1; m_fields = new Collection<MigrationField>(); } /// <summary> /// Copy constructor for creating revisions on the target side. /// </summary> /// <param name="sourceId">Id of the source work item</param> /// <param name="source">Source revision</param> internal MigrationRevision( string sourceId, MigrationRevision source) { Debug.Assert(source.m_source == null, "Copying an already copied revision!"); Debug.Assert(source.m_revision >= 0, "Copying an invalid revision!"); m_revision = -1; m_author = source.m_author; m_utcChangeTime = source.m_utcChangeTime; m_fields = new Collection<MigrationField>(); m_source = new Watermark(sourceId, source.m_revision); } /// <summary> /// Constructor. Initializes new revision. /// </summary> /// <param name="sourceId">Id of the source work item</param> /// <param name="author">Person who created the revision</param> internal MigrationRevision(string sourceId, string author) { m_source = new Watermark(sourceId, 0); m_revision = m_source.Revision = -1; m_author = author; m_utcChangeTime = DateTime.UtcNow; m_fields = new Collection<MigrationField>(); } #endregion /// <summary> /// Gets the revision number. /// </summary> public int Revision { get { return m_revision; } } /// <summary> /// Gets name of the person created the revision. /// </summary> public string Author { get { return m_author; } internal set { m_author = value; } } /// <summary> /// Gets time when revision was created. /// </summary> public DateTime UtcChangeTime { get { return m_utcChangeTime; } } /// <summary> /// Gets all fields in the revision. /// </summary> public Collection<MigrationField> Fields { get { return m_fields; } } /// <summary> /// Returns source revision. /// </summary> public Watermark Source { get { return m_source; } } } }
{ "content_hash": "0b5206615e87f177a27b0e176bc21395", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 104, "avg_line_length": 36.77777777777778, "alnum_prop": 0.5617011387404137, "repo_name": "adamdriscoll/TfsIntegrationPlatform", "id": "26e6a0de051cc8b4fa6436403be9737eba9204fb", "size": "4306", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Features/IntegrationPlatform-svn/Adapters/TFS/Tfs2010WITAdapter/CommonConcepts/MigrationRevision.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "13536" }, { "name": "C", "bytes": "2463" }, { "name": "C#", "bytes": "26484323" }, { "name": "C++", "bytes": "496653" }, { "name": "CSS", "bytes": "6674" }, { "name": "HTML", "bytes": "567982" }, { "name": "Objective-C", "bytes": "346" }, { "name": "PLpgSQL", "bytes": "91299" }, { "name": "SQLPL", "bytes": "10698" }, { "name": "Smalltalk", "bytes": "26598" }, { "name": "XSLT", "bytes": "135096" } ], "symlink_target": "" }
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef security_sandbox_loggingCallbacks_h__ #define security_sandbox_loggingCallbacks_h__ #include "mozilla/sandboxing/loggingTypes.h" #include "mozilla/sandboxing/sandboxLogging.h" #ifdef TARGET_SANDBOX_EXPORTS #include <sstream> #include <iostream> #include "mozilla/Preferences.h" #include "nsContentUtils.h" #ifdef MOZ_STACKWALKING #include "nsStackWalk.h" #endif #define TARGET_SANDBOX_EXPORT __declspec(dllexport) #else #define TARGET_SANDBOX_EXPORT __declspec(dllimport) #endif namespace mozilla { namespace sandboxing { // We need to use a callback to work around the fact that sandbox_s lib is // linked into plugin-container.exe directly and also via xul.dll via // sandboxbroker.dll. This causes problems with holding the state required to // implement sandbox logging. // So, we provide a callback from plugin-container.exe that the code in xul.dll // can call to make sure we hit the right version of the code. void TARGET_SANDBOX_EXPORT SetProvideLogFunctionCb(ProvideLogFunctionCb aProvideLogFunctionCb); // Provide a call back so a pointer to a logging function can be passed later. static void PrepareForLogging() { SetProvideLogFunctionCb(ProvideLogFunction); } #ifdef TARGET_SANDBOX_EXPORTS static ProvideLogFunctionCb sProvideLogFunctionCb = nullptr; void SetProvideLogFunctionCb(ProvideLogFunctionCb aProvideLogFunctionCb) { sProvideLogFunctionCb = aProvideLogFunctionCb; } #ifdef MOZ_STACKWALKING static uint32_t sStackTraceDepth = 0; // NS_WalkStackCallback to write a formatted stack frame to an ostringstream. static void StackFrameToOStringStream(uint32_t aFrameNumber, void* aPC, void* aSP, void* aClosure) { std::ostringstream* stream = static_cast<std::ostringstream*>(aClosure); nsCodeAddressDetails details; char buf[1024]; NS_DescribeCodeAddress(aPC, &details); NS_FormatCodeAddressDetails(buf, sizeof(buf), aFrameNumber, aPC, &details); *stream << std::endl << "--" << buf; stream->flush(); } #endif // Log to the browser console and, if DEBUG build, stderr. static void Log(const char* aMessageType, const char* aFunctionName, const char* aContext, const bool aShouldLogStackTrace = false, uint32_t aFramesToSkip = 0) { std::ostringstream msgStream; msgStream << "Process Sandbox " << aMessageType << ": " << aFunctionName; if (aContext) { msgStream << " for : " << aContext; } #ifdef MOZ_STACKWALKING if (aShouldLogStackTrace) { if (sStackTraceDepth) { msgStream << std::endl << "Stack Trace:"; NS_StackWalk(StackFrameToOStringStream, aFramesToSkip, sStackTraceDepth, &msgStream, 0, nullptr); } } #endif std::string msg = msgStream.str(); #if defined(DEBUG) // Use NS_DebugBreak directly as we want child process prefix, but not source // file or line number. NS_DebugBreak(NS_DEBUG_WARNING, nullptr, msg.c_str(), nullptr, -1); #endif if (nsContentUtils::IsInitialized()) { nsContentUtils::LogMessageToConsole(msg.c_str()); } } // Initialize sandbox logging if required. static void InitLoggingIfRequired() { if (!sProvideLogFunctionCb) { return; } if (Preferences::GetBool("security.sandbox.windows.log") || PR_GetEnv("MOZ_WIN_SANDBOX_LOGGING")) { sProvideLogFunctionCb(Log); #if defined(MOZ_CONTENT_SANDBOX) && defined(MOZ_STACKWALKING) // We can only log the stack trace on process types where we know that the // sandbox won't prevent it. if (XRE_GetProcessType() == GeckoProcessType_Content) { Preferences::AddUintVarCache(&sStackTraceDepth, "security.sandbox.windows.log.stackTraceDepth"); } #endif } } #endif } // sandboxing } // mozilla #endif // security_sandbox_loggingCallbacks_h__
{ "content_hash": "e51700740aac2148082076829deafeae", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 79, "avg_line_length": 29.59124087591241, "alnum_prop": 0.7249629995066601, "repo_name": "fstudio/Phoenix", "id": "75747744b96eabb3707056a82df5d15358fe45b3", "size": "4054", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/Packers/deps/sandbox/chromium-shim/sandbox/win/loggingCallbacks.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "1228" }, { "name": "Batchfile", "bytes": "780" }, { "name": "C", "bytes": "9677836" }, { "name": "C#", "bytes": "11133" }, { "name": "C++", "bytes": "27602381" }, { "name": "CMake", "bytes": "32934" }, { "name": "CSS", "bytes": "24966" }, { "name": "D", "bytes": "7226" }, { "name": "HTML", "bytes": "409374" }, { "name": "Makefile", "bytes": "18318" }, { "name": "Objective-C", "bytes": "76457" }, { "name": "Objective-C++", "bytes": "59358" }, { "name": "PowerShell", "bytes": "3202" }, { "name": "Python", "bytes": "86998" }, { "name": "Shell", "bytes": "9003" }, { "name": "SourcePawn", "bytes": "1544" }, { "name": "nesC", "bytes": "6287" } ], "symlink_target": "" }
package it.unibz.inf.onprom.obdamapper.utility; import com.google.inject.Injector; import it.unibz.inf.ontop.exception.InvalidMappingException; import it.unibz.inf.ontop.exception.MappingIOException; import it.unibz.inf.ontop.injection.OntopSQLOWLAPIConfiguration; import it.unibz.inf.ontop.protege.core.OldSyntaxMappingConverter; import it.unibz.inf.ontop.spec.mapping.parser.impl.OntopNativeMappingParser; import it.unibz.inf.ontop.spec.mapping.pp.SQLPPMapping; import it.unibz.inf.ontop.spec.mapping.serializer.impl.OntopNativeMappingSerializer; import org.semanticweb.owlapi.model.OWLOntology; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Properties; public class OntopUtility { public static synchronized Properties getDataSourceProperties(File obdaFile) { try { OldSyntaxMappingConverter converter = new OldSyntaxMappingConverter(new FileReader(obdaFile), obdaFile.getName()); return converter.getDataSourceProperties().orElse(null); } catch (Exception e) { e.printStackTrace(); } return null; } public static OntopSQLOWLAPIConfiguration getConfiguration(OWLOntology ontology, //OBDAModel obdaModel, SQLPPMapping mapping, Properties dataSourceProperties) { return OntopSQLOWLAPIConfiguration.defaultBuilder() .ontology(ontology) .ppMapping(mapping) //.ppMapping(obdaModel.generatePPMapping()) .properties(dataSourceProperties) .build(); } // public static OBDAModel emptyOBDAModel(OntopMappingSQLAllConfiguration configuration) { // return new OBDAModel( // configuration.getInjector().getInstance(SQLPPMappingFactory.class), // new PrefixDocumentFormatImpl(), // configuration.getInjector().getInstance(AtomFactory.class), // configuration.getInjector().getInstance(TermFactory.class), // configuration.getInjector().getInstance(TypeFactory.class), // configuration.getInjector().getInstance(TargetAtomFactory.class), // configuration.getInjector().getInstance(SubstitutionFactory.class), // configuration.getInjector().getInstance(RDF.class), // configuration.getInjector().getInstance(TargetQueryParserFactory.class), // configuration.getInjector().getInstance(SQLPPSourceQueryFactory.class) // ); // } public static SQLPPMapping getOBDAModel(File obdaFile, File propertiesFile) { Properties properties = new Properties(); try { properties.load(new FileReader(propertiesFile)); } catch (IOException e) { throw new IllegalArgumentException(e); } // properties.put(RDBMSourceParameterConstants.DATABASE_URL, ""); // properties.put(RDBMSourceParameterConstants.DATABASE_USERNAME, ""); // properties.put(RDBMSourceParameterConstants.DATABASE_PASSWORD, ""); // properties.put(RDBMSourceParameterConstants.DATABASE_DRIVER, ""); return getOBDAModel(obdaFile, properties); } public static SQLPPMapping getOBDAModel(File obdaFile, Properties dataSource) { // properties.put(RDBMSourceParameterConstants.DATABASE_URL, ""); // properties.put(RDBMSourceParameterConstants.DATABASE_USERNAME, ""); // properties.put(RDBMSourceParameterConstants.DATABASE_PASSWORD, ""); // properties.put(RDBMSourceParameterConstants.DATABASE_DRIVER, ""); Injector injector = OntopSQLOWLAPIConfiguration.defaultBuilder() .properties(dataSource) .build().getInjector(); OntopNativeMappingParser parser = injector.getInstance(OntopNativeMappingParser.class); try { return parser.parse(obdaFile); } catch (InvalidMappingException | MappingIOException e) { throw new IllegalArgumentException(e); } } public static void saveModel(SQLPPMapping model, File file) { try { OntopNativeMappingSerializer writer = new OntopNativeMappingSerializer(); writer.write(file, model); } catch (Exception e) { e.printStackTrace(); } } }
{ "content_hash": "3311b3bd70e5a18b4423de0ee902dd2c", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 126, "avg_line_length": 44.59405940594059, "alnum_prop": 0.661190053285968, "repo_name": "onprom/onprom", "id": "69f157c7b0ab85c4dce47d87623852ddf85ccb5a", "size": "5386", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "obdamapper/src/main/java/it/unibz/inf/onprom/obdamapper/utility/OntopUtility.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "834321" }, { "name": "q", "bytes": "5662" } ], "symlink_target": "" }
{% load i18n static %} {% if entries %} <div class="slider-container"> <div class="slider"> <ul class="slides"> {% for entry in entries %} <li class="slide slide-{{ forloop.counter }}"> <a href="{{ entry.get_absolute_url }}" title="{{ entry.title }}"> <img src="{% if entry.image %}{{ entry.image.url }}{% endif %}" alt="{{ entry.title }}" /> </a> <div class="slide-content"> <h2> <a href="{{ entry.get_absolute_url }}" rel="bookmark" title="{{ entry.title }}">{{ entry.title }}</a> </h2> {{ entry.excerpt|linebreaks|truncatewords_html:30 }} </div> </li> {% endfor %} </ul> </div> </div> {% get_static_prefix as STATIC_URL %} <script type="text/javascript" src="{{ STATIC_URL }}zinnia/js/jquery.js"></script> <script type="text/javascript" src="{{ STATIC_URL }}zinnia/js/jquery.flexslider.js"></script> <script type="text/javascript"> jQuery(window).load(function() { jQuery(".slider").flexslider({ controlsContainer: ".slider", animation: "fade", slideshow: true, directionNav: true, controlNav: true, pauseOnHover: true, slideshowSpeed: 7000, animationDuration: 600 }); }); </script> {% endif %}
{ "content_hash": "fb8e1a079b7fb315f305dd130f1fd380", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 100, "avg_line_length": 33.325, "alnum_prop": 0.5408852213053263, "repo_name": "westinedu/newertrends", "id": "69a7f7392850df3618a85478c45d9335bf5798df", "size": "1333", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "zinnia/templates/zinnia/tags/slider_entries.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "450683" }, { "name": "PHP", "bytes": "1052" }, { "name": "Python", "bytes": "5511333" }, { "name": "Ruby", "bytes": "249" }, { "name": "Shell", "bytes": "1355" } ], "symlink_target": "" }
package org.wso2.carbon.business.messaging.hl7.store; import org.apache.axiom.om.OMElement; import org.apache.synapse.MessageContext; public class JDBCUtils { public static String getTableExistsQuery(String tableName) { return "SHOW TABLES LIKE '" + tableName + "';"; } public static String getCreateTableQuery(String tableName) { return "CREATE TABLE "+tableName+" (id INT AUTO_INCREMENT, messageId VARCHAR(50), message TEXT, timestamp TIMESTAMP, PRIMARY KEY (id));"; } public static String setMessage(String tableName, String messageId, String message) { return "INSERT INTO "+tableName+" (messageId, message) " + "VALUES (?, ?);"; } }
{ "content_hash": "70a848103a3bc92159152439e15a65ad", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 145, "avg_line_length": 28.44, "alnum_prop": 0.6835443037974683, "repo_name": "maheshika/carbon-mediation", "id": "cff0690d4b36d028aa0e440d7d51c7661d494a11", "size": "711", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/business-adaptors/hl7/org.wso2.carbon.business.messaging.hl7.store/src/main/java/org/wso2/carbon/business/messaging/hl7/store/JDBCUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "59562" }, { "name": "Java", "bytes": "3532688" }, { "name": "JavaScript", "bytes": "1112401" }, { "name": "Shell", "bytes": "456" } ], "symlink_target": "" }
using System; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudioTools.MockVsTests { internal class MockVsShell : IVsShell { public int AdviseBroadcastMessages(IVsBroadcastMessageEvents pSink, out uint pdwCookie) { throw new NotImplementedException(); } public int AdviseShellPropertyChanges(IVsShellPropertyEvents pSink, out uint pdwCookie) { throw new NotImplementedException(); } public int GetPackageEnum(out IEnumPackages ppenum) { throw new NotImplementedException(); } public int GetProperty(int propid, out object pvar) { pvar = null; return VSConstants.E_FAIL; } public int IsPackageInstalled(ref Guid guidPackage, out int pfInstalled) { throw new NotImplementedException(); } public int IsPackageLoaded(ref Guid guidPackage, out IVsPackage ppPackage) { throw new NotImplementedException(); } public int LoadPackage(ref Guid guidPackage, out IVsPackage ppPackage) { throw new NotImplementedException(); } public int LoadPackageString(ref Guid guidPackage, uint resid, out string pbstrOut) { throw new NotImplementedException(); } public int LoadUILibrary(ref Guid guidPackage, uint dwExFlags, out uint phinstOut) { throw new NotImplementedException(); } public int SetProperty(int propid, object var) { throw new NotImplementedException(); } public int UnadviseBroadcastMessages(uint dwCookie) { throw new NotImplementedException(); } public int UnadviseShellPropertyChanges(uint dwCookie) { throw new NotImplementedException(); } } }
{ "content_hash": "91185db9d7321977ccfa1745e0b80ad2", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 95, "avg_line_length": 27.718309859154928, "alnum_prop": 0.6224593495934959, "repo_name": "kant2002/nodejstools", "id": "be001ec35e7f12bfee6146d3d1037d59e9962dd5", "size": "2130", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Common/Tests/MockVsTests/MockVsShell.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "112" }, { "name": "Batchfile", "bytes": "4018" }, { "name": "C#", "bytes": "5435381" }, { "name": "CSS", "bytes": "504" }, { "name": "HTML", "bytes": "7785" }, { "name": "JavaScript", "bytes": "75360" }, { "name": "PowerShell", "bytes": "9002" }, { "name": "Python", "bytes": "2458" }, { "name": "TypeScript", "bytes": "8313" }, { "name": "Vue", "bytes": "1791" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Bull. Herb. Boissier 2(App. 1): 66 (1894) #### Original name Bacidia mesospora C. Knight ### Remarks null
{ "content_hash": "5110c762e54f02745ed4eb5d653c750f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 41, "avg_line_length": 13, "alnum_prop": 0.6863905325443787, "repo_name": "mdoering/backbone", "id": "685268f10e8f114e49fb93fa3371c26a2a0babb9", "size": "237", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Patellariales/Patellariaceae/Patellaria/Patellaria mesospora/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
var Database, Snake, SnakeEmitter, config, events, sys, util; var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }; sys = require('sys'); util = require('util'); events = require('events'); config = require('./config'); Database = require('./database').Database; /* Snake Class */ exports.SnakeEmitter = SnakeEmitter = new events.EventEmitter; exports.Snake = Snake = (function() { __extends(Snake, events.EventEmitter); function Snake(id) { this.id = id; this.kills = 0; this.deaths = 0; this.goodies = 0; this.length = config.SNAKE_LENGTH; this.name = ""; this.reset(); this.color = Math.floor(Math.random() * 16777215).toString(16); } Snake.prototype.setName = function(name) { this.name = name; return SnakeEmitter.emit('createPlayer', { name: this.name }); }; Snake.prototype.toJSON = function() { return { elements: this.elements, goodies: this.goodies, kills: this.kills, deaths: this.deaths, color: this.color, name: this.name, score: this.score() }; }; Snake.prototype.score = function() { return this.goodies + this.kills; }; Snake.prototype.addKill = function() { this.kills++; this.length = this.elements.unshift({ x: -1, y: -1 }); return this.length; }; Snake.prototype.reset = function() { var i, rH; rH = Math.floor(Math.random() * 49); this.deaths++; this.goodies = this.kills = 0; this.length = config.SNAKE_LENGTH; this.direction = "right"; this.elements = (function() { var _ref, _results; _results = []; for (i = _ref = this.length; _ref <= 1 ? i <= 1 : i >= 1; _ref <= 1 ? i++ : i--) { _results.push({ x: -i, y: rH }); } return _results; }).call(this); this.emit('reset'); return SnakeEmitter.emit('updateScore', { name: this.name, score: this.getScore() }); }; Snake.prototype.getScore = function() { return this.goodies * 2 + this.kills - this.deaths; }; Snake.prototype.doStep = function() { var i, _ref; for (i = 0, _ref = this.length - 1; 0 <= _ref ? i < _ref : i > _ref; 0 <= _ref ? i++ : i--) { this.moveTail(i); } this.moveHead(); return this; }; Snake.prototype.addGoodie = function() { this.length = this.elements.unshift({ x: -1, y: -1 }); this.goodies++; return this.length; }; Snake.prototype.moveTail = function(i) { this.elements[i].x = this.elements[i + 1].x; return this.elements[i].y = this.elements[i + 1].y; }; Snake.prototype.moveHead = function() { var head; head = this.length - 1; switch (this.direction) { case "left": this.elements[head].x -= 1; break; case "right": this.elements[head].x += 1; break; case "up": this.elements[head].y -= 1; break; case "down": this.elements[head].y += 1; } if (this.elements[head].x < 0) this.elements[head].x = config.STAGE_WIDTH; if (this.elements[head].y < 0) this.elements[head].y = config.STAGE_HEIGHT; if (this.elements[head].x > config.STAGE_WIDTH) this.elements[head].x = 0; if (this.elements[head].y > config.STAGE_HEIGHT) { return this.elements[head].y = 0; } }; Snake.prototype.head = function() { return this.elements[this.length - 1]; }; Snake.prototype.blocks = function(other) { var collision, element, head, _i, _len, _ref; head = other.head(); collision = false; _ref = this.elements; for (_i = 0, _len = _ref.length; _i < _len; _i++) { element = _ref[_i]; if (head.x === element.x && head.y === element.y) collision = true; } return collision; }; Snake.prototype.ateGoodie = function(goodie) { var head; if (goodie == null) return false; head = this.head(); return head.x === goodie.x && head.y === goodie.y; }; Snake.prototype.blocksSelf = function() { var collision, head, i, _ref; head = this.head(); collision = false; for (i = 0, _ref = this.length - 1; 0 <= _ref ? i < _ref : i > _ref; 0 <= _ref ? i++ : i--) { if (head.x === this.elements[i].x && head.y === this.elements[i].y) { collision = true; } } return collision; }; return Snake; })();
{ "content_hash": "9de5745e6ab8e286ae3c89962feb9215", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 335, "avg_line_length": 26.07262569832402, "alnum_prop": 0.5686736661667023, "repo_name": "jblanche/SnakeOnCoffee", "id": "5bca71721d2110e9d2304166be509a24636e1241", "size": "4667", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/snake.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "24529" }, { "name": "JavaScript", "bytes": "891860" } ], "symlink_target": "" }
/* config.h. Generated from config.h.in by configure. */ /* config.h.in. Generated from configure.in by autoheader. */ /* Define to 1 if you have the <dlfcn.h> header file. */ #define HAVE_DLFCN_H 1 /* Define to 1 if you have the `gettimeofday' function. */ #define HAVE_GETTIMEOFDAY 1 /* Define to 1 if you have the <inttypes.h> header file. */ #define HAVE_INTTYPES_H 1 /* Define to 1 if you have the `usb' library (-lusb). */ #define HAVE_LIBUSB 1 /* Define to 1 if you have the <memory.h> header file. */ #define HAVE_MEMORY_H 1 /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the `strerror' function. */ #define HAVE_STRERROR 1 /* Define to 1 if you have the <strings.h> header file. */ #define HAVE_STRINGS_H 1 /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the <unistd.h> header file. */ #define HAVE_UNISTD_H 1 /* libusb has usb_interrupt_read() */ #define HAVE_USB_INTERRUPT_READ 1 /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #define LT_OBJDIR ".libs/" /* Name of package */ #define PACKAGE "libp5glove" /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "" /* Define to the full name of this package. */ #define PACKAGE_NAME "" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "" /* Define to the home page for this package. */ #define PACKAGE_URL "" /* Define to the version of this package. */ #define PACKAGE_VERSION "" /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */ #define TIME_WITH_SYS_TIME 1 /* Version number of package */ #define VERSION "0.3" /* Define to 1 if the X Window System is missing or not being used. */ /* #undef X_DISPLAY_MISSING */
{ "content_hash": "f142c8e3022c02c4d1995ac01f6f4de7", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 78, "avg_line_length": 28.320987654320987, "alnum_prop": 0.6900610287707062, "repo_name": "awesomebytes/p5glove_ros", "id": "ecba3315dfe446b51d48feb37f495c286012b3c4", "size": "2294", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "p5glove_ros/include/p5glove_ros/config.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "98277" }, { "name": "C++", "bytes": "2150" }, { "name": "Shell", "bytes": "301920" } ], "symlink_target": "" }
type KeysOfUnion<T> = T extends T ? keyof T : never; export default KeysOfUnion
{ "content_hash": "1d0577a70ee29d0106e84fdc2b296269", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 52, "avg_line_length": 27, "alnum_prop": 0.7407407407407407, "repo_name": "Collect-io/Collect.io", "id": "c7e900c6a3587db6f5240b80fefd9370e7720e21", "size": "160", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "front/src/types/utilities/keysOfUnion.ts", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3605" }, { "name": "CSS", "bytes": "3015" }, { "name": "Gherkin", "bytes": "6341" }, { "name": "HTML", "bytes": "15400" }, { "name": "JavaScript", "bytes": "9905" }, { "name": "PHP", "bytes": "200340" }, { "name": "Vue", "bytes": "1422" } ], "symlink_target": "" }
(* category: Test synopsis: Basic reactions using functionDefinitions with three species in a compartment where the species have only substance units. componentTags: Compartment, Species, Reaction, Parameter, FunctionDefinition testTags: Amount, HasOnlySubstanceUnits testType: TimeCourse levels: 2.1, 2.2, 2.3, 2.4, 3.1 generatedBy: Numeric The model contains one compartment called "compartment". There are three species named S1, S2 and S3 and two parameters named k1 and k2. The model contains two reactions defined as: [{width:30em,margin: 1em auto}| *Reaction* | *Rate* | | S1 + S2 -> S3 | $k1 * multiply(S1,S2)$ | | S3 -> S1 + S2 | $k2 * S3$ |] The model contains one functionDefinition defined as: [{width:30em,margin: 1em auto}| *Id* | *Arguments* | *Formula* | | multiply | x, y | $x * y$ |] The initial conditions are as follows: [{width:30em,margin: 1em auto}| |*Value* |*Units* | |Initial amount of S1 |$1.0 \x 10^-2$ |mole | |Initial amount of S2 |$2.0 \x 10^-2$ |mole | |Initial amount of S3 |$1.0 \x 10^-2$ |mole | |Value of parameter k1 |$ 1.7 $ |mole^-1^ second^-1^ | |Value of parameter k2 |$ 0.3$ |second^-1^ | |Volume of compartment "compartment" |$ 1$ |litre |] The species have been declared as having substance units only. Thus, they must be treated as amounts where they appear in expressions. *) newcase[ "00114" ]; addFunction[ multiply, arguments -> {x, y}, math -> x * y]; addCompartment[ compartment, size -> 1 ]; addSpecies[ S1, initialAmount -> 1.0 10^-2, hasOnlySubstanceUnits->True ]; addSpecies[ S2, initialAmount -> 2.0 10^-2, hasOnlySubstanceUnits->True ]; addSpecies[ S3, initialAmount -> 1.0 10^-2, hasOnlySubstanceUnits->True ]; addParameter[ k1, value -> 1.7 ]; addParameter[ k2, value -> 0.3 ]; addReaction[ S1 + S2 -> S3, reversible -> False, kineticLaw -> k1 * multiply[S1,S2] ]; addReaction[ S3 -> S1 + S2, reversible -> False, kineticLaw -> k2 * S3 ]; makemodel[]
{ "content_hash": "a7583ecb7c7c2d871fc0e7315885e294", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 93, "avg_line_length": 39.089285714285715, "alnum_prop": 0.6084970306075834, "repo_name": "stanleygu/sbmltest2archive", "id": "3a492bf2125a2c914985f5dccd967c344498b03c", "size": "2189", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sbml-test-cases/cases/semantic/00114/00114-model.m", "mode": "33188", "license": "mit", "language": [ { "name": "M", "bytes": "12509" }, { "name": "Mathematica", "bytes": "721776" }, { "name": "Matlab", "bytes": "1729754" }, { "name": "Objective-C", "bytes": "144988" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>paco: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.13.1 / paco - 4.0.1</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> paco <small> 4.0.1 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-05-02 22:22:55 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-02 22:22:55 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.13.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.07.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.07.1 Official release 4.07.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; name: &quot;coq-paco&quot; version: &quot;4.0.1&quot; maintainer: &quot;paco@sf.snu.ac.kr&quot; synopsis: &quot;Coq library implementing parameterized coinduction&quot; homepage: &quot;https://github.com/snu-sf/paco/&quot; dev-repo: &quot;git+https://github.com/snu-sf/paco.git&quot; bug-reports: &quot;https://github.com/snu-sf/paco/issues/&quot; authors: [ &quot;Chung-Kil Hur &lt;gil.hur@sf.snu.ac.kr&gt;&quot; &quot;Georg Neis &lt;neis@mpi-sws.org&gt;&quot; &quot;Derek Dreyer &lt;dreyer@mpi-sws.org&gt;&quot; &quot;Viktor Vafeiadis &lt;viktor@mpi-sws.org&gt;&quot; &quot;Minki Cho &lt;minki.cho@sf.snu.ac.kr&gt;&quot; ] license: &quot;BSD-3&quot; build: [make &quot;-C&quot; &quot;src&quot; &quot;all&quot; &quot;-j%{jobs}%&quot;] install: [make &quot;-C&quot; &quot;src&quot; &quot;-f&quot; &quot;Makefile.coq&quot; &quot;install&quot;] remove: [&quot;rm&quot; &quot;-r&quot; &quot;-f&quot; &quot;%{lib}%/coq/user-contrib/Paco&quot;] depends: [ &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.13~&quot;} ] tags: [ &quot;date:2019-04-30&quot; &quot;category:Computer Science/Programming Languages/Formal Definitions and Theory&quot; &quot;category:Mathematics/Logic&quot; &quot;keyword:co-induction&quot; &quot;keyword:simulation&quot; &quot;keyword:parameterized greatest fixed point&quot; ] url { http: &quot;https://github.com/snu-sf/paco/archive/v4.0.1.tar.gz&quot; checksum: &quot;e8e312d5d00de4152eb21134e6a21768&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-paco.4.0.1 coq.8.13.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.13.1). The following dependencies couldn&#39;t be met: - coq-paco -&gt; coq &lt; 8.13~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-paco.4.0.1</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "5993f81d200407a367af525c32e5471e", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 159, "avg_line_length": 41.48863636363637, "alnum_prop": 0.5471103807176116, "repo_name": "coq-bench/coq-bench.github.io", "id": "aa29a4b3ccb2eacfc206aa7e55d7f4f3191266fc", "size": "7327", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.07.1-2.0.6/released/8.13.1/paco/4.0.1.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package oracle.ateam.sample.mobile.persistence.db; import java.math.BigDecimal; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.HashMap; import java.util.Map; import oracle.ateam.sample.mobile.util.ADFMobileLogger; /** * Class that holds information needed to set up a bind parameter in a SQL statement when accessing local database. * It contains the mapping between an entity attribute and the underlying table column, and can hold the actual value. * Optionally, it also contains SQL operator information when used to construct SQL where clause. * This class is also used to create an entity from a web service payload. When parsing the web service payload a list * of bindParamInfos is created which is then used to create an entity instance and to insert a row in the SQLite database. * * @deprecated Use the class with same name in oracle.ateam.sample.mobile.v2.persistence.* instead */ public class BindParamInfo { private static ADFMobileLogger sLog = ADFMobileLogger.createLogger(BindParamInfo.class); private static Map typeMapping = new HashMap(); static { // Mapping based on http://docs.oracle.com/javase/1.5.0/docs/guide/jdbc/getstart/mapping.html#1034737 typeMapping.put(String.class, new Integer(Types.CHAR)); typeMapping.put(BigDecimal.class, new Integer(Types.NUMERIC)); typeMapping.put(Boolean.class, new Integer(Types.BIT)); typeMapping.put(Integer.class, new Integer(Types.INTEGER)); typeMapping.put(Long.class, new Integer(Types.BIGINT)); typeMapping.put(Float.class, new Integer(Types.REAL)); typeMapping.put(Double.class, new Integer(Types.DOUBLE)); typeMapping.put(Byte[].class, new Integer(Types.BINARY)); typeMapping.put(Date.class, new Integer(Types.DATE)); typeMapping.put(java.util.Date.class, new Integer(Types.DATE)); typeMapping.put(Time.class, new Integer(Types.TIME)); typeMapping.put(Timestamp.class, new Integer(Types.TIMESTAMP)); typeMapping.put(Clob.class, new Integer(Types.CLOB)); typeMapping.put(Blob.class, new Integer(Types.BLOB)); } private String attributeName; private String tableName; private String columnName; private Class javaType; private int sqlType; private Object value; private boolean primaryKey = false; private String operator = "="; private boolean caseInsensitive = false; public void setAttributeName(String attributeName) { this.attributeName = attributeName; } public String getAttributeName() { return attributeName; } public void setColumnName(String columnName) { this.columnName = columnName; } public String getColumnName() { return columnName; } public void setSqlType(int sqlType) { this.sqlType = sqlType; } public int getSqlType() { return sqlType; } public void setValue(Object value) { this.value = convertDateValueIfNeeded(value); } public Object getValue() { return value; } public static int getSqlType(Class javaType) { Integer type = (Integer) typeMapping.get(javaType); return type.intValue(); } public void setJavaType(Class javaType) { this.javaType = javaType; if (typeMapping.get(javaType)!=null) { setSqlType(getSqlType(javaType)); } } public Class getJavaType() { return javaType; } public void setTableName(String tableName) { this.tableName = tableName; } public String getTableName() { return tableName; } public Object convertDateValueIfNeeded(Object value) { if (value!=null && value instanceof java.util.Date) { java.util.Date utilDateValue = (java.util.Date) value; // time component lost when using Date // Date sqlDate = new Date(utilDateValue.getTime()); Timestamp sqlDate = new Timestamp(utilDateValue.getTime()); value = sqlDate; } return value; } public void setPrimaryKey(boolean primaryKey) { this.primaryKey = primaryKey; } public boolean isPrimaryKey() { return primaryKey; } public void setOperator(String operator) { this.operator = operator; } public String getOperator() { return operator; } public void setCaseInsensitive(boolean caseInsensitive) { this.caseInsensitive = caseInsensitive; } public boolean isCaseInsensitive() { return caseInsensitive; } }
{ "content_hash": "3bca00100842f2374daeafc308730bde", "timestamp": "", "source": "github", "line_count": 175, "max_line_length": 123, "avg_line_length": 25.52, "alnum_prop": 0.7178683385579937, "repo_name": "oracle/mobile-persistence", "id": "350ee908cc6831f71eed07f2e044f34855ea0b38", "size": "4909", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Projects/Framework/Runtime/src/oracle/ateam/sample/mobile/persistence/db/BindParamInfo.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1649852" } ], "symlink_target": "" }
- Designed software architecture and wire-frame for Internet marketing software that utilized email and lead capturing components. This software used for a mortgage company in Southern California receives on average of 300 leads per day in their desired demographic. Languages Used: PHP, Ruby on Rails, HTML, CSS, JavaScript, jQuery Framework. - Currently designed over 1,000 website templates and many websites for different companies. Languages Used: PHP, HTML, CSS, JavaScript, jQuery Framework. - Developed file-secure platforms for the US Army Reserve to establish secure means of transfer for sensitive data throughout Battalions in Iraq and Afghanistan. - Developing Web UX/UI and Design for over 15 years. Languages Used: HTML, CSS, JavaScript, ASP .NET ### Skills - Solutions-driven, motivated self-starter. Works well in groups or in solo-projects with serious attention to detail (pixel perfect). - Respected for remaining calm in stressful situations, under tight deadlines and as an asset to the team. - Resourceful and driven to find a practical, deliverable solution that is profitable for the customer as well as for the Company. - Known for well-honed skills in multi-tasking and creative instincts in UI/UX development. - Development of beautiful design Layouts in HTML, CSS, JavaScript, Photoshop and Illustrator. #### Languages JavaScript, PHP, C/C++, CSS (LESS) #### Frameworks #####JavaScript: Node.js, Express.js, Hapi.js, Angular.js, Mocha, Jade, Handlebars/Mustache, MongoDB/Mongoose, SQL, jQuery #####PHP: WordPress, ModX ## Work History ### [Aspen Engineering and Construction Management](http://www.aspenengineering.com/) Chief Technology Officer: July 2005 – May 2008 Duties: - Design Company and sister company websites and networking - Create training for new software and core procedural techniques inside new technologies. - Deploy new hardware to offices and preform on-site or tele-installations via web media/video. - Design environment for Army Corp of Engineers to transfer files from Denver offices to Battalions in Iraq. - Create paperless filing standard with full implemention throughout sister companies located in California and Colorado. **Tools:** Dreamweaver, TextEdit+, UltraEdit, Photoshop, Illustrator, HTML, ASP, CSS, JavaScript, MySQL, SSH, CURL ### [Hillside Software](http://hillsidesoftware.com/) Front End Developer / Graphic Designer: August 2008 – January 2010 Duties: - Design Print Material in Photoshop and Illustrator/InDesign. - Create Logos and Vector Print Designs in Illustrator. - Help maintain and create new features for the HomeCards IDX software **Tools:** Aptana, Notepad++, Visual Studio, VB, .NET, Photoshop, Illustrator, HTML, Ruby on Rails, CSS, JavaScript, jQuery, SSH, CURL ### [Snaffo, Inc.](#) Developer / Designer: February 2010 – December 2010 Duties: - Design Websites using PHP, HTML, JavaScript, and many other Frameworks. - Design Print Material in Photoshop and Illustrator/InDesign. - Create Logos and Vector Print Designs in Illustrator. - Create Proposals and Invoices for Company billing to clients and accounting. - Design Marketing Material and Landing Pages for Email Campaigns. **Tools:** Aptana, Notepad++, Photoshop, Illustrator, HTML, PHP, CSS, JavaScript, jQuery, SSH, CURL, WordPress ### [The Global Elements](http://theglobalelements.com/) Senior Web Developer: January 2011 – December 2011 Duties: - Design Websites using PHP, HTML, JavaScript, and many other Frameworks. - Design Print Material in Photoshop and Illustrator/InDesign. - Create Logos and Vector Print Designs in Illustrator. - Use CMS systems like WordPress, ModX for Client Websites. **Tools:** Dreamweaver, TextEdit+, UltraEdit, Eclipse, Photoshop, Illustrator, HTML, ASP, PHP, Ruby on Rails, CSS, JavaScript, jQuery, MySQL, SQLite, SSH, CURL, ASP.NET ### [Hillside Software](http://hillsidesoftware.com/) Application Developer: April 2011 - September 2013 Duties: - Develop/Maintain WordPress IDX Plugin - Write Node.js scripts for large data processing/deligation - Develop Single Property Facebook Social Application in Node.js / Express.js **Tools:** SublimeText, Nodepad++, Photoshop, PHP, LESS, Node.js, CoffeeScript, Mocha, Jade, Mustache/Hogan.js, Ember.js, jQuery, MongoDB ### [Mobile Accord, Inc.](https://mgive.com/) Contract Developer: April 2013 - October 2014 Duties: - End-to-end contract developer for custom micro applications including - Social Share Node.js, Express, Angular.js, Mongoose application - m2Screen Node.js, Express, Angular.js, Mongoose application **Tools:** SublimeText, Nodepad++, Node.js, CoffeeScript, Mocha, Jade, NeDB, Angular.js, Ember.js, jQuery, Mongoose, Zombie.js, Request.js, SockJS, Socket.io ### [HomeAdvisor](https://homeadvisor.com/) Front-end Developer: September 2013 - August 2015 Duties: - JavaScript & CSS ninja for the consumer site - Develop image compression automation tasks with Gulp with an imagediff step using node.js - Lead front-end developer on the consumer site results page in Angular.js viewed over 5mil+ times a year - Refactored old styleguides to use preprocessor (LESS) and created living styleguide for the consumer site - Developed custom json model for front-end to get and share values from back-end controllers to front-end js **Tools:** SublimeText, Node.js, JavaScript, Mocha, Jade, Angular.js, jQuery, Mongoose, Spring MVC, Java, IntelliJ IDEA ### [HomeAdvisor](https://homeadvisor.com/) Senior Front-end Developer: August 2015 - Current Duties: - Senior JavaScript & CSS ninja for core products - Implemented Nightwatch.js for UAT testing across site and got front-end developers setup and trained - Responsible for JavaScript & CSS code quality of other front-end developers **Tools:** SublimeText, Node.js, JavaScript, Mocha, Jade, jQuery, Mongoose, Spring MVC, Java, IntelliJ IDEA, Elastic Search, jconsole, Nightwatch.js, Docker ## Education #### Chaffey High School - Ontario, California ##### Years Attended: 1999 -2001 ##### Degree: High School Diploma ###### Note: Early Credit Graduation Program with Chaffey Community College in the summers of 1999 and 2000. #### University of Riverside –Riverside, California ##### Years Attended: 2001 - 2004 #### Metropolitan State College of Denver ##### Years Attended: 2007 – 2008 ## Speaking ##### [RE BarCamp – Metrolist](http://www.metrolist.com/mymls_popup.asp?page=news&article=1209_re_barcamp) I spoke at this event in 2012 and gave a presentation on WordPress. It was a success and I was asked back for a second time. ## Contact Me - [Email](mailto:davehigginbotham@gmail.com) - [Github](https://github.com/dhigginbotham) - [Coderbits](https://coderbits.com/dhz) - [Codeivate](http://www.codeivate.com/users/dhigginbotham) - [LinkedIn](http://www.linkedin.com/in/dahigginbotham/)
{ "content_hash": "7f038f7de6ff6b14cf657af9c39f8aca", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 343, "avg_line_length": 47.183673469387756, "alnum_prop": 0.7587946943483276, "repo_name": "dhigginbotham/resume", "id": "eb601baab0b2968c50560ec61f9065850e8d8ffd", "size": "6994", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!DOCTYPE html> <!--[if IEMobile 7]><html class="iem7 no-js" lang="en" dir="ltr"><![endif]--> <!--[if lt IE 7]><html class="lt-ie9 lt-ie8 lt-ie7 no-js" lang="en" dir="ltr"><![endif]--> <!--[if (IE 7)&(!IEMobile)]><html class="lt-ie9 lt-ie8 no-js" lang="en" dir="ltr"><![endif]--> <!--[if IE 8]><html class="lt-ie9 no-js" lang="en" dir="ltr"><![endif]--> <!--[if (gt IE 8)|(gt IEMobile 7)]><!--> <html class="no-js not-oldie" lang="en" dir="ltr"> <!--<![endif]--> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="HandheldFriendly" content="true" /> <link rel="shortcut icon" href="https://www.epa.gov/sites/all/themes/epa/favicon.ico" type="image/vnd.microsoft.icon" /> <meta name="MobileOptimized" content="width" /> <meta http-equiv="cleartype" content="on" /> <meta http-equiv="ImageToolbar" content="false" /> <meta name="viewport" content="width=device-width" /> <meta name="version" content="20161218" /> <!--googleon: all--> <meta name="DC.description" content="" /> <meta name="DC.title" content="" /> <title> Assessing Climate Change Impacts to the Quantity and Seasonality of Ground Water Recharge in the Basin and Range Province of the Western United States| Research Project Database | Grantee Research Project | ORD | US EPA</title> <!--googleoff: snippet--> <meta name="keywords" content="" /> <link rel="shortlink" href="" /> <link rel="canonical" href="" /> <meta name="DC.creator" content="" /> <meta name="DC.language" content="en" /> <meta name="DC.Subject.epachannel" content="" /> <meta name="DC.type" content="" /> <meta name="DC.date.created" content="" /> <meta name="DC.date.modified" content="2013-03-04" /> <!--googleoff: all--> <link type="text/css" rel="stylesheet" href="https://www.epa.gov/misc/ui/jquery.ui.autocomplete.css" media="all" /> <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/lib/jquery.ui.theme.css" media="all" /> <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/libraries/template2/s.css" media="all" /> <!--[if lt IE 9]><link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/ie.css" media="all" /><![endif]--> <link rel="alternate" type="application/atom+xml" title="EPA.gov All Press Releases" href="https://www.epa.gov/newsreleases/search/rss" /> <link rel="alternate" type="application/atom+xml" title="EPA.gov Headquarters Press Releases" href="https://www.epa.gov/newsreleases/search/rss/field_press_office/headquarters" /> <link rel="alternate" type="application/atom+xml" title="Greenversations, EPA's Blog" href="https://blog.epa.gov/blog/feed/" /> <!--[if lt IE 9]><script src="https://www.epa.gov/sites/all/themes/epa/js/html5.js"></script><![endif]--> <style type="text/css"> /*This style needed for highlight link. Please do not remove*/ .hlText { font-family: "Arial"; color: red; font-weight: bold; font-style: italic; background-color: yellow; } .tblClass { font-size:smaller; min-width: 10%; line-height: normal; } </style> </head> <!-- NOTE, figure out body classes! --> <body class="node-type-(web-area|page|document|webform) (microsite|resource-directory)" > <!-- Google Tag Manager --> <noscript> <iframe src="//www.googletagmanager.com/ns.html?id=GTM-L8ZB" height="0" width="0" style="display:none;visibility:hidden"></iframe> </noscript> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-L8ZB');</script> <!-- End Google Tag Manager --> <div class="skip-links"><a href="#main-content" class="skip-link element-invisible element-focusable">Jump to main content</a></div> <header class="masthead clearfix" role="banner"> <img class="site-logo" src="https://www.epa.gov/sites/all/themes/epa/logo.png" alt="" /> <hgroup class="site-name-and-slogan"> <h1 class="site-name"><a href="https://www.epa.gov/" title="Go to the home page" rel="home"><span>US EPA</span></a></h1> <div class="site-slogan">United States Environmental Protection Agency</div> </hgroup> <form class="epa-search" method="get" action="https://search.epa.gov/epasearch/epasearch"> <label class="element-hidden" for="search-box">Search</label> <input class="form-text" placeholder="Search EPA.gov" name="querytext" id="search-box" value=""/> <button class="epa-search-button" id="search-button" type="submit" title="Search">Search</button> <input type="hidden" name="fld" value="" /> <input type="hidden" name="areaname" value="" /> <input type="hidden" name="areacontacts" value="" /> <input type="hidden" name="areasearchurl" value="" /> <input type="hidden" name="typeofsearch" value="epa" /> <input type="hidden" name="result_template" value="2col.ftl" /> <input type="hidden" name="filter" value="sample4filt.hts" /> </form> </header> <section id="main-content" class="main-content clearfix" role="main"> <div class="region-preface clearfix"> <div id="block-pane-epa-web-area-connect" class="block block-pane contextual-links-region"> <ul class="menu utility-menu"> <li class="menu-item"><a href="https://www.epa.gov/research-grants/forms/contact-us-about-research-grants" class="menu-link contact-us">Contact Us</a></li> </ul> </div> </div> <div class="main-column clearfix"> <!--googleon: all--> <div class="panel-pane pane-node-content" > <div class="pane-content"> <div class="node node-page clearfix view-mode-full"> <div class="box multi related-info right clear-right" style="max-width:300px; font-size:14px;"><!--googleoff: index--> <!-- RFA Search start --> <h5 class="pane-title">Related Information</h5> <div class="pane-content"> <ul><li><a href="https://www.epa.gov/research-grants/">Research Grants</a></li> <li><a href="https://www.epa.gov/P3">P3: Student Design Competition</a></li> <li><a href="https://www.epa.gov/research-fellowships/">Research Fellowships</a></li> <li><a href="https://www.epa.gov/sbir/">Small Business Innovation Research (SBIR)</a></li> <li><a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/search.welcome">Grantee Research Project Results Search</a></li> </ul> </div> <!-- RFA Search End --><!--googleon: index--> </div> <a name="content"></a> <h2> Assessing Climate Change Impacts to the Quantity and Seasonality of Ground Water Recharge in the Basin and Range Province of the Western United States</h2> <b>EPA Grant Number:</b> FP917491<br /> <b>Title:</b> Assessing Climate Change Impacts to the Quantity and Seasonality of Ground Water Recharge in the Basin and Range Province of the Western United States<br /> <b>Investigators:</b> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/13990"> Neff, Kirstin L </a> <br /> <strong>Institution:</strong> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.institutionInfo/institution/37"> <b>University of Arizona</b> </a> <br /> <strong>EPA Project Officer:</strong> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/7202"> Just, Theodore J. </a> <br /> <b>Project Period:</b> August 20, 2012 through August 19, 2015 <br /> <b>Project Amount:</b> $126,000 <br /> <b>RFA:</b> STAR Graduate Fellowships (2012) <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.rfatext/rfa_id/550">RFA Text</a>&nbsp;|&nbsp; <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/recipients.display/rfa_id/550">Recipients Lists</a> <br /> <b>Research Category:</b> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.researchCategory/rc_id/106">Academic Fellowships</a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.researchCategory/rc_id/990">Fellowship - Hydrology</a> <br /> <br> <h3>Objective:</h3> <p> Ground water recharge replenishes aquifers, a primary source of freshwater for human consumption and riparian areas. It is critical to understand the current ground water recharge regimes in the Western United States and how those regimes might shift in the face of climate change, impacting the quantity and composition of riparian ground water. This research will address the following questions: How does the seasonality of ground water recharge vary in the Basin and Range Province? How is the quantity and seasonality of ground water recharge related to the size of riparian areas? How will the quantity and seasonality of ground water recharge change with climate change?</p> <p></p> <h3>Approach:</h3> <p> This research will characterize ground water recharge regimes in study basins throughout the Basin and Range Province, extending from northern Mexico to the U.S. states of Nevada and Utah. It is comprised of new field investigations using water chemistry analysis and computer modeling to partition incoming precipitation into recharge, runoff and evapotranspiration, as well as the amalgamation and analysis of existing data for the region. The result will be a survey of current conditions with an eye toward how they might change with climate change.</p> <p></p> <h3>Expected Results:</h3> <p>Watersheds in the Basin and Range Province are characterized by a bimodal precipitation regime of dry summers and wet winters. The current assumption is that the relative contributions to ground water recharge by summer and winter precipitation varies throughout the province, with winter precipitation dominating in the northern parts of the region and summer floods playing a more significant role in the south, where the North American Monsoon extends its influence. In the future, climatologists expect a shift northward of precipitation and temperature norms as surface temperatures increase across the region, and a survey of recharge regimes up and down the basin and range could provide a space-for-time substitution in predicting future hydrologic conditions throughout the region.</p> <p><strong>Potential to Further Environmental/Human Health Protection</strong></p> <p>Establishing a robust understanding of the current relationship between the seasonality and quantity of precipitation and ground water recharge processes will allow for predictions of how recharge regimes might change in the future, and thus how the quantity and quality of freshwater for human use and ecosystems also might change. This research will provide the foundation for better management of ground water resources, helping to plan for future human use and the conservation of delicate ground water-fed riparian ecosystems and the valuable ecosystem services they provide to the surrounding semi-arid communities, including public health and economic benefits.</p> <p></p> <h3>Supplemental Keywords:</h3> <i>ground water recharge, climate change, riparian health</i> <p /> </div> </div> </div> <div id="block-epa-og-footer" class="block block-epa-og"> <p class="pagetop"><a href="#content">Top of Page</a></p> <!--googleoff: all--> <p id="epa-og-footer"> The perspectives, information and conclusions conveyed in research project abstracts, progress reports, final reports, journal abstracts and journal publications convey the viewpoints of the principal investigator and may not represent the views and policies of ORD and EPA. Conclusions drawn by the principal investigators have not been reviewed by the Agency. </p> </div> <!--googleoff: all--> </div> </section> <nav class="nav simple-nav simple-main-nav" role="navigation"> <div class="nav__inner"> <h2 class="element-invisible">Main menu</h2> <ul class="menu" role="menu"> <li class="menu-item" id="menu-learn" role="presentation"><a href="https://www.epa.gov/environmental-topics" title="Learn about EPA's environmental topics to help protect the environment in your home, workplace, and community and EPA&#039;s research mission is to conduct leading-edge research and foster the sound use of science and technology." class="menu-link" role="menuitem">Environmental Topics</a></li> <li class="menu-item" id="menu-lawsregs" role="presentation"><a href="https://www.epa.gov/laws-regulations" title="Laws written by Congress provide the authority for EPA to write regulations. Regulations explain the technical, operational, and legal details necessary to implement laws." class="menu-link" role="menuitem">Laws &amp; Regulations</a></li> <li class="menu-item" id="menu-about" role="presentation"><a href="https://www.epa.gov/aboutepa" title="Learn more about: our mission and what we do, how we are organized, and our history." class="menu-link" role="menuitem">About EPA</a></li> </ul> </div> </nav> <footer class="main-footer clearfix" role="contentinfo"> <div class="main-footer__inner"> <div class="region-footer"> <div class="block block-pane block-pane-epa-global-footer"> <div class="row cols-3"> <div class="col size-1of3"> <div class="col__title">Discover.</div> <ul class="menu"> <li><a href="https://www.epa.gov/accessibility">Accessibility</a></li> <li><a href="https://www.epa.gov/aboutepa/administrator-gina-mccarthy">EPA Administrator</a></li> <li><a href="https://www.epa.gov/planandbudget">Budget &amp; Performance</a></li> <li><a href="https://www.epa.gov/contracts">Contracting</a></li> <li><a href="https://www.epa.gov/home/grants-and-other-funding-opportunities">Grants</a></li> <li><a href="https://www.epa.gov/ocr/whistleblower-protections-epa-and-how-they-relate-non-disclosure-agreements-signed-epa-employees">No FEAR Act Data</a></li> <li><a href="https://www.epa.gov/home/privacy-and-security-notice">Privacy and Security</a></li> </ul> </div> <div class="col size-1of3"> <div class="col__title">Connect.</div> <ul class="menu"> <li><a href="https://www.data.gov/">Data.gov</a></li> <li><a href="https://www.epa.gov/office-inspector-general/about-epas-office-inspector-general">Inspector General</a></li> <li><a href="https://www.epa.gov/careers">Jobs</a></li> <li><a href="https://www.epa.gov/newsroom">Newsroom</a></li> <li><a href="https://www.whitehouse.gov/open">Open Government</a></li> <li><a href="http://www.regulations.gov/">Regulations.gov</a></li> <li><a href="https://www.epa.gov/newsroom/email-subscriptions">Subscribe</a></li> <li><a href="https://www.usa.gov/">USA.gov</a></li> <li><a href="https://www.whitehouse.gov/">White House</a></li> </ul> </div> <div class="col size-1of3"> <div class="col__title">Ask.</div> <ul class="menu"> <li><a href="https://www.epa.gov/home/forms/contact-us">Contact Us</a></li> <li><a href="https://www.epa.gov/home/epa-hotlines">Hotlines</a></li> <li><a href="https://www.epa.gov/foia">FOIA Requests</a></li> <li><a href="https://www.epa.gov/home/frequent-questions-specific-epa-programstopics">Frequent Questions</a></li> </ul> <div class="col__title">Follow.</div> <ul class="social-menu"> <li><a class="menu-link social-facebook" href="https://www.facebook.com/EPA">Facebook</a></li> <li><a class="menu-link social-twitter" href="https://twitter.com/epa">Twitter</a></li> <li><a class="menu-link social-youtube" href="https://www.youtube.com/user/USEPAgov">YouTube</a></li> <li><a class="menu-link social-flickr" href="https://www.flickr.com/photos/usepagov">Flickr</a></li> <li><a class="menu-link social-instagram" href="https://instagram.com/epagov">Instagram</a></li> </ul> <p class="last-updated">Last updated on Monday, March 4, 2013</p> </div> </div> </div> </div> </div> </footer> <script src="https://www.epa.gov/sites/all/libraries/template2/jquery.js"></script> <script src="https://www.epa.gov/sites/all/libraries/template/js.js"></script> <script src="https://www.epa.gov/sites/all/modules/custom/epa_core/js/alert.js"></script> <script src="https://www.epa.gov/sites/all/modules/contrib/jquery_update/replace/ui/ui/minified/jquery.ui.core.min.js"></script> <script src="https://www.epa.gov/sites/all/modules/contrib/jquery_update/replace/ui/ui/minified/jquery.ui.widget.min.js"></script> <script src="https://www.epa.gov/sites/all/modules/contrib/jquery_update/replace/ui/ui/minified/jquery.ui.position.min.js"></script> <script src="https://www.epa.gov/sites/all/modules/contrib/jquery_update/replace/ui/ui/minified/jquery.ui.autocomplete.min.js"></script> <!--[if lt IE 9]><script src="https://www.epa.gov/sites/all/themes/epa/js/ie.js"></script><![endif]--> <!-- REMOVE if not using --> <script language=javascript> <!-- // Activate cloak // pressing enter will not default submit the first defined button but the programmed defined button function chkCDVal(cdVal) { var isErr = true; try{ var CDParts = cdVal.split(','); var st = CDParts[0]; var cd = CDParts[1]; var objRegExp = new RegExp('[0-9][0-9]'); if (!isNaN(st)) { isErr = false; } if (!objRegExp.test(cd) || (cd.length>3)){ isErr = false; } } catch(err){ isErr = false; } return isErr; } function checkCongDist(cdtxt) { //alert(cdtxt.value); if (!chkCDVal(cdtxt.value)) { alert('Congressional District MUST be in the following format: state, district; example: Virginia, 08'); return false; } else { return true; } } function fnTrapKD(btn, event) { var btn = getObject(btn); if (document.all) { if (event.keyCode == 13) { event.returnValue=false;event.cancel = true;btn.click(); } } else { if (event.which == 13) { event.returnValue=false;event.cancelBubble = true;btn.click(); } } } function CheckFilter() { if (document.searchform.presetTopic.options[document.searchform.presetTopic.selectedIndex].value == 'NA'){ alert('You must select a subtopic. \n This item is not selectable'); document.searchform.presetTopic.options[0].selected = true; } } function openHelpWindow(url,title,scrollable) { var win = window.open(url,"title",'width=300,height=220,left=320,top=150,resizable=1,scrollbars='+scrollable+',menubar=no,status=no'); win.focus(); } function openNewWindow(url,title,scrollable) { var win = window.open(url,"title",'width=300,height=220,left=320,top=150,resizable=1,scrollbars='+scrollable+',menubar=no,status=no'); } function openNewWindow(url,title) { var win = window.open(url,"title",'width=300,height=220,left=320,top=150,resizable=1,scrollbars=no,menubar=no,status=no'); } function openNewMapWindow(url,title) { var win = window.open(url,"title",'width=800,height=450,left=320,top=150,resizable=1,scrollbars=no,menubar=no,status=no'); } function openNoticeWindow(url,title) { var win = window.open(url,"title",'width=300,height=150,left=500,top=150,resizable=1,scrollbars=no,menubar=no,status=no'); } function openNewSearchWindow(site,subj) { title = 'window'; var win = window.open('https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.pubsearch/site/' + site + '/redirect/' + subj,"title",'width=640,height=480,resizable=1,scrollbars=yes,menubar=yes,status=no'); } function autoCheck(name) { document.forms['thisForm'].elements[name].checked = true; } function alertUser() { var ok = alert("This search might take longer than expected. Please refrain from hitting the refresh or reload button on your browser. The search results will appear after the search is complete. Thank you."); } function closePopupWindow(redirectUrl) { opener.location = redirectUrl; opener.focus(); this.close(); } //--> </script> </body> </html>
{ "content_hash": "f3dd2b7e9a1137264ae8563887ad1757", "timestamp": "", "source": "github", "line_count": 422, "max_line_length": 682, "avg_line_length": 51.89336492890995, "alnum_prop": 0.6424494269144709, "repo_name": "1wheel/scraping", "id": "a44a3a6fe7182e87b9513d5821dbd55adf9c5895", "size": "21899", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "epa-grants/research/raw/09929.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4406" }, { "name": "DIGITAL Command Language", "bytes": "381196" }, { "name": "HTML", "bytes": "2546703681" }, { "name": "JavaScript", "bytes": "620077" }, { "name": "Jupyter Notebook", "bytes": "14020" } ], "symlink_target": "" }
set -e ginkgo -r --randomizeAllSpecs -cover bower install OUTPUT_FOLDER='builds' CURRENT_REVISION=`git rev-parse --short HEAD` OUTPUT_FILE="$OUTPUT_FOLDER/$CURRENT_REVISION.tar.gz" echo "Building application" APP_NAME="abbita" go get GOOS=linux GOARCH=amd64 go build -o $APP_NAME # docker run --rm -v "$(pwd)":/go/src/github.com/gophergala/abbita -w /go/src/github.com/gophergala/abbita -e GOOS=linux -e GOARCH=amd64 golang:1.3 go get && go build -o $APP_NAME tar -zcf $OUTPUT_FILE $APP_NAME public rm -f $APP_NAME echo "Application saved to $OUTPUT_FILE" cp $OUTPUT_FILE builds/latest.tar.gz echo "Deploying app" ansible-playbook -i provision/inv.ini provision/app.yml
{ "content_hash": "e31c6837ba3c65216a3be04fc607b74f", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 180, "avg_line_length": 39.588235294117645, "alnum_prop": 0.7488855869242199, "repo_name": "JamesMura/abbita", "id": "f2fbbe83354c985249405a0517ce27ae79f7bf79", "size": "686", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build_and_deploy_package.sh", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "38" }, { "name": "Go", "bytes": "6125" }, { "name": "JavaScript", "bytes": "1776" }, { "name": "Makefile", "bytes": "82" }, { "name": "Shell", "bytes": "686" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); require APPPATH . '/libraries/REST_Controller.php'; class Setting extends REST_Controller { public function __construct() { parent::__construct(); $this->load->model('master/Accused_type_model'); $this->load->model('master/Channel_model'); $this->load->model('master/Complain_type_model'); $this->load->model('master/Subject_model'); $this->load->model('master/Wish_model'); $this->load->model('master/Send_org_model'); $this->load->model('master/Setting_upload_model'); $this->load->model('data/Key_in_model'); } public function accused_type_get() { $id = $this->get('id'); $type= $this->get('type'); $parent_id= $this->get('parent_id'); if($type == 'parent'){ $data_result = $this->Accused_type_model->where('parent_id', $parent_id)->order_by('accused_type_id', 'DESC')->get_all(); }else { $data_result = $this->Accused_type_model->where('parent_id', '0')->order_by('accused_type_id', 'DESC')->get_all(); } // If the id parameter doesn't exist return all the users if ($id === NULL) { // Check if the users data store contains users (in case the database result returns NULL) if ($data_result) { // Set the response and exit $this->response($data_result, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { // Set the response and exit $this->response([ 'status' => FALSE, 'message' => 'No users were found' ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } // Find and return a single record for a particular user. $id = (int)$id; // Validate the id. if ($id <= 0) { // Invalid id, set the response and exit. $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } // Get the user from the array, using the id as key for retrieval. // Usually a model is to be used for this. //$type = NULL; $data_result = $this->Accused_type_model->get($id); if (!empty($data_result)) { $this->set_response($data_result, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { $this->set_response([ 'status' => FALSE, 'message' => 'User could not be found' ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } public function accused_type_post() { $ids = $this->Accused_type_model->insert(array( 'accused_type' => $this->post('accused_type'), 'parent_id' => $this->post('parent_id') )); $this->set_response($ids, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code } public function accused_type_put() { //$id = $this->put('accused_type'); //$ids = $this->AccusedType_model->update(array('accused_type' => $this->put('accused_type')),$id); $ids = $this->Accused_type_model->update(array( 'accused_type' => $this->put('accused_type'), 'parent_id' => $this->put('parent_id') ), $this->put('accused_type_id')); if ($ids) { $this->response($ids, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } } public function accused_type_delete() { $id = (int)$this->get('id'); // Validate the id. if ($id <= 0) { // Set the response and exit $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } $ids = $this->Accused_type_model->delete($id); $this->set_response($ids, REST_Controller::HTTP_NO_CONTENT); // NO_CONTENT (204) being the HTTP response code } public function channel_get() { $id = $this->get('id'); // If the id parameter doesn't exist return all the users if ($id === NULL) { // Check if the users data store contains users (in case the database result returns NULL) $types = $this->Channel_model->order_by('channel_id', 'DESC')->get_all(); if ($types) { // Set the response and exit $this->response($types, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { // Set the response and exit $this->response([ 'status' => FALSE, 'message' => 'No users were found' ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } // Find and return a single record for a particular user. $id = (int)$id; // Validate the id. if ($id <= 0) { // Invalid id, set the response and exit. $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } // Get the user from the array, using the id as key for retrieval. // Usually a model is to be used for this. //$type = NULL; $type = $this->Channel_model->get($id); if (!empty($type)) { $this->set_response($type, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { $this->set_response([ 'status' => FALSE, 'message' => 'User could not be found' ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } public function channel_post() { $ids = $this->Channel_model->insert(array('channel_name' => $this->post('channel_name'))); $this->set_response($ids, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code } public function channel_put() { //$id = $this->put('accused_type'); //$ids = $this->AccusedType_model->update(array('accused_type' => $this->put('accused_type')),$id); $ids = $this->Channel_model->update(array('channel_name' => $this->put('channel_name')), $this->put('channel_id')); if ($ids) { $this->response($ids, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } } public function channel_delete() { $id = (int)$this->get('id'); // Validate the id. if ($id <= 0) { // Set the response and exit $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } $ids = $this->Channel_model->delete($id); $this->set_response($ids, REST_Controller::HTTP_NO_CONTENT); // NO_CONTENT (204) being the HTTP response code } public function complain_type_get() { $id = $this->get('id'); $type= $this->get('type'); $parent_id= $this->get('parent_id'); // If the id parameter doesn't exist return all the users if ($id === NULL) { // Check if the users data store contains users (in case the database result returns NULL) $types = $this->Complain_type_model->get_all(); if($type == 'parent'){ $data_result = $this->Complain_type_model->where('parent_id', $parent_id)->order_by('complain_type_id', 'DESC')->get_all(); }else { $data_result = $this->Complain_type_model->where('parent_id', '0')->order_by('complain_type_id', 'DESC')->get_all(); } if ($data_result) { // Set the response and exit $this->response($data_result, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { // Set the response and exit $this->response([ 'status' => FALSE, 'message' => 'No users were found' ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } // Find and return a single record for a particular user. $id = (int)$id; // Validate the id. if ($id <= 0) { // Invalid id, set the response and exit. $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } // Get the user from the array, using the id as key for retrieval. // Usually a model is to be used for this. //$type = NULL; $data_result = $this->Complain_type_model->get($id); if (!empty($data_result)) { $this->set_response($data_result, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { $this->set_response([ 'status' => FALSE, 'message' => 'User could not be found' ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } public function complain_type_post() { $ids = $this->Complain_type_model->insert(array( 'complain_type_name' => $this->post('complain_type_name'), 'parent_id' => $this->post('parent_id'), 'status_active' => '1', 'icon_pin' => $this->post('icon_pin') )); $this->set_response($ids, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code } public function complain_type_put() { $data = $this->put(); if (!array_key_exists('complain_type_name', $data)) { unset($data['complain_type_name']); } if (!array_key_exists('parent_id', $data)) { unset($data['parent_id']); } if (!array_key_exists('icon_pin', $data)) { unset($data['icon_pin']); } $status_active = $data['status_active']; if (!array_key_exists('status_active', $data)) { unset($data['status_active']); } if (array_key_exists('complain_type_id', $data)) { $complain_type_id = $data['complain_type_id']; unset($data['complain_type_id']); } if (!empty($complain_type_id)) { if ($status_active != '' || !empty($status_active)) { $data_result = $this->Complain_type_model->where('parent_id', $complain_type_id)->order_by('complain_type_id', 'DESC')->get_all(); foreach($data_result AS $val){ $this->Complain_type_model->update(array( 'status_active' => $status_active ), $val->complain_type_id); } } $ids = $this->Complain_type_model->update($data, $complain_type_id); } if ($ids) { $this->response($ids, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } } public function complain_type_delete() { $id = (int)$this->get('id'); // Validate the id. if ($id <= 0) { // Set the response and exit $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } $ids = $this->Complain_type_model->delete($id); $this->set_response($ids, REST_Controller::HTTP_NO_CONTENT); // NO_CONTENT (204) being the HTTP response code } public function subject_get() { $id = $this->get('id'); // If the id parameter doesn't exist return all the users if ($id === NULL) { // Check if the users data store contains users (in case the database result returns NULL) $types = $this->Subject_model->order_by('subject_id', 'DESC')->get_all(); if ($types) { // Set the response and exit $this->response($types, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { // Set the response and exit $this->response([ 'status' => FALSE, 'message' => 'No users were found' ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } // Find and return a single record for a particular user. $id = (int)$id; // Validate the id. if ($id <= 0) { // Invalid id, set the response and exit. $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } // Get the user from the array, using the id as key for retrieval. // Usually a model is to be used for this. //$type = NULL; $type = $this->Subject_model->get($id); if (!empty($type)) { $this->set_response($type, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { $this->set_response([ 'status' => FALSE, 'message' => 'User could not be found' ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } public function subject_post() { $ids = $this->Subject_model->insert(array('subject_name' => $this->post('subject_name'))); $this->set_response($ids, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code } public function subject_put() { $ids = $this->Subject_model->update(array('subject_name' => $this->put('subject_name')), $this->put('subject_id')); if ($ids) { $this->response($ids, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } } public function subject_delete() { $id = (int)$this->get('id'); // Validate the id. if ($id <= 0) { // Set the response and exit $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } $ids = $this->Subject_model->delete($id); $this->set_response($ids, REST_Controller::HTTP_NO_CONTENT); // NO_CONTENT (204) being the HTTP response code } public function wish_get() { $id = $this->get('id'); // If the id parameter doesn't exist return all the users if ($id === NULL) { // Check if the users data store contains users (in case the database result returns NULL) $types = $this->Wish_model->order_by('wish_id', 'DESC')->get_all(); if ($types) { // Set the response and exit $this->response($types, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { // Set the response and exit $this->response([ 'status' => FALSE, 'message' => 'No users were found' ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } // Find and return a single record for a particular user. $id = (int)$id; // Validate the id. if ($id <= 0) { // Invalid id, set the response and exit. $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } // Get the user from the array, using the id as key for retrieval. // Usually a model is to be used for this. //$type = NULL; $type = $this->Wish_model->get($id); if (!empty($type)) { $this->set_response($type, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { $this->set_response([ 'status' => FALSE, 'message' => 'User could not be found' ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } public function wish_post() { $ids = $this->Wish_model->insert(array('wish_name' => $this->post('wish_name'))); $this->set_response($ids, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code } public function wish_put() { $ids = $this->Wish_model->update(array('wish_name' => $this->put('wish_name')), $this->put('wish_id')); if ($ids) { $this->response($ids, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } } public function wish_delete() { $id = (int)$this->get('id'); // Validate the id. if ($id <= 0) { // Set the response and exit $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } $ids = $this->Wish_model->delete($id); $this->set_response($ids, REST_Controller::HTTP_NO_CONTENT); // NO_CONTENT (204) being the HTTP response code } public function org_get() { $id = $this->get('id'); $type= $this->get('type'); $parent_id= $this->get('parent_id'); if ($id === NULL) { if($type == 'parent'){ $data_result = $this->Send_org_model->where(array('parent_id'=> $parent_id,'active'=>'1'))->order_by('send_org_id', 'DESC')->get_all(); }else { $data_result = $this->Send_org_model->where(array('parent_id'=>'0','active'=>'1'))->order_by('send_org_id', 'DESC')->get_all(); } if ($data_result) { $this->response($data_result, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { $this->response([ 'status' => FALSE, 'message' => 'No users were found' ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } $id = (int)$id; if ($id <= 0) { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } $data_result = $this->Send_org_model->get($id); if (!empty($data_result)) { $this->set_response($data_result, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { $this->set_response([ 'status' => FALSE, 'message' => 'User could not be found' ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } public function org_post() { $ids = $this->Send_org_model->insert(array( 'send_org_name' => $this->post('send_org_name'), 'parent_id' => $this->post('parent_id') )); $this->set_response($ids, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code } public function org_put() { $ids = $this->Send_org_model->update(array( 'send_org_name' => $this->put('send_org_name'), 'parent_id' => $this->put('parent_id') ), $this->put('send_org_id')); if ($ids) { $this->response($ids, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } } public function org_delete() { $id = (int)$this->get('id'); // Validate the id. if ($id <= 0) { // Set the response and exit $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } $ids = $this->Send_org_model->delete($id); $this->set_response($ids, REST_Controller::HTTP_NO_CONTENT); // NO_CONTENT (204) being the HTTP response code } public function use_org_get() { $id = $this->get('id'); $data_result = $this->Key_in_model->where('send_org_id', $id)->get_all(); if ($data_result) { $this->response($data_result, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { $this->response([ 'status' => FALSE, 'message' => 'No users were found' ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } public function use_accused_type_get() { $id = $this->get('id'); $data_result = $this->Key_in_model->where('accused_type_id', $id)->get_all(); if ($data_result) { $this->response($data_result, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { $this->response([ 'status' => FALSE, 'message' => 'No users were found' ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } public function use_complain_type_get() { $id = $this->get('id'); $data_result = $this->Key_in_model->where('complain_type_id', $id)->get_all(); if ($data_result) { $this->response($data_result, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { $this->response([ 'status' => FALSE, 'message' => 'No users were found' ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } public function setting_upload_get($id) { $data_result = $this->Setting_upload_model->where('setting_id', $id)->get(); if ($data_result) { $this->response($data_result, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { $this->response([ 'status' => FALSE, 'message' => 'No users were found' ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } public function setting_upload_post() { //$ids = $this->Setting_upload_model->update(array( //'upload_size' => $this->post('upload_size'), //'upload_type' => $this->post('upload_type') //), $this->post('setting_id')); //echo $this->post('upload_size')." ".$this->post('upload_type')." ".$this->post('setting_id'); $ids = $this->db->query("UPDATE ms_setting_upload SET upload_size = '".$this->post('upload_size')."', upload_type = '".$this->post('upload_type')."' WHERE setting_id = '".$this->post('setting_id')."' "); if ($ids) { $this->response($ids, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code }else{ $this->response($ids, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } } }
{ "content_hash": "982e1cfafab6933d0676ec7a41d2a3b0", "timestamp": "", "source": "github", "line_count": 608, "max_line_length": 211, "avg_line_length": 38.10690789473684, "alnum_prop": 0.5298027536794855, "repo_name": "cybergroupcm/drdhcbi", "id": "040bcb0e11c98c55770a90e31df87ff4f6ff59d7", "size": "23169", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "application/controllers/api/Setting.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "902853" }, { "name": "HTML", "bytes": "9521350" }, { "name": "JavaScript", "bytes": "3536218" }, { "name": "PHP", "bytes": "22805771" }, { "name": "Redcode", "bytes": "3162" } ], "symlink_target": "" }
namespace spvtools { namespace val { bool IsValidScope(uint32_t scope) { // Deliberately avoid a default case so we have to update the list when the // scopes list changes. switch (static_cast<SpvScope>(scope)) { case SpvScopeCrossDevice: case SpvScopeDevice: case SpvScopeWorkgroup: case SpvScopeSubgroup: case SpvScopeInvocation: case SpvScopeQueueFamilyKHR: case SpvScopeShaderCallKHR: return true; case SpvScopeMax: break; } return false; } spv_result_t ValidateScope(ValidationState_t& _, const Instruction* inst, uint32_t scope) { SpvOp opcode = inst->opcode(); bool is_int32 = false, is_const_int32 = false; uint32_t value = 0; std::tie(is_int32, is_const_int32, value) = _.EvalInt32IfConst(scope); if (!is_int32) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": expected scope to be a 32-bit int"; } if (!is_const_int32) { if (_.HasCapability(SpvCapabilityShader) && !_.HasCapability(SpvCapabilityCooperativeMatrixNV)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Scope ids must be OpConstant when Shader capability is " << "present"; } if (_.HasCapability(SpvCapabilityShader) && _.HasCapability(SpvCapabilityCooperativeMatrixNV) && !spvOpcodeIsConstant(_.GetIdOpcode(scope))) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Scope ids must be constant or specialization constant when " << "CooperativeMatrixNV capability is present"; } } if (is_const_int32 && !IsValidScope(value)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Invalid scope value:\n " << _.Disassemble(*_.FindDef(scope)); } return SPV_SUCCESS; } spv_result_t ValidateExecutionScope(ValidationState_t& _, const Instruction* inst, uint32_t scope) { SpvOp opcode = inst->opcode(); bool is_int32 = false, is_const_int32 = false; uint32_t value = 0; std::tie(is_int32, is_const_int32, value) = _.EvalInt32IfConst(scope); if (auto error = ValidateScope(_, inst, scope)) { return error; } if (!is_const_int32) { return SPV_SUCCESS; } // Vulkan specific rules if (spvIsVulkanEnv(_.context()->target_env)) { // Vulkan 1.1 specific rules if (_.context()->target_env != SPV_ENV_VULKAN_1_0) { // Scope for Non Uniform Group Operations must be limited to Subgroup if (spvOpcodeIsNonUniformGroupOperation(opcode) && value != SpvScopeSubgroup) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": in Vulkan environment Execution scope is limited to " << "Subgroup"; } } // If OpControlBarrier is used in fragment, vertex, tessellation evaluation, // or geometry stages, the execution Scope must be Subgroup. if (opcode == SpvOpControlBarrier && value != SpvScopeSubgroup) { _.function(inst->function()->id()) ->RegisterExecutionModelLimitation([](SpvExecutionModel model, std::string* message) { if (model == SpvExecutionModelFragment || model == SpvExecutionModelVertex || model == SpvExecutionModelGeometry || model == SpvExecutionModelTessellationEvaluation) { if (message) { *message = "in Vulkan evironment, OpControlBarrier execution scope " "must be Subgroup for Fragment, Vertex, Geometry and " "TessellationEvaluation execution models"; } return false; } return true; }); } // Vulkan generic rules // Scope for execution must be limited to Workgroup or Subgroup if (value != SpvScopeWorkgroup && value != SpvScopeSubgroup) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": in Vulkan environment Execution Scope is limited to " << "Workgroup and Subgroup"; } } // WebGPU Specific rules if (spvIsWebGPUEnv(_.context()->target_env)) { if (value != SpvScopeWorkgroup) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": in WebGPU environment Execution Scope is limited to " << "Workgroup"; } else { _.function(inst->function()->id()) ->RegisterExecutionModelLimitation( [](SpvExecutionModel model, std::string* message) { if (model != SpvExecutionModelGLCompute) { if (message) { *message = ": in WebGPU environment, Workgroup Execution Scope is " "limited to GLCompute execution model"; } return false; } return true; }); } } // TODO(atgoo@github.com) Add checks for OpenCL and OpenGL environments. // General SPIRV rules // Scope for execution must be limited to Workgroup or Subgroup for // non-uniform operations if (spvOpcodeIsNonUniformGroupOperation(opcode) && value != SpvScopeSubgroup && value != SpvScopeWorkgroup) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": Execution scope is limited to Subgroup or Workgroup"; } return SPV_SUCCESS; } spv_result_t ValidateMemoryScope(ValidationState_t& _, const Instruction* inst, uint32_t scope) { const SpvOp opcode = inst->opcode(); bool is_int32 = false, is_const_int32 = false; uint32_t value = 0; std::tie(is_int32, is_const_int32, value) = _.EvalInt32IfConst(scope); if (auto error = ValidateScope(_, inst, scope)) { return error; } if (!is_const_int32) { return SPV_SUCCESS; } if (value == SpvScopeQueueFamilyKHR) { if (_.HasCapability(SpvCapabilityVulkanMemoryModelKHR)) { return SPV_SUCCESS; } else { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": Memory Scope QueueFamilyKHR requires capability " << "VulkanMemoryModelKHR"; } } if (value == SpvScopeDevice && _.HasCapability(SpvCapabilityVulkanMemoryModelKHR) && !_.HasCapability(SpvCapabilityVulkanMemoryModelDeviceScopeKHR)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Use of device scope with VulkanKHR memory model requires the " << "VulkanMemoryModelDeviceScopeKHR capability"; } // Vulkan Specific rules if (spvIsVulkanEnv(_.context()->target_env)) { if (value == SpvScopeCrossDevice) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": in Vulkan environment, Memory Scope cannot be CrossDevice"; } // Vulkan 1.0 specifc rules if (_.context()->target_env == SPV_ENV_VULKAN_1_0 && value != SpvScopeDevice && value != SpvScopeWorkgroup && value != SpvScopeInvocation) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": in Vulkan 1.0 environment Memory Scope is limited to " << "Device, Workgroup and Invocation"; } // Vulkan 1.1 specifc rules if ((_.context()->target_env == SPV_ENV_VULKAN_1_1 || _.context()->target_env == SPV_ENV_VULKAN_1_2) && value != SpvScopeDevice && value != SpvScopeWorkgroup && value != SpvScopeSubgroup && value != SpvScopeInvocation) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": in Vulkan 1.1 and 1.2 environment Memory Scope is limited " << "to Device, Workgroup and Invocation"; } } // WebGPU specific rules if (spvIsWebGPUEnv(_.context()->target_env)) { switch (inst->opcode()) { case SpvOpControlBarrier: if (value != SpvScopeWorkgroup) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": in WebGPU environment Memory Scope is limited to " << "Workgroup for OpControlBarrier"; } break; case SpvOpMemoryBarrier: if (value != SpvScopeWorkgroup) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": in WebGPU environment Memory Scope is limited to " << "Workgroup for OpMemoryBarrier"; } break; default: if (spvOpcodeIsAtomicOp(inst->opcode())) { if (value != SpvScopeQueueFamilyKHR) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": in WebGPU environment Memory Scope is limited to " << "QueueFamilyKHR for OpAtomic* operations"; } } if (value != SpvScopeWorkgroup && value != SpvScopeInvocation && value != SpvScopeQueueFamilyKHR) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": in WebGPU environment Memory Scope is limited to " << "Workgroup, Invocation, and QueueFamilyKHR"; } break; } if (value == SpvScopeWorkgroup) { _.function(inst->function()->id()) ->RegisterExecutionModelLimitation( [](SpvExecutionModel model, std::string* message) { if (model != SpvExecutionModelGLCompute) { if (message) { *message = ": in WebGPU environment, Workgroup Memory Scope is " "limited to GLCompute execution model"; } return false; } return true; }); } } // TODO(atgoo@github.com) Add checks for OpenCL and OpenGL environments. return SPV_SUCCESS; } } // namespace val } // namespace spvtools
{ "content_hash": "75b79211b7255a0aa550f3d6fa3045b9", "timestamp": "", "source": "github", "line_count": 282, "max_line_length": 80, "avg_line_length": 36.13475177304964, "alnum_prop": 0.5850834151128558, "repo_name": "endlessm/chromium-browser", "id": "ea3ebcb66e4cdc301e4542d78eea6290d8d965cc", "size": "10970", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/swiftshader/third_party/SPIRV-Tools/source/val/validate_scopes.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
Copyright (c) 2016 Pedro Polez Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.]]-- local json = require("dkjson") --TODO: Load dkjson relative to mapDecoder's path. map = {} mapDec = {} local mapTextures = {} mapPositions = {} mapProps = {} local mapLighting = {} mapPropsfield = {} local tileWidth = 0 local tileHeight = 0 local mapPlayfieldWidthInTiles = 0 local mapPlayfieldHeightInTiles = 0 local objectListSize = 0 local zoomLevel = 1 function map.decodeJson(filename) assert(filename, "Filename is nil!") if not love.filesystem.isFile(filename) then error("Given filename is not a file! Is it a directory? Does it exist?") end --Reads file mapJson = love.filesystem.read(filename) --Attempts to decode file mapDec = json.decode(mapJson) end function map.generatePlayField() --TODO: Maps will be packed as renamed ZIP file extensios and will be able to be installed in users machines. So, textures and props have to be loaded from this directory. --Currently, the mapDecoder will look for textures in folder named textures in the root of the project, and props in a props folder. print("Current map information:") print("General information: =-=-=-=-=-=-=") if mapDec.general ~= nil then print("Map name: "..mapDec.general[1].name) print("Map version: "..mapDec.general[1].version) print("Map lighting: "..mapDec.general[1].lighting) if mapDec.general[1].lighting ~= nil then mapLighting = string.split_(mapDec.general[1].lighting, "|") end print("----") end print("Ground textures: =-=-=-=-=-=-=-=") for i, texture in ipairs(mapDec.textures) do --Print table contents for now print(texture.file) print(texture.mnemonic) print("---") table.insert(mapTextures, {file = texture.file, mnemonic = texture.mnemonic, image = love.graphics.newImage("textures/"..texture.file)}) end --Get ground texture dimensions tileWidth = mapTextures[1].image:getWidth()/2 tileHeight = mapTextures[1].image:getHeight()/2 print("Playfield props: =-=-=-=-=-=-=-=") if mapDec.props ~= nil then for i, props in ipairs(mapDec.props) do print(props.file) print(props.mnemonic) print(props.origin) print("----") table.insert(mapProps, {file = props.file, mnemonic = props.mnemonic, image = love.graphics.newImage("props/"..props.file), origins = string.split_(props.origin, "|")}) end else print("No props found on current map!") end --Add each ground tile to a table according to their texture --TODO: the following should be done on a separate thread. I have not tested the performance of the following lines on a colossal map. timerStart = love.timer.getTime() for i, groundTexture in ipairs(mapTextures) do for colunas in ipairs(mapDec.data) do for linhas in ipairs(mapDec.data[colunas]) do for i, properties in ipairs(mapDec.data[colunas][linhas]) do --Add ground texture if mnemonic is found if properties == groundTexture.mnemonic then local xPos = linhas local yPos = colunas if mapPositions[colunas] == nil then mapPositions[colunas] = {} end if mapPositions[colunas][linhas] == nil then mapPositions[colunas][linhas] = {} end table.insert(mapPositions[colunas][linhas], {texture = groundTexture.image, x=xPos, y=yPos}) end end end end end --TODO: Merge these loops, since both save stuff to the same table? --Add object to map accordingly for i, props in ipairs(mapProps) do --For each object --Loop through map terrain information for colunas in ipairs(mapDec.data) do for linhas in ipairs(mapDec.data[colunas]) do --Iterate over the objects in a given 2D position for i, objects in ipairs(mapDec.data[colunas][linhas]) do if objects == props.mnemonic then --table.insert(mapPositions[colunas][linhas], {texture=props.image, x=linhas, y=colunas, offX=props.origins[1], offY=props.origins[2]}) --VERY IMPORTANT NOTE ABOUT THE FOLLOWING LINES --these control the ZBuffer in some *dark manner*. IT WORKS. I **really** have to figure out why. pX, pY = map.toIso(linhas, colunas) colX = linhas * (tileWidth*zoomLevel) colY = colunas * (tileWidth*zoomLevel) colX, colY = map.toIso(colX, colY) table.insert(mapPropsfield,{texture=props.image, x=linhas, y=colunas, offX=props.origins[1], offY=props.origins[2], mapY = pY, mapX = pX, colX = colX, colY = colY, width = props.image:getWidth(), height = props.image:getHeight(), alpha = false}) end end end end end --Calculate map dimensions mapPlayfieldWidthInTiles = #mapPositions mapPlayfieldHeightInTiles = #mapPositions[1] --Store map original object list size without any extra dynamic objects objectListSize = #mapPropsfield timerEnd = love.timer.getTime() print("Decode loop took "..((timerEnd-timerStart)*100).."ms") end function map.drawGround(xOff, yOff, size) assert(xOff) assert(yOff) assert(size) zoomLevel = size --Apply lighting love.graphics.setColor(tonumber(mapLighting[1]), tonumber(mapLighting[2]), tonumber(mapLighting[3]), 255) --Draw the flat ground layer for the map, without elevation or props. for i in ipairs(mapPositions) do for j=1,#mapPositions[i], 1 do local xPos = mapPositions[i][j][1].x * (tileWidth*zoomLevel) local yPos = mapPositions[i][j][1].y * (tileWidth*zoomLevel) local xPos, yPos = map.toIso(xPos, yPos) love.graphics.draw(mapPositions[i][j][1].texture,xPos+xOff, yPos+yOff, 0, size, size, mapPositions[i][j][1].texture:getWidth()/2, mapPositions[i][j][1].texture:getHeight()/2 ) end end end function map.drawObjects(xOff, yOff, size) --Figure out dynamic object occlusion if #mapPropsfield > objectListSize then for i=objectListSize+1, #mapPropsfield do for j=1, objectListSize do if CheckCollision(mapPropsfield[j].colX, mapPropsfield[j].colY, mapPropsfield[j].width, mapPropsfield[j].height, mapPropsfield[i].colX, mapPropsfield[i].colY, mapPropsfield[i].width, mapPropsfield[i].height) and mapPropsfield[i].y < mapPropsfield[j].y and mapPropsfield[i].x < mapPropsfield[j].x then mapPropsfield[j].alpha = true end end end end --Sort ZBuffer and draw objects. for k,v in spairs(mapPropsfield, function(t,a,b) return t[b].mapY > t[a].mapY end) do local xPos = v.x * (tileWidth*zoomLevel) local yPos = v.y * (tileWidth*zoomLevel) local xPos, yPos = map.toIso(xPos, yPos) if v.alpha then love.graphics.setColor(255, 255, 255, 90) else love.graphics.setColor(255, 255, 255, 255) end love.graphics.draw(v.texture, xPos+xOff, yPos+yOff, 0, size, size, v.offX, v.offY) --Update values in order to minimize for loops v.alpha = false v.colX = xPos-v.offX v.colY = yPos-v.offY v.mapX, v.mapY = map.toIso(v.x, v.y) end end function map.getTileCoordinates2D(i, j) local xP = mapPositions[i][j][1].x * (tileWidth*zoomLevel) local yP = mapPositions[i][j][1].y * (tileWidth*zoomLevel) xP, yP = map.toIso(xP, yP) return xP, yP end function map.getPlayfieldWidth() return mapPlayfieldWidthInTiles end function map.getPlayfieldHeight() return mapPlayfieldHeightInTiles end function map.getGroundTileWidth() return tileWidth end --Links used whilst searching for information on isometric maps: --http://stackoverflow.com/questions/892811/drawing-isometric-game-worlds --https://gamedevelopment.tutsplus.com/tutorials/creating-isometric-worlds-a-primer-for-game-developers--gamedev-6511 --Give it a good read if you don't understand whats happening over here. function map.toIso(x, y) assert(x, "Position X is nil!") assert(y, "Position Y is nil!") newX = x-y newY = (x + y)/2 return newX, newY end function map.toCartesian(x, y) assert(x, "Position X is nil!") assert(y, "Position Y is nil!") x = (2 * y + x)/2 y = (2 * y - x)/2 return x, y end function map.insertNewObject(textureI, isoX, isoY, offXR, offYR) --User checks if offXR == nil then offXR = 0 end if offYR == nil then offYR = 0 end assert(textureI, "Invalid texture file for object!") assert(isoX, "No X position for object! (Isometric coordinates)") assert(isoY, "No Y position for object! (Isometric coordinates)") assert(mapPlayfieldWidthInTiles>=isoX, "Insertion coordinates out of map bounds! (X)") assert(mapPlayfieldWidthInTiles>=isoY, "Insertion coordinates out of map bounds! (Y)") local rx, ry = map.toIso(isoX, isoY) local colX = isoX * (tileWidth*zoomLevel) local colY = isoY * (tileWidth*zoomLevel) colX, colY = map.toIso(colX, colY) --Insert object on map table.insert(mapPropsfield, {texture=textureI, x=isoY, y=isoX+0.001, offX=offXR, offY = offYR, mapY = ry, mapX = rx, colX = colX, colY = colY, width = textureI:getWidth(), height = textureI:getHeight(), alpha = false}) end function map.removeObject(x, y) if #mapPositions[x][y] > 1 then table.remove(mapPositions[x][y], #mapPositions[x][y]) end end --This next function had the underscore added to avoid collisions with --any other possible split function the user may want to use. function string:split_(sSeparator, nMax, bRegexp) assert(sSeparator ~= '') assert(nMax == nil or nMax >= 1) local aRecord = {} if self:len() > 0 then local bPlain = not bRegexp nMax = nMax or -1 local nField, nStart = 1, 1 local nFirst,nLast = self:find(sSeparator, nStart, bPlain) while nFirst and nMax ~= 0 do aRecord[nField] = self:sub(nStart, nFirst-1) nField = nField+1 nStart = nLast+1 nFirst,nLast = self:find(sSeparator, nStart, bPlain) nMax = nMax-1 end aRecord[nField] = self:sub(nStart) end return aRecord --Credit goes to JoanOrdinas @ lua-users.org end function spairs(t, order) -- collect the keys local keys = {} for k in pairs(t) do keys[#keys+1] = k end -- if order function given, sort by it by passing the table and keys a, b, -- otherwise just sort the keys if order then table.sort(keys, function(a,b) return order(t, a, b) end) else table.sort(keys) end -- return the iterator function local i = 0 return function() i = i + 1 if keys[i] then return keys[i], t[keys[i]] end end --https://stackoverflow.com/questions/15706270/sort-a-table-in-lua --Function "spairs" by Michal Kottman. end -- Collision detection function; -- Returns true if two boxes overlap, false if they don't; -- x1,y1 are the top-left coords of the first box, while w1,h1 are its width and height; -- x2,y2,w2 & h2 are the same, but for the second box. function CheckCollision(x1,y1,w1,h1, x2,y2,w2,h2) return x1 < x2+w2 and x2 < x1+w1 and y1 < y2+h2 and y2 < y1+h1 end return map
{ "content_hash": "3a123a0fe135467eb706777f90dfad41", "timestamp": "", "source": "github", "line_count": 351, "max_line_length": 304, "avg_line_length": 33.111111111111114, "alnum_prop": 0.7093443469282396, "repo_name": "Sulunia/isomap-love2d", "id": "fec6dd87560acf10ce7952182addb1dec3861bf7", "size": "11639", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "isomap.lua", "mode": "33188", "license": "mit", "language": [ { "name": "Lua", "bytes": "58873" } ], "symlink_target": "" }
require "chef-utils" unless defined?(ChefUtils::CANARY) require_relative "../resource" require_relative "../win32/security" if ChefUtils.windows_ruby? autoload :ISO8601, "iso8601" if ChefUtils.windows_ruby? require_relative "../util/path_helper" require_relative "../util/backup" require "win32/taskscheduler" if ChefUtils.windows_ruby? class Chef class Resource class WindowsTask < Chef::Resource unified_mode true provides(:windows_task) { true } description "Use the **windows_task** resource to create, delete or run a Windows scheduled task." introduced "13.0" examples <<~DOC **Create a scheduled task to run every 15 minutes as the Administrator user**: ```ruby windows_task 'chef-client' do user 'Administrator' password 'password' command 'chef-client' run_level :highest frequency :minute frequency_modifier 15 end ``` **Create a scheduled task to run every 2 days**: ```ruby windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :daily frequency_modifier 2 end ``` **Create a scheduled task to run on specific days of the week**: ```ruby windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :weekly day 'Mon, Thu' end ``` **Create a scheduled task to run only once**: ```ruby windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :once start_time '16:10' end ``` **Create a scheduled task to run on current day every 3 weeks and delay upto 1 min**: ```ruby windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :weekly frequency_modifier 3 random_delay '60' end ``` **Create a scheduled task to run weekly starting on Dec 28th 2018**: ```ruby windows_task 'chef-client 8' do command 'chef-client' run_level :highest frequency :weekly start_day '12/28/2018' end ``` **Create a scheduled task to run every Monday, Friday every 2 weeks**: ```ruby windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :weekly frequency_modifier 2 day 'Mon, Fri' end ``` **Create a scheduled task to run when computer is idle with idle duration 20 min**: ```ruby windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :on_idle idle_time 20 end ``` **Delete a task named "old task"**: ```ruby windows_task 'old task' do action :delete end ``` **Enable a task named "chef-client"**: ```ruby windows_task 'chef-client' do action :enable end ``` **Disable a task named "ProgramDataUpdater" with TaskPath "\\Microsoft\\Windows\\Application Experience\\ProgramDataUpdater"** ```ruby windows_task '\\Microsoft\\Windows\\Application Experience\\ProgramDataUpdater' do action :disable end ``` DOC allowed_actions :create, :delete, :run, :end, :enable, :disable, :change property :task_name, String, regex: [%r{\A[^/\:\*\?\<\>\|]+\z}], description: "An optional property to set the task name if it differs from the resource block's name. Example: `Task Name` or `/Task Name`", name_property: true property :command, String, description: "The command to be executed by the windows scheduled task." property :cwd, String, description: "The directory the task will be run from." property :user, String, description: "The user to run the task as.", default: lazy { Chef::ReservedNames::Win32::Security::SID.LocalSystem.account_simple_name if ChefUtils.windows_ruby? }, default_description: "The localized SYSTEM user for the node." property :password, String, description: "The user's password. The user property must be set if using this property." property :run_level, Symbol, equal_to: %i{highest limited}, description: "Run with `:limited` or `:highest` privileges.", default: :limited property :force, [TrueClass, FalseClass], description: "When used with create, will update the task.", default: false property :interactive_enabled, [TrueClass, FalseClass], description: "Allow task to run interactively or non-interactively. Requires user and password to also be set.", default: false property :frequency_modifier, [Integer, String], default: 1, description: <<~DOCS * For frequency `:minute` valid values are 1 to 1439 * For frequency `:hourly` valid values are 1 to 23 * For frequency `:daily` valid values are 1 to 365 * For frequency `:weekly` valid values are 1 to 52 * For frequency `:monthly` valid values are `('FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST')` OR `1-12`. * e.g. If user want to run the task on `second week of the month` use `frequency_modifier` value as `SECOND`. Multiple values for weeks of the month should be comma separated e.g. `"FIRST, THIRD, LAST"`. * To run task every (n) months use values 1 to 12. DOCS property :frequency, Symbol, equal_to: %i{minute hourly daily weekly monthly once on_logon onstart on_idle none}, description: "The frequency with which to run the task. Note: This property is required in Chef Infra Client 14.1 or later. Note: The `:once` value requires the `start_time` property to be set." property :start_day, String, description: "Specifies the first date on which the task runs in **MM/DD/YYYY** format.", default_description: "The current date." property :start_time, String, description: "Specifies the start time to run the task, in **HH:mm** format." property :day, [String, Integer], description: <<~DOCS The day(s) on which the task runs. * Use this property when setting `frequency` to `:monthly` or `:weekly`. * Valid values with frequency `:weekly` are `MON`-`SUN` or `*`. * Valid values with frequency `:monthly` are `1-31`, `MON`-`SUN`, and `LASTDAY`. * Use `MON`-`SUN` or `LASTDAY` if you are setting `frequency_modifier` as "FIRST, SECOND, THIRD etc." else use 1-31. * Multiple days should be comma separated. e.g `1, 2, 3` or `MON, WED, FRI`. DOCS property :months, String, description: "The Months of the year on which the task runs, such as: `JAN, FEB` or `*`. Multiple months should be comma delimited. e.g. `Jan, Feb, Mar, Dec`." property :idle_time, Integer, description: "For `:on_idle` frequency, the time (in minutes) without user activity that must pass to trigger the task, from `1` - `999`." property :random_delay, [String, Integer], description: "Delays the task up to a given time (in seconds)." property :execution_time_limit, [String, Integer], description: "The maximum time the task will run. This field accepts either seconds or an ISO8601 duration value.", default: "PT72H", default_description: "PT72H (72 hours in ISO8601 duration format)" property :minutes_duration, [String, Integer], description: "" property :minutes_interval, [String, Integer], description: "" property :priority, Integer, description: "Use to set Priority Levels range from 0 to 10.", default: 7, callbacks: { "should be in range of 0 to 10" => proc { |v| v >= 0 && v <= 10 } } property :disallow_start_if_on_batteries, [TrueClass, FalseClass], introduced: "14.4", default: false, description: "Disallow start of the task if the system is running on battery power." property :stop_if_going_on_batteries, [TrueClass, FalseClass], introduced: "14.4", default: false, description: "Scheduled task option when system is switching on battery." property :description, String, introduced: "14.7", description: "The task description." property :start_when_available, [TrueClass, FalseClass], introduced: "14.15", default: false, description: "To start the task at any time after its scheduled time has passed." property :backup, [Integer, FalseClass], introduced: "17.0", default: 5, description: "Number of backups to keep of the task when modified/deleted. Set to false to disable backups." attr_accessor :exists, :task, :command_arguments VALID_WEEK_DAYS = %w{ mon tue wed thu fri sat sun * }.freeze VALID_DAYS_OF_MONTH = ("1".."31").to_a << "last" << "lastday" VALID_MONTHS = %w{JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC *}.freeze VALID_WEEKS = %w{FIRST SECOND THIRD FOURTH LAST LASTDAY}.freeze def after_created if random_delay validate_random_delay(random_delay, frequency) random_delay(sec_to_min(random_delay)) end if execution_time_limit execution_time_limit(259200) if execution_time_limit == "PT72H" raise ArgumentError, "Invalid value passed for `execution_time_limit`. Please pass seconds as an Integer (e.g. 60) or a String with numeric values only (e.g. '60')." unless numeric_value_in_string?(execution_time_limit) execution_time_limit(sec_to_min(execution_time_limit)) end validate_frequency(frequency) if action.include?(:create) || action.include?(:change) validate_start_time(start_time, frequency) validate_start_day(start_day, frequency) if start_day validate_user_and_password(user, password) validate_create_frequency_modifier(frequency, frequency_modifier) if frequency_modifier validate_create_day(day, frequency, frequency_modifier) if day validate_create_months(months, frequency) if months validate_frequency_monthly(frequency_modifier, months, day) if frequency == :monthly validate_idle_time(idle_time, frequency) idempotency_warning_for_frequency_weekly(day, start_day) if frequency == :weekly end private ## Resource is not idempotent when day, start_day is not provided with frequency :weekly ## we set start_day when not given by user as current date based on which we set the day property for current current date day is monday .. ## we set the monday as the day so at next run when new_resource.day is nil and current_resource day is monday due to which update gets called def idempotency_warning_for_frequency_weekly(day, start_day) if start_day.nil? && day.nil? logger.warn "To maintain idempotency for frequency :weekly provide start_day, start_time and day." end end # Validate the passed value is numeric values only if it is a string def numeric_value_in_string?(val) return true if Integer(val) rescue ArgumentError false end def validate_frequency(frequency) if frequency.nil? || !(%i{minute hourly daily weekly monthly once on_logon onstart on_idle none}.include?(frequency)) raise ArgumentError, "Frequency needs to be provided. Valid frequencies are :minute, :hourly, :daily, :weekly, :monthly, :once, :on_logon, :onstart, :on_idle, :none." end end def validate_frequency_monthly(frequency_modifier, months, day) # validates the frequency :monthly and raises error if frequency_modifier is first, second, third etc and day is not provided if (frequency_modifier != 1) && (frequency_modifier_includes_days_of_weeks?(frequency_modifier)) && !(day) raise ArgumentError, "Please select day on which you want to run the task e.g. 'Mon, Tue'. Multiple values must be separated by comma." end # frequency_modifier 2-12 is used to set every (n) months, so using :months property with frequency_modifier is not valid since they both used to set months. # Not checking value 1 here for frequency_modifier since we are setting that as default value it won't break anything since preference is given to months property if (frequency_modifier.to_i.between?(2, 12)) && !(months.nil?) raise ArgumentError, "For frequency :monthly either use property months or frequency_modifier to set months." end end # returns true if frequency_modifier has values First, second, third, fourth, last, lastday def frequency_modifier_includes_days_of_weeks?(frequency_modifier) frequency_modifier = frequency_modifier.to_s.split(",") frequency_modifier.map! { |value| value.strip.upcase } (frequency_modifier - VALID_WEEKS).empty? end def validate_random_delay(random_delay, frequency) if %i{on_logon onstart on_idle none}.include? frequency raise ArgumentError, "`random_delay` property is supported only for frequency :once, :minute, :hourly, :daily, :weekly and :monthly" end raise ArgumentError, "Invalid value passed for `random_delay`. Please pass seconds as an Integer (e.g. 60) or a String with numeric values only (e.g. '60')." unless numeric_value_in_string?(random_delay) end # @todo when we drop ruby 2.3 support this should be converted to .match?() instead of =~f def validate_start_day(start_day, frequency) if start_day && frequency == :none raise ArgumentError, "`start_day` property is not supported with frequency: #{frequency}" end # make sure the start_day is in MM/DD/YYYY format: http://rubular.com/r/cgjHemtWl5 if start_day raise ArgumentError, "`start_day` property must be in the MM/DD/YYYY format." unless %r{^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$}.match?(start_day) end end # @todo when we drop ruby 2.3 support this should be converted to .match?() instead of =~ def validate_start_time(start_time, frequency) if start_time raise ArgumentError, "`start_time` property is not supported with `frequency :none`" if frequency == :none raise ArgumentError, "`start_time` property must be in the HH:mm format (e.g. 6:20pm -> 18:20)." unless /^[0-2][0-9]:[0-5][0-9]$/.match?(start_time) else raise ArgumentError, "`start_time` needs to be provided with `frequency :once`" if frequency == :once end end # System users will not require a password # Other users will require a password if the task is non-interactive. # # @param [String] user # @param [String] password # def validate_user_and_password(user, password) if non_system_user?(user) if password.nil? && !interactive_enabled raise ArgumentError, "Please provide a password or check if this task needs to be interactive! Valid passwordless users are: '#{Chef::ReservedNames::Win32::Security::SID::SYSTEM_USER.join("', '")}'" end else unless password.nil? raise ArgumentError, "Password is not required for system users." end end end # Password is not required for system user and required for non-system user. def password_required?(user) @password_required ||= (!user.nil? && !Chef::ReservedNames::Win32::Security::SID.system_user?(user)) end alias non_system_user? password_required? def validate_create_frequency_modifier(frequency, frequency_modifier) if (%i{on_logon onstart on_idle none}.include?(frequency)) && ( frequency_modifier != 1) raise ArgumentError, "frequency_modifier property not supported with frequency :#{frequency}" end if frequency == :monthly unless (1..12).cover?(frequency_modifier.to_i) || frequency_modifier_includes_days_of_weeks?(frequency_modifier) raise ArgumentError, "frequency_modifier value #{frequency_modifier} is invalid. Valid values for :monthly frequency are 1 - 12, 'FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST'." end else unless frequency.nil? || frequency_modifier.nil? frequency_modifier = frequency_modifier.to_i min = 1 max = case frequency when :minute 1439 when :hourly 23 when :daily 365 when :weekly 52 else min end unless frequency_modifier.between?(min, max) raise ArgumentError, "frequency_modifier value #{frequency_modifier} is invalid. Valid values for :#{frequency} frequency are #{min} - #{max}." end end end end def validate_create_day(day, frequency, frequency_modifier) raise ArgumentError, "day property is only valid for tasks that run monthly or weekly" unless %i{weekly monthly}.include?(frequency) # This has been verified with schtask.exe https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/schtasks#d-dayday-- # verified with earlier code if day "*" is given with frequency it raised exception Invalid value for /D option raise ArgumentError, "day wild card (*) is only valid with frequency :weekly" if frequency == :monthly && day == "*" if day.is_a?(String) && day.to_i.to_s != day days = day.split(",") if days_includes_days_of_months?(days) # Following error will be raise if day is set as 1-31 and frequency is selected as :weekly since those values are valid with only frequency :monthly raise ArgumentError, "day values 1-31 or last is only valid with frequency :monthly" if frequency == :weekly else days.map! { |day| day.to_s.strip.downcase } unless (days - VALID_WEEK_DAYS).empty? raise ArgumentError, "day property invalid. Only valid values are: #{VALID_WEEK_DAYS.map(&:upcase).join(", ")}. Multiple values must be separated by a comma." end end end end def validate_create_months(months, frequency) raise ArgumentError, "months property is only valid for tasks that run monthly" if frequency != :monthly if months.is_a?(String) months = months.split(",") months.map! { |month| month.strip.upcase } unless (months - VALID_MONTHS).empty? raise ArgumentError, "months property invalid. Only valid values are: #{VALID_MONTHS.join(", ")}. Multiple values must be separated by a comma." end end end # This method returns true if day has values from 1-31 which is a days of moths and used with frequency :monthly def days_includes_days_of_months?(days) days.map! { |day| day.to_s.strip.downcase } (days - VALID_DAYS_OF_MONTH).empty? end def validate_idle_time(idle_time, frequency) if !idle_time.nil? && frequency != :on_idle raise ArgumentError, "idle_time property is only valid for tasks that run on_idle" end if idle_time.nil? && frequency == :on_idle raise ArgumentError, "idle_time value should be set for :on_idle frequency." end unless idle_time.nil? || idle_time > 0 && idle_time <= 999 raise ArgumentError, "idle_time value #{idle_time} is invalid. Valid values for :on_idle frequency are 1 - 999." end end # Converts the number of seconds to an ISO8601 duration format and returns it. # Ref : https://github.com/arnau/ISO8601/blob/master/lib/iso8601/duration.rb#L18-L23 # e.g. # ISO8601::Duration.new(65707200).to_s # returns 'PT65707200S' def sec_to_dur(seconds) ISO8601::Duration.new(seconds.to_i).to_s end def sec_to_min(seconds) seconds.to_i / 60 end action_class do if ChefUtils.windows_ruby? include ::Win32 MONTHS = { JAN: ::Win32::TaskScheduler::JANUARY, FEB: ::Win32::TaskScheduler::FEBRUARY, MAR: ::Win32::TaskScheduler::MARCH, APR: ::Win32::TaskScheduler::APRIL, MAY: ::Win32::TaskScheduler::MAY, JUN: ::Win32::TaskScheduler::JUNE, JUL: ::Win32::TaskScheduler::JULY, AUG: ::Win32::TaskScheduler::AUGUST, SEP: ::Win32::TaskScheduler::SEPTEMBER, OCT: ::Win32::TaskScheduler::OCTOBER, NOV: ::Win32::TaskScheduler::NOVEMBER, DEC: ::Win32::TaskScheduler::DECEMBER, }.freeze DAYS_OF_WEEK = { MON: ::Win32::TaskScheduler::MONDAY, TUE: ::Win32::TaskScheduler::TUESDAY, WED: ::Win32::TaskScheduler::WEDNESDAY, THU: ::Win32::TaskScheduler::THURSDAY, FRI: ::Win32::TaskScheduler::FRIDAY, SAT: ::Win32::TaskScheduler::SATURDAY, SUN: ::Win32::TaskScheduler::SUNDAY }.freeze WEEKS_OF_MONTH = { FIRST: ::Win32::TaskScheduler::FIRST_WEEK, SECOND: ::Win32::TaskScheduler::SECOND_WEEK, THIRD: ::Win32::TaskScheduler::THIRD_WEEK, FOURTH: ::Win32::TaskScheduler::FOURTH_WEEK, }.freeze DAYS_OF_MONTH = { 1 => ::Win32::TaskScheduler::TASK_FIRST, 2 => ::Win32::TaskScheduler::TASK_SECOND, 3 => ::Win32::TaskScheduler::TASK_THIRD, 4 => ::Win32::TaskScheduler::TASK_FOURTH, 5 => ::Win32::TaskScheduler::TASK_FIFTH, 6 => ::Win32::TaskScheduler::TASK_SIXTH, 7 => ::Win32::TaskScheduler::TASK_SEVENTH, 8 => ::Win32::TaskScheduler::TASK_EIGHTH, # cspell:disable-next-line 9 => ::Win32::TaskScheduler::TASK_NINETH, 10 => ::Win32::TaskScheduler::TASK_TENTH, 11 => ::Win32::TaskScheduler::TASK_ELEVENTH, 12 => ::Win32::TaskScheduler::TASK_TWELFTH, 13 => ::Win32::TaskScheduler::TASK_THIRTEENTH, 14 => ::Win32::TaskScheduler::TASK_FOURTEENTH, 15 => ::Win32::TaskScheduler::TASK_FIFTEENTH, 16 => ::Win32::TaskScheduler::TASK_SIXTEENTH, 17 => ::Win32::TaskScheduler::TASK_SEVENTEENTH, 18 => ::Win32::TaskScheduler::TASK_EIGHTEENTH, 19 => ::Win32::TaskScheduler::TASK_NINETEENTH, 20 => ::Win32::TaskScheduler::TASK_TWENTIETH, 21 => ::Win32::TaskScheduler::TASK_TWENTY_FIRST, 22 => ::Win32::TaskScheduler::TASK_TWENTY_SECOND, 23 => ::Win32::TaskScheduler::TASK_TWENTY_THIRD, 24 => ::Win32::TaskScheduler::TASK_TWENTY_FOURTH, 25 => ::Win32::TaskScheduler::TASK_TWENTY_FIFTH, 26 => ::Win32::TaskScheduler::TASK_TWENTY_SIXTH, 27 => ::Win32::TaskScheduler::TASK_TWENTY_SEVENTH, 28 => ::Win32::TaskScheduler::TASK_TWENTY_EIGHTH, 29 => ::Win32::TaskScheduler::TASK_TWENTY_NINTH, # cspell:disable-next-line 30 => ::Win32::TaskScheduler::TASK_THIRTYETH, 31 => ::Win32::TaskScheduler::TASK_THIRTY_FIRST, }.freeze PRIORITY = { "critical" => 0, "highest" => 1, "above_normal_2" => 2 , "above_normal_3" => 3, "normal_4" => 4, "normal_5" => 5, "normal_6" => 6, "below_normal_7" => 7, "below_normal_8" => 8, "lowest" => 9, "idle" => 10 }.freeze end def load_current_resource @current_resource = Chef::Resource::WindowsTask.new(new_resource.name) task = ::Win32::TaskScheduler.new(new_resource.task_name, nil, "\\", false) @current_resource.exists = task.exists?(new_resource.task_name) if @current_resource.exists task.get_task(new_resource.task_name) @current_resource.task = task pathed_task_name = new_resource.task_name.start_with?("\\") ? new_resource.task_name : "\\#{new_resource.task_name}" @current_resource.task_name(pathed_task_name) end @current_resource end # separated command arguments from :command property def set_command_and_arguments cmd, *args = Chef::Util::PathHelper.split_args(new_resource.command) new_resource.command = cmd new_resource.command_arguments = args.join(" ") end def set_start_day_and_time new_resource.start_day = Time.now.strftime("%m/%d/%Y") unless new_resource.start_day new_resource.start_time = Time.now.strftime("%H:%M") unless new_resource.start_time end def update_task(task) converge_by("#{new_resource} task updated") do do_backup task.set_account_information(new_resource.user, new_resource.password, new_resource.interactive_enabled) task.application_name = new_resource.command if new_resource.command task.parameters = new_resource.command_arguments if new_resource.command_arguments task.working_directory = new_resource.cwd if new_resource.cwd task.trigger = trigger unless new_resource.frequency == :none task.configure_settings(config_settings) task.creator = new_resource.user task.description = new_resource.description unless new_resource.description.nil? task.configure_principals(principal_settings) end end def trigger start_month, start_day, start_year = new_resource.start_day.to_s.split("/") start_hour, start_minute = new_resource.start_time.to_s.split(":") # TODO currently end_month, end_year and end_year needs to be set to 0. If not set win32-taskscheduler throwing nil into integer error. trigger_hash = { start_year: start_year.to_i, start_month: start_month.to_i, start_day: start_day.to_i, start_hour: start_hour.to_i, start_minute: start_minute.to_i, end_month: 0, end_day: 0, end_year: 0, trigger_type: trigger_type, type: type, random_minutes_interval: new_resource.random_delay, } if new_resource.frequency == :minute trigger_hash[:minutes_interval] = new_resource.frequency_modifier end if new_resource.frequency == :hourly minutes = convert_hours_in_minutes(new_resource.frequency_modifier.to_i) trigger_hash[:minutes_interval] = minutes end if new_resource.minutes_interval trigger_hash[:minutes_interval] = new_resource.minutes_interval end if new_resource.minutes_duration trigger_hash[:minutes_duration] = new_resource.minutes_duration end if trigger_type == ::Win32::TaskScheduler::MONTHLYDOW && frequency_modifier_contains_last_week?(new_resource.frequency_modifier) trigger_hash[:run_on_last_week_of_month] = true else trigger_hash[:run_on_last_week_of_month] = false end if trigger_type == ::Win32::TaskScheduler::MONTHLYDATE && day_includes_last_or_lastday?(new_resource.day) trigger_hash[:run_on_last_day_of_month] = true else trigger_hash[:run_on_last_day_of_month] = false end trigger_hash end def frequency_modifier_contains_last_week?(frequency_modifier) frequency_modifier = frequency_modifier.to_s.split(",") frequency_modifier.map! { |value| value.strip.upcase } frequency_modifier.include?("LAST") end def day_includes_last_or_lastday?(day) day = day.to_s.split(",") day.map! { |value| value.strip.upcase } day.include?("LAST") || day.include?("LASTDAY") end def convert_hours_in_minutes(hours) hours.to_i * 60 if hours end # TODO : Try to optimize this method # known issue : Since start_day and time is not mandatory while updating weekly frequency for which start_day is not mentioned by user idempotency # is not getting maintained as new_resource.start_day is nil and we fetch the day of week from start_day to set and its currently coming as nil and don't match with current_task def task_needs_update?(task) flag = false if new_resource.frequency == :none flag = (task.author != new_resource.user || task.application_name != new_resource.command || description_needs_update?(task) || task.parameters != new_resource.command_arguments.to_s || task.principals[:run_level] != run_level || task.settings[:disallow_start_if_on_batteries] != new_resource.disallow_start_if_on_batteries || task.settings[:stop_if_going_on_batteries] != new_resource.stop_if_going_on_batteries || task.settings[:start_when_available] != new_resource.start_when_available) else current_task_trigger = task.trigger(0) new_task_trigger = trigger flag = (ISO8601::Duration.new(task.idle_settings[:idle_duration])) != (ISO8601::Duration.new(new_resource.idle_time * 60)) if new_resource.frequency == :on_idle flag = (ISO8601::Duration.new(task.execution_time_limit)) != (ISO8601::Duration.new(new_resource.execution_time_limit * 60)) unless new_resource.execution_time_limit.nil? # if trigger not found updating the task to add the trigger if current_task_trigger.nil? flag = true else flag = true if start_day_updated?(current_task_trigger, new_task_trigger) == true || start_time_updated?(current_task_trigger, new_task_trigger) == true || current_task_trigger[:trigger_type] != new_task_trigger[:trigger_type] || current_task_trigger[:type] != new_task_trigger[:type] || current_task_trigger[:random_minutes_interval].to_i != new_task_trigger[:random_minutes_interval].to_i || current_task_trigger[:minutes_interval].to_i != new_task_trigger[:minutes_interval].to_i || task.author.to_s.casecmp(new_resource.user.to_s) != 0 || task.application_name != new_resource.command || description_needs_update?(task) || task.parameters != new_resource.command_arguments.to_s || task.working_directory != new_resource.cwd.to_s || task.principals[:logon_type] != logon_type || task.principals[:run_level] != run_level || PRIORITY[task.priority] != new_resource.priority || task.settings[:disallow_start_if_on_batteries] != new_resource.disallow_start_if_on_batteries || task.settings[:stop_if_going_on_batteries] != new_resource.stop_if_going_on_batteries || task.settings[:start_when_available] != new_resource.start_when_available if trigger_type == ::Win32::TaskScheduler::MONTHLYDATE flag = true if current_task_trigger[:run_on_last_day_of_month] != new_task_trigger[:run_on_last_day_of_month] end if trigger_type == ::Win32::TaskScheduler::MONTHLYDOW flag = true if current_task_trigger[:run_on_last_week_of_month] != new_task_trigger[:run_on_last_week_of_month] end end end flag end def start_day_updated?(current_task_trigger, new_task_trigger) ( new_resource.start_day && (current_task_trigger[:start_year].to_i != new_task_trigger[:start_year] || current_task_trigger[:start_month].to_i != new_task_trigger[:start_month] || current_task_trigger[:start_day].to_i != new_task_trigger[:start_day]) ) end def start_time_updated?(current_task_trigger, new_task_trigger) ( new_resource.start_time && ( current_task_trigger[:start_hour].to_i != new_task_trigger[:start_hour] || current_task_trigger[:start_minute].to_i != new_task_trigger[:start_minute] ) ) end def trigger_type case new_resource.frequency when :once, :minute, :hourly ::Win32::TaskScheduler::ONCE when :daily ::Win32::TaskScheduler::DAILY when :weekly ::Win32::TaskScheduler::WEEKLY when :monthly # If frequency modifier is set with frequency :monthly we are setting taskscheduler as monthlydow # Ref https://msdn.microsoft.com/en-us/library/windows/desktop/aa382061(v=vs.85).aspx new_resource.frequency_modifier.to_i.between?(1, 12) ? ::Win32::TaskScheduler::MONTHLYDATE : ::Win32::TaskScheduler::MONTHLYDOW when :on_idle ::Win32::TaskScheduler::ON_IDLE when :onstart ::Win32::TaskScheduler::AT_SYSTEMSTART when :on_logon ::Win32::TaskScheduler::AT_LOGON else raise ArgumentError, "Please set frequency" end end def type case trigger_type when ::Win32::TaskScheduler::ONCE { once: nil } when ::Win32::TaskScheduler::DAILY { days_interval: new_resource.frequency_modifier.to_i } when ::Win32::TaskScheduler::WEEKLY { weeks_interval: new_resource.frequency_modifier.to_i, days_of_week: days_of_week.to_i } when ::Win32::TaskScheduler::MONTHLYDATE { months: months_of_year.to_i, days: days_of_month.to_i } when ::Win32::TaskScheduler::MONTHLYDOW { months: months_of_year.to_i, days_of_week: days_of_week.to_i, weeks_of_month: weeks_of_month.to_i } when ::Win32::TaskScheduler::ON_IDLE # TODO: handle option for this trigger when ::Win32::TaskScheduler::AT_LOGON # TODO: handle option for this trigger when ::Win32::TaskScheduler::AT_SYSTEMSTART # TODO: handle option for this trigger end end # Deleting last from the array of weeks of month since last week is handled in :run_on_last_week_of_month parameter. def weeks_of_month weeks_of_month = [] if new_resource.frequency_modifier weeks = new_resource.frequency_modifier.split(",") weeks.map! { |week| week.to_s.strip.upcase } weeks.delete("LAST") if weeks.include?("LAST") weeks_of_month = get_binary_values_from_constants(weeks, WEEKS_OF_MONTH) end weeks_of_month end # Deleting the "LAST" and "LASTDAY" from days since last day is handled in :run_on_last_day_of_month parameter. def days_of_month days_of_month = [] if new_resource.day days = new_resource.day.to_s.split(",") days.map! { |day| day.to_s.strip.upcase } days.delete("LAST") if days.include?("LAST") days.delete("LASTDAY") if days.include?("LASTDAY") if days - (1..31).to_a days.each do |day| days_of_month << DAYS_OF_MONTH[day.to_i] end days_of_month = days_of_month.size > 1 ? days_of_month.inject(:|) : days_of_month[0] end else days_of_month = DAYS_OF_MONTH[1] end days_of_month end def days_of_week if new_resource.day # this line of code is just to support backward compatibility of wild card * new_resource.day = "mon, tue, wed, thu, fri, sat, sun" if new_resource.day == "*" && new_resource.frequency == :weekly days = new_resource.day.to_s.split(",") days.map! { |day| day.to_s.strip.upcase } weeks_days = get_binary_values_from_constants(days, DAYS_OF_WEEK) else # following condition will make the frequency :weekly idempotent if start_day is not provided by user setting day as the current_resource day if (current_resource) && (current_resource.task) && (current_resource.task.trigger(0)[:type][:days_of_week]) && (new_resource.start_day.nil?) weeks_days = current_resource.task.trigger(0)[:type][:days_of_week] else day = get_day(new_resource.start_day).to_sym if new_resource.start_day DAYS_OF_WEEK[day] end end end def months_of_year months_of_year = [] if new_resource.frequency_modifier.to_i.between?(1, 12) && !(new_resource.months) new_resource.months = set_months(new_resource.frequency_modifier.to_i) end if new_resource.months # this line of code is just to support backward compatibility of wild card * new_resource.months = "jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec" if new_resource.months == "*" && new_resource.frequency == :monthly months = new_resource.months.split(",") months.map! { |month| month.to_s.strip.upcase } months_of_year = get_binary_values_from_constants(months, MONTHS) else MONTHS.each do |key, value| months_of_year << MONTHS[key] end months_of_year = months_of_year.inject(:|) end months_of_year end # This values are set for frequency_modifier set as 1-12 # This is to give backward compatibility validated this values with earlier code and running schtask.exe # Used this as reference https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/schtasks#d-dayday-- def set_months(frequency_modifier) case frequency_modifier when 1 "jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec" when 2 "feb, apr, jun, aug, oct, dec" when 3 "mar, jun, sep, dec" when 4 "apr, aug, dec" when 5 "may, oct" when 6 "jun, dec" when 7 "jul" when 8 "aug" when 9 "sep" when 10 "oct" when 11 "nov" when 12 "dec" end end def get_binary_values_from_constants(array_values, constant) data = [] array_values.each do |value| value = value.to_sym data << constant[value] end data.size > 1 ? data.inject(:|) : data[0] end def run_level case new_resource.run_level when :highest ::Win32::TaskScheduler::TASK_RUNLEVEL_HIGHEST when :limited ::Win32::TaskScheduler::TASK_RUNLEVEL_LUA end end # TODO: while creating the configuration settings win32-taskscheduler it accepts execution time limit values in ISO8601 format def config_settings settings = { execution_time_limit: new_resource.execution_time_limit, enabled: true, } settings[:idle_duration] = new_resource.idle_time if new_resource.idle_time settings[:run_only_if_idle] = true if new_resource.idle_time settings[:priority] = new_resource.priority settings[:disallow_start_if_on_batteries] = new_resource.disallow_start_if_on_batteries settings[:stop_if_going_on_batteries] = new_resource.stop_if_going_on_batteries settings[:start_when_available] = new_resource.start_when_available settings end def principal_settings settings = {} settings[:run_level] = run_level settings[:logon_type] = logon_type settings end def description_needs_update?(task) task.description != new_resource.description unless new_resource.description.nil? end def logon_type # Ref: https://msdn.microsoft.com/en-us/library/windows/desktop/aa383566(v=vs.85).aspx # if nothing is passed as logon_type the TASK_LOGON_SERVICE_ACCOUNT is getting set as default so using that for comparison. user_id = new_resource.user.to_s password = new_resource.password.to_s if Chef::ReservedNames::Win32::Security::SID.service_account_user?(user_id) ::Win32::TaskScheduler::TASK_LOGON_SERVICE_ACCOUNT elsif Chef::ReservedNames::Win32::Security::SID.group_user?(user_id) ::Win32::TaskScheduler::TASK_LOGON_GROUP elsif !user_id.empty? && !password.empty? if new_resource.interactive_enabled ::Win32::TaskScheduler::TASK_LOGON_INTERACTIVE_TOKEN else ::Win32::TaskScheduler::TASK_LOGON_PASSWORD end else ::Win32::TaskScheduler::TASK_LOGON_INTERACTIVE_TOKEN end end # This method checks if task and command properties exist since those two are mandatory properties to create a schedules task. def basic_validation validate = [] validate << "Command" if new_resource.command.nil? || new_resource.command.empty? validate << "Task Name" if new_resource.task_name.nil? || new_resource.task_name.empty? return true if validate.empty? raise Chef::Exceptions::ValidationFailed.new "Value for '#{validate.join(", ")}' option cannot be empty" end # rubocop:disable Style/StringLiteralsInInterpolation def run_schtasks(task_action, options = {}) cmd = "schtasks /#{task_action} /TN \"#{new_resource.task_name}\" " options.each_key do |option| unless option == "TR" cmd += "/#{option} " cmd += "\"#{options[option].to_s.gsub('"', "\\\"")}\" " unless options[option] == "" end end # Appending Task Run [TR] option at the end since appending causing sometimes to append other options in option["TR"] value if options["TR"] cmd += "/TR \"#{options["TR"]} \" " unless task_action == "DELETE" end logger.trace("running: ") logger.trace(" #{cmd}") shell_out!(cmd, returns: [0]) end # rubocop:enable Style/StringLiteralsInInterpolation def get_day(date) Date.strptime(date, "%m/%d/%Y").strftime("%a").upcase end def do_backup file = "C:/Windows/System32/Tasks/#{new_resource.task_name}" Chef::Util::Backup.new(new_resource, file).backup! end end action :create, description: "Creates a scheduled task, or updates an existing task if any property has changed." do set_command_and_arguments if new_resource.command if current_resource.exists logger.trace "#{new_resource} task exist." unless (task_needs_update?(current_resource.task)) || (new_resource.force) logger.info "#{new_resource} task does not need updating and force is not specified - nothing to do" return end # if start_day and start_time is not set by user current date and time will be set while updating any property set_start_day_and_time unless new_resource.frequency == :none update_task(current_resource.task) else basic_validation set_start_day_and_time converge_by("#{new_resource} task created") do task = ::Win32::TaskScheduler.new if new_resource.frequency == :none task.new_work_item(new_resource.task_name, {}, { user: new_resource.user, password: new_resource.password, interactive: new_resource.interactive_enabled }) task.activate(new_resource.task_name) else task.new_work_item(new_resource.task_name, trigger, { user: new_resource.user, password: new_resource.password, interactive: new_resource.interactive_enabled }) end task.application_name = new_resource.command task.parameters = new_resource.command_arguments if new_resource.command_arguments task.working_directory = new_resource.cwd if new_resource.cwd task.configure_settings(config_settings) task.configure_principals(principal_settings) task.set_account_information(new_resource.user, new_resource.password, new_resource.interactive_enabled) task.creator = new_resource.user task.description = new_resource.description unless new_resource.description.nil? task.activate(new_resource.task_name) end end end action :run, description: "Runs a scheduled task." do if current_resource.exists logger.trace "#{new_resource} task exists" if current_resource.task.status == "running" logger.info "#{new_resource} task is currently running, skipping run" else converge_by("run scheduled task #{new_resource}") do current_resource.task.run end end else logger.debug "#{new_resource} task does not exist - nothing to do" end end action :delete, description: "Deletes a scheduled task." do if current_resource.exists logger.trace "#{new_resource} task exists" converge_by("delete scheduled task #{new_resource}") do do_backup ts = ::Win32::TaskScheduler.new ts.delete(current_resource.task_name) end else logger.debug "#{new_resource} task does not exist - nothing to do" end end action :end, description: "Ends a scheduled task." do if current_resource.exists logger.trace "#{new_resource} task exists" if current_resource.task.status != "running" logger.debug "#{new_resource} is not running - nothing to do" else converge_by("#{new_resource} task ended") do current_resource.task.stop end end else logger.debug "#{new_resource} task does not exist - nothing to do" end end action :enable, description: "Enables a scheduled task." do if current_resource.exists logger.trace "#{new_resource} task exists" if current_resource.task.status == "not scheduled" converge_by("#{new_resource} task enabled") do # TODO wind32-taskscheduler currently not having any method to handle this so using schtasks.exe here run_schtasks "CHANGE", "ENABLE" => "" end else logger.debug "#{new_resource} already enabled - nothing to do" end else logger.fatal "#{new_resource} task does not exist - nothing to do" raise Errno::ENOENT, "#{new_resource}: task does not exist, cannot enable" end end action :disable, description: "Disables a scheduled task." do if current_resource.exists logger.info "#{new_resource} task exists" if %w{ready running}.include?(current_resource.task.status) converge_by("#{new_resource} task disabled") do # TODO: in win32-taskscheduler there is no method which disables the task so currently calling disable with schtasks.exe run_schtasks "CHANGE", "DISABLE" => "" end else logger.warn "#{new_resource} already disabled - nothing to do" end else logger.warn "#{new_resource} task does not exist - nothing to do" end end action_class do alias_method :action_change, :action_create end end end end
{ "content_hash": "51fd9d4870fa4b23d727ecd3c682a2c0", "timestamp": "", "source": "github", "line_count": 1079, "max_line_length": 229, "avg_line_length": 45.14550509731232, "alnum_prop": 0.6053128592543932, "repo_name": "tas50/chef-1", "id": "224e59204b75e00608cf551ba46650e322276a00", "size": "49416", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "lib/chef/resource/windows_task.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1453" }, { "name": "HTML", "bytes": "74961" }, { "name": "Makefile", "bytes": "2652" }, { "name": "PowerShell", "bytes": "19283" }, { "name": "Python", "bytes": "13362" }, { "name": "Raku", "bytes": "128" }, { "name": "Ruby", "bytes": "10968490" }, { "name": "Shell", "bytes": "39807" } ], "symlink_target": "" }
@interface InterfaceController() @end @implementation InterfaceController - (void)awakeWithContext:(id)context { [super awakeWithContext:context]; // Configure interface objects here. } - (void)willActivate { // This method is called when watch view controller is about to be visible to user [super willActivate]; } - (void)didDeactivate { // This method is called when watch view controller is no longer visible [super didDeactivate]; } @end
{ "content_hash": "8e940f8d3ec362936600404a41e8729e", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 86, "avg_line_length": 17.703703703703702, "alnum_prop": 0.7196652719665272, "repo_name": "NilStack/NotificationOnWatch", "id": "a3be560ae77c9c068401a94264659414697cf32a", "size": "673", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "NotificationOnWatch WatchKit Extension/InterfaceController.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "7331" } ], "symlink_target": "" }
package _05BarracksWarsReturnOfTheDependencies.core; import _05BarracksWarsReturnOfTheDependencies.contracts.CommandInterpreter; import _05BarracksWarsReturnOfTheDependencies.contracts.Executable; import java.lang.reflect.InvocationTargetException; public class CommandInterpreterImpl implements CommandInterpreter { private static final String PACKAGE_PATH_COMMANDS = "_05BarracksWarsReturnOfTheDependencies.core.commands."; private static final String COMMAND_SUFFIX = "Command"; public CommandInterpreterImpl() { } @Override public Executable interpretCommand(String command) { String commandName = Character.toUpperCase(command.charAt(0)) + command.substring(1); try { return (Executable) Class.forName(PACKAGE_PATH_COMMANDS + commandName + COMMAND_SUFFIX) .getDeclaredConstructor().newInstance(); } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { throw new RuntimeException("Invalid command!"); } } }
{ "content_hash": "b94958bb357761a39fe7aee908b812e0", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 146, "avg_line_length": 40.96296296296296, "alnum_prop": 0.7549728752260397, "repo_name": "yangra/SoftUni", "id": "db42641cca38ef8708f04211eb4d2c47835d7d90", "size": "1106", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "JavaFundamentals/JavaOOPAdvanced/05.ReflectionExercise/src/_05BarracksWarsReturnOfTheDependencies/core/CommandInterpreterImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "301" }, { "name": "Batchfile", "bytes": "64953" }, { "name": "C#", "bytes": "1237474" }, { "name": "CSS", "bytes": "474654" }, { "name": "HTML", "bytes": "187923" }, { "name": "Java", "bytes": "2815020" }, { "name": "JavaScript", "bytes": "636500" }, { "name": "PHP", "bytes": "72489" }, { "name": "SQLPL", "bytes": "27954" }, { "name": "Shell", "bytes": "84674" } ], "symlink_target": "" }
//===- llvm/CodeGen/GlobalISel/Utils.cpp -------------------------*- C++ -*-==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// /// \file This file implements the utility functions used by the GlobalISel /// pipeline. //===----------------------------------------------------------------------===// #include "llvm/CodeGen/GlobalISel/Utils.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/Twine.h" #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h" #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/StackProtector.h" #include "llvm/CodeGen/TargetInstrInfo.h" #include "llvm/CodeGen/TargetPassConfig.h" #include "llvm/CodeGen/TargetRegisterInfo.h" #include "llvm/IR/Constants.h" #define DEBUG_TYPE "globalisel-utils" using namespace llvm; Register llvm::constrainRegToClass(MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const RegisterBankInfo &RBI, Register Reg, const TargetRegisterClass &RegClass) { if (!RBI.constrainGenericRegister(Reg, RegClass, MRI)) return MRI.createVirtualRegister(&RegClass); return Reg; } Register llvm::constrainOperandRegClass( const MachineFunction &MF, const TargetRegisterInfo &TRI, MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const RegisterBankInfo &RBI, MachineInstr &InsertPt, const TargetRegisterClass &RegClass, const MachineOperand &RegMO) { Register Reg = RegMO.getReg(); // Assume physical registers are properly constrained. assert(Register::isVirtualRegister(Reg) && "PhysReg not implemented"); Register ConstrainedReg = constrainRegToClass(MRI, TII, RBI, Reg, RegClass); // If we created a new virtual register because the class is not compatible // then create a copy between the new and the old register. if (ConstrainedReg != Reg) { MachineBasicBlock::iterator InsertIt(&InsertPt); MachineBasicBlock &MBB = *InsertPt.getParent(); if (RegMO.isUse()) { BuildMI(MBB, InsertIt, InsertPt.getDebugLoc(), TII.get(TargetOpcode::COPY), ConstrainedReg) .addReg(Reg); } else { assert(RegMO.isDef() && "Must be a definition"); BuildMI(MBB, std::next(InsertIt), InsertPt.getDebugLoc(), TII.get(TargetOpcode::COPY), Reg) .addReg(ConstrainedReg); } } else { if (GISelChangeObserver *Observer = MF.getObserver()) { if (!RegMO.isDef()) { MachineInstr *RegDef = MRI.getVRegDef(Reg); Observer->changedInstr(*RegDef); } Observer->changingAllUsesOfReg(MRI, Reg); Observer->finishedChangingAllUsesOfReg(); } } return ConstrainedReg; } Register llvm::constrainOperandRegClass( const MachineFunction &MF, const TargetRegisterInfo &TRI, MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const RegisterBankInfo &RBI, MachineInstr &InsertPt, const MCInstrDesc &II, const MachineOperand &RegMO, unsigned OpIdx) { Register Reg = RegMO.getReg(); // Assume physical registers are properly constrained. assert(Register::isVirtualRegister(Reg) && "PhysReg not implemented"); const TargetRegisterClass *RegClass = TII.getRegClass(II, OpIdx, &TRI, MF); // Some of the target independent instructions, like COPY, may not impose any // register class constraints on some of their operands: If it's a use, we can // skip constraining as the instruction defining the register would constrain // it. // We can't constrain unallocatable register classes, because we can't create // virtual registers for these classes, so we need to let targets handled this // case. if (RegClass && !RegClass->isAllocatable()) RegClass = TRI.getConstrainedRegClassForOperand(RegMO, MRI); if (!RegClass) { assert((!isTargetSpecificOpcode(II.getOpcode()) || RegMO.isUse()) && "Register class constraint is required unless either the " "instruction is target independent or the operand is a use"); // FIXME: Just bailing out like this here could be not enough, unless we // expect the users of this function to do the right thing for PHIs and // COPY: // v1 = COPY v0 // v2 = COPY v1 // v1 here may end up not being constrained at all. Please notice that to // reproduce the issue we likely need a destination pattern of a selection // rule producing such extra copies, not just an input GMIR with them as // every existing target using selectImpl handles copies before calling it // and they never reach this function. return Reg; } return constrainOperandRegClass(MF, TRI, MRI, TII, RBI, InsertPt, *RegClass, RegMO); } bool llvm::constrainSelectedInstRegOperands(MachineInstr &I, const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI) { assert(!isPreISelGenericOpcode(I.getOpcode()) && "A selected instruction is expected"); MachineBasicBlock &MBB = *I.getParent(); MachineFunction &MF = *MBB.getParent(); MachineRegisterInfo &MRI = MF.getRegInfo(); for (unsigned OpI = 0, OpE = I.getNumExplicitOperands(); OpI != OpE; ++OpI) { MachineOperand &MO = I.getOperand(OpI); // There's nothing to be done on non-register operands. if (!MO.isReg()) continue; LLVM_DEBUG(dbgs() << "Converting operand: " << MO << '\n'); assert(MO.isReg() && "Unsupported non-reg operand"); Register Reg = MO.getReg(); // Physical registers don't need to be constrained. if (Register::isPhysicalRegister(Reg)) continue; // Register operands with a value of 0 (e.g. predicate operands) don't need // to be constrained. if (Reg == 0) continue; // If the operand is a vreg, we should constrain its regclass, and only // insert COPYs if that's impossible. // constrainOperandRegClass does that for us. MO.setReg(constrainOperandRegClass(MF, TRI, MRI, TII, RBI, I, I.getDesc(), MO, OpI)); // Tie uses to defs as indicated in MCInstrDesc if this hasn't already been // done. if (MO.isUse()) { int DefIdx = I.getDesc().getOperandConstraint(OpI, MCOI::TIED_TO); if (DefIdx != -1 && !I.isRegTiedToUseOperand(DefIdx)) I.tieOperands(DefIdx, OpI); } } return true; } bool llvm::canReplaceReg(Register DstReg, Register SrcReg, MachineRegisterInfo &MRI) { // Give up if either DstReg or SrcReg is a physical register. if (DstReg.isPhysical() || SrcReg.isPhysical()) return false; // Give up if the types don't match. if (MRI.getType(DstReg) != MRI.getType(SrcReg)) return false; // Replace if either DstReg has no constraints or the register // constraints match. return !MRI.getRegClassOrRegBank(DstReg) || MRI.getRegClassOrRegBank(DstReg) == MRI.getRegClassOrRegBank(SrcReg); } bool llvm::isTriviallyDead(const MachineInstr &MI, const MachineRegisterInfo &MRI) { // If we can move an instruction, we can remove it. Otherwise, it has // a side-effect of some sort. bool SawStore = false; if (!MI.isSafeToMove(/*AA=*/nullptr, SawStore) && !MI.isPHI()) return false; // Instructions without side-effects are dead iff they only define dead vregs. for (auto &MO : MI.operands()) { if (!MO.isReg() || !MO.isDef()) continue; Register Reg = MO.getReg(); if (Register::isPhysicalRegister(Reg) || !MRI.use_nodbg_empty(Reg)) return false; } return true; } static void reportGISelDiagnostic(DiagnosticSeverity Severity, MachineFunction &MF, const TargetPassConfig &TPC, MachineOptimizationRemarkEmitter &MORE, MachineOptimizationRemarkMissed &R) { bool IsFatal = Severity == DS_Error && TPC.isGlobalISelAbortEnabled(); // Print the function name explicitly if we don't have a debug location (which // makes the diagnostic less useful) or if we're going to emit a raw error. if (!R.getLocation().isValid() || IsFatal) R << (" (in function: " + MF.getName() + ")").str(); if (IsFatal) report_fatal_error(R.getMsg()); else MORE.emit(R); } void llvm::reportGISelWarning(MachineFunction &MF, const TargetPassConfig &TPC, MachineOptimizationRemarkEmitter &MORE, MachineOptimizationRemarkMissed &R) { reportGISelDiagnostic(DS_Warning, MF, TPC, MORE, R); } void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC, MachineOptimizationRemarkEmitter &MORE, MachineOptimizationRemarkMissed &R) { MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); reportGISelDiagnostic(DS_Error, MF, TPC, MORE, R); } void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC, MachineOptimizationRemarkEmitter &MORE, const char *PassName, StringRef Msg, const MachineInstr &MI) { MachineOptimizationRemarkMissed R(PassName, "GISelFailure: ", MI.getDebugLoc(), MI.getParent()); R << Msg; // Printing MI is expensive; only do it if expensive remarks are enabled. if (TPC.isGlobalISelAbortEnabled() || MORE.allowExtraAnalysis(PassName)) R << ": " << ore::MNV("Inst", MI); reportGISelFailure(MF, TPC, MORE, R); } Optional<int64_t> llvm::getConstantVRegVal(Register VReg, const MachineRegisterInfo &MRI) { Optional<ValueAndVReg> ValAndVReg = getConstantVRegValWithLookThrough(VReg, MRI, /*LookThroughInstrs*/ false); assert((!ValAndVReg || ValAndVReg->VReg == VReg) && "Value found while looking through instrs"); if (!ValAndVReg) return None; return ValAndVReg->Value; } Optional<ValueAndVReg> llvm::getConstantVRegValWithLookThrough( Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs, bool HandleFConstant) { SmallVector<std::pair<unsigned, unsigned>, 4> SeenOpcodes; MachineInstr *MI; auto IsConstantOpcode = [HandleFConstant](unsigned Opcode) { return Opcode == TargetOpcode::G_CONSTANT || (HandleFConstant && Opcode == TargetOpcode::G_FCONSTANT); }; auto GetImmediateValue = [HandleFConstant, &MRI](const MachineInstr &MI) -> Optional<APInt> { const MachineOperand &CstVal = MI.getOperand(1); if (!CstVal.isImm() && !CstVal.isCImm() && (!HandleFConstant || !CstVal.isFPImm())) return None; if (!CstVal.isFPImm()) { unsigned BitWidth = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits(); APInt Val = CstVal.isImm() ? APInt(BitWidth, CstVal.getImm()) : CstVal.getCImm()->getValue(); assert(Val.getBitWidth() == BitWidth && "Value bitwidth doesn't match definition type"); return Val; } return CstVal.getFPImm()->getValueAPF().bitcastToAPInt(); }; while ((MI = MRI.getVRegDef(VReg)) && !IsConstantOpcode(MI->getOpcode()) && LookThroughInstrs) { switch (MI->getOpcode()) { case TargetOpcode::G_TRUNC: case TargetOpcode::G_SEXT: case TargetOpcode::G_ZEXT: SeenOpcodes.push_back(std::make_pair( MI->getOpcode(), MRI.getType(MI->getOperand(0).getReg()).getSizeInBits())); VReg = MI->getOperand(1).getReg(); break; case TargetOpcode::COPY: VReg = MI->getOperand(1).getReg(); if (Register::isPhysicalRegister(VReg)) return None; break; case TargetOpcode::G_INTTOPTR: VReg = MI->getOperand(1).getReg(); break; default: return None; } } if (!MI || !IsConstantOpcode(MI->getOpcode())) return None; Optional<APInt> MaybeVal = GetImmediateValue(*MI); if (!MaybeVal) return None; APInt &Val = *MaybeVal; while (!SeenOpcodes.empty()) { std::pair<unsigned, unsigned> OpcodeAndSize = SeenOpcodes.pop_back_val(); switch (OpcodeAndSize.first) { case TargetOpcode::G_TRUNC: Val = Val.trunc(OpcodeAndSize.second); break; case TargetOpcode::G_SEXT: Val = Val.sext(OpcodeAndSize.second); break; case TargetOpcode::G_ZEXT: Val = Val.zext(OpcodeAndSize.second); break; } } if (Val.getBitWidth() > 64) return None; return ValueAndVReg{Val.getSExtValue(), VReg}; } const llvm::ConstantFP * llvm::getConstantFPVRegVal(Register VReg, const MachineRegisterInfo &MRI) { MachineInstr *MI = MRI.getVRegDef(VReg); if (TargetOpcode::G_FCONSTANT != MI->getOpcode()) return nullptr; return MI->getOperand(1).getFPImm(); } namespace { struct DefinitionAndSourceRegister { llvm::MachineInstr *MI; Register Reg; }; } // namespace static llvm::Optional<DefinitionAndSourceRegister> getDefSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI) { Register DefSrcReg = Reg; auto *DefMI = MRI.getVRegDef(Reg); auto DstTy = MRI.getType(DefMI->getOperand(0).getReg()); if (!DstTy.isValid()) return None; while (DefMI->getOpcode() == TargetOpcode::COPY) { Register SrcReg = DefMI->getOperand(1).getReg(); auto SrcTy = MRI.getType(SrcReg); if (!SrcTy.isValid() || SrcTy != DstTy) break; DefMI = MRI.getVRegDef(SrcReg); DefSrcReg = SrcReg; } return DefinitionAndSourceRegister{DefMI, DefSrcReg}; } llvm::MachineInstr *llvm::getDefIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI) { Optional<DefinitionAndSourceRegister> DefSrcReg = getDefSrcRegIgnoringCopies(Reg, MRI); return DefSrcReg ? DefSrcReg->MI : nullptr; } Register llvm::getSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI) { Optional<DefinitionAndSourceRegister> DefSrcReg = getDefSrcRegIgnoringCopies(Reg, MRI); return DefSrcReg ? DefSrcReg->Reg : Register(); } llvm::MachineInstr *llvm::getOpcodeDef(unsigned Opcode, Register Reg, const MachineRegisterInfo &MRI) { MachineInstr *DefMI = getDefIgnoringCopies(Reg, MRI); return DefMI && DefMI->getOpcode() == Opcode ? DefMI : nullptr; } APFloat llvm::getAPFloatFromSize(double Val, unsigned Size) { if (Size == 32) return APFloat(float(Val)); if (Size == 64) return APFloat(Val); if (Size != 16) llvm_unreachable("Unsupported FPConstant size"); bool Ignored; APFloat APF(Val); APF.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &Ignored); return APF; } Optional<APInt> llvm::ConstantFoldBinOp(unsigned Opcode, const unsigned Op1, const unsigned Op2, const MachineRegisterInfo &MRI) { auto MaybeOp1Cst = getConstantVRegVal(Op1, MRI); auto MaybeOp2Cst = getConstantVRegVal(Op2, MRI); if (MaybeOp1Cst && MaybeOp2Cst) { LLT Ty = MRI.getType(Op1); APInt C1(Ty.getSizeInBits(), *MaybeOp1Cst, true); APInt C2(Ty.getSizeInBits(), *MaybeOp2Cst, true); switch (Opcode) { default: break; case TargetOpcode::G_ADD: return C1 + C2; case TargetOpcode::G_AND: return C1 & C2; case TargetOpcode::G_ASHR: return C1.ashr(C2); case TargetOpcode::G_LSHR: return C1.lshr(C2); case TargetOpcode::G_MUL: return C1 * C2; case TargetOpcode::G_OR: return C1 | C2; case TargetOpcode::G_SHL: return C1 << C2; case TargetOpcode::G_SUB: return C1 - C2; case TargetOpcode::G_XOR: return C1 ^ C2; case TargetOpcode::G_UDIV: if (!C2.getBoolValue()) break; return C1.udiv(C2); case TargetOpcode::G_SDIV: if (!C2.getBoolValue()) break; return C1.sdiv(C2); case TargetOpcode::G_UREM: if (!C2.getBoolValue()) break; return C1.urem(C2); case TargetOpcode::G_SREM: if (!C2.getBoolValue()) break; return C1.srem(C2); } } return None; } bool llvm::isKnownNeverNaN(Register Val, const MachineRegisterInfo &MRI, bool SNaN) { const MachineInstr *DefMI = MRI.getVRegDef(Val); if (!DefMI) return false; if (DefMI->getFlag(MachineInstr::FmNoNans)) return true; if (SNaN) { // FP operations quiet. For now, just handle the ones inserted during // legalization. switch (DefMI->getOpcode()) { case TargetOpcode::G_FPEXT: case TargetOpcode::G_FPTRUNC: case TargetOpcode::G_FCANONICALIZE: return true; default: return false; } } return false; } Align llvm::inferAlignFromPtrInfo(MachineFunction &MF, const MachinePointerInfo &MPO) { auto PSV = MPO.V.dyn_cast<const PseudoSourceValue *>(); if (auto FSPV = dyn_cast_or_null<FixedStackPseudoSourceValue>(PSV)) { MachineFrameInfo &MFI = MF.getFrameInfo(); return commonAlignment(MFI.getObjectAlign(FSPV->getFrameIndex()), MPO.Offset); } return Align(1); } Optional<APInt> llvm::ConstantFoldExtOp(unsigned Opcode, const unsigned Op1, uint64_t Imm, const MachineRegisterInfo &MRI) { auto MaybeOp1Cst = getConstantVRegVal(Op1, MRI); if (MaybeOp1Cst) { LLT Ty = MRI.getType(Op1); APInt C1(Ty.getSizeInBits(), *MaybeOp1Cst, true); switch (Opcode) { default: break; case TargetOpcode::G_SEXT_INREG: return C1.trunc(Imm).sext(C1.getBitWidth()); } } return None; } void llvm::getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU) { AU.addPreserved<StackProtector>(); } LLT llvm::getLCMType(LLT Ty0, LLT Ty1) { if (!Ty0.isVector() && !Ty1.isVector()) { unsigned Mul = Ty0.getSizeInBits() * Ty1.getSizeInBits(); int GCDSize = greatestCommonDivisor(Ty0.getSizeInBits(), Ty1.getSizeInBits()); return LLT::scalar(Mul / GCDSize); } if (Ty0.isVector() && !Ty1.isVector()) { assert(Ty0.getElementType() == Ty1 && "not yet handled"); return Ty0; } if (Ty1.isVector() && !Ty0.isVector()) { assert(Ty1.getElementType() == Ty0 && "not yet handled"); return Ty1; } if (Ty0.isVector() && Ty1.isVector()) { assert(Ty0.getElementType() == Ty1.getElementType() && "not yet handled"); int GCDElts = greatestCommonDivisor(Ty0.getNumElements(), Ty1.getNumElements()); int Mul = Ty0.getNumElements() * Ty1.getNumElements(); return LLT::vector(Mul / GCDElts, Ty0.getElementType()); } llvm_unreachable("not yet handled"); } LLT llvm::getGCDType(LLT OrigTy, LLT TargetTy) { if (OrigTy.isVector() && TargetTy.isVector()) { assert(OrigTy.getElementType() == TargetTy.getElementType()); int GCD = greatestCommonDivisor(OrigTy.getNumElements(), TargetTy.getNumElements()); return LLT::scalarOrVector(GCD, OrigTy.getElementType()); } if (OrigTy.isVector() && !TargetTy.isVector()) { assert(OrigTy.getElementType() == TargetTy); return TargetTy; } assert(!OrigTy.isVector() && !TargetTy.isVector() && "GCD type of vector and scalar not implemented"); int GCD = greatestCommonDivisor(OrigTy.getSizeInBits(), TargetTy.getSizeInBits()); return LLT::scalar(GCD); }
{ "content_hash": "8da91e44de5f6dcd40e4abf87d151a03", "timestamp": "", "source": "github", "line_count": 558, "max_line_length": 80, "avg_line_length": 36.16487455197132, "alnum_prop": 0.63800792864222, "repo_name": "endlessm/chromium-browser", "id": "475d5e583040a186e353f58e44cc5393fd9f031b", "size": "20180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/llvm/llvm/lib/CodeGen/GlobalISel/Utils.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
import gql from "graphql-tag"; import BillingModifierFragment from 'lib/fragment/BillingModifier'; export default gql` mutation addBillingModifier( $input: AddBillingModifierInput!) { addBillingModifier(input: $input){ ...billingModifierFields } } ${BillingModifierFragment} `;
{ "content_hash": "eb527473c07933e8302423cdbeca4d98", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 67, "avg_line_length": 27.09090909090909, "alnum_prop": 0.7516778523489933, "repo_name": "amazeeio/lagoon", "id": "ac784ad8b6fce25a192cee9f816d4348cba70e1c", "size": "298", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "services/ui/src/lib/mutation/AddBillingModifier.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "327" }, { "name": "Dockerfile", "bytes": "91473" }, { "name": "HTML", "bytes": "3270" }, { "name": "JavaScript", "bytes": "917507" }, { "name": "Makefile", "bytes": "41263" }, { "name": "PHP", "bytes": "148874" }, { "name": "PLSQL", "bytes": "148" }, { "name": "Python", "bytes": "777" }, { "name": "Roff", "bytes": "3321" }, { "name": "SQLPL", "bytes": "33383" }, { "name": "Shell", "bytes": "336135" }, { "name": "Smarty", "bytes": "590" }, { "name": "TSQL", "bytes": "13766" }, { "name": "TypeScript", "bytes": "196542" }, { "name": "VCL", "bytes": "16240" } ], "symlink_target": "" }
using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Media.Models { public partial class MediaServicesNameAvailabilityContent : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsDefined(Name)) { writer.WritePropertyName("name"); writer.WriteStringValue(Name); } if (Optional.IsDefined(ResourceType)) { writer.WritePropertyName("type"); writer.WriteStringValue(ResourceType); } writer.WriteEndObject(); } } }
{ "content_hash": "46ffe2e266d776ffca087ac97a855ba8", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 85, "avg_line_length": 29.166666666666668, "alnum_prop": 0.5828571428571429, "repo_name": "Azure/azure-sdk-for-net", "id": "1fec1de8106f55606afdeaa4e52ed9e13046a78c", "size": "838", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/mediaservices/Azure.ResourceManager.Media/src/Generated/Models/MediaServicesNameAvailabilityContent.Serialization.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>pygraph.algorithms.filters.radius.radius</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="pygraph-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" ><a class="navbar" target="_top" href="http://code.google.com/p/python-graph/">python-graph</a></th> </tr></table></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="pygraph-module.html">Package&nbsp;pygraph</a> :: <a href="pygraph.algorithms-module.html">Package&nbsp;algorithms</a> :: <a href="pygraph.algorithms.filters-module.html">Package&nbsp;filters</a> :: <a href="pygraph.algorithms.filters.radius-module.html">Module&nbsp;radius</a> :: Class&nbsp;radius </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> </table> </td> </tr> </table> <!-- ==================== CLASS DESCRIPTION ==================== --> <h1 class="epydoc">Class radius</h1><p class="nomargin-top"></p> <center> <center> <map id="class_hierarchy_for_radius" name="class_hierarchy_for_radius"> <area shape="rect" id="node1" href="pygraph.algorithms.filters.radius.radius-class.html" title="radius" alt="" coords="5,5,67,32"/> </map> <img src="class_hierarchy_for_radius.gif" alt='' usemap="#class_hierarchy_for_radius" ismap="ismap" class="graph-without-title" /> </center> </center> <hr /> <p>Radial search filter.</p> <p>This will keep searching contained inside a specified limit.</p> <!-- ==================== INSTANCE METHODS ==================== --> <a name="section-InstanceMethods"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td align="left" colspan="2" class="table-header"> <span class="table-header">Instance Methods</span></td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="pygraph.algorithms.filters.radius.radius-class.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">radius</span>)</span><br /> Initialize the filter.</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="pygraph.algorithms.filters.radius.radius-class.html#configure" class="summary-sig-name">configure</a>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">graph</span>, <span class="summary-sig-arg">spanning_tree</span>)</span><br /> Configure the filter.</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">boolean</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="pygraph.algorithms.filters.radius.radius-class.html#__call__" class="summary-sig-name">__call__</a>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">node</span>, <span class="summary-sig-arg">parent</span>)</span><br /> Decide if the given node should be included in the search process.</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>: <code>__delattr__</code>, <code>__format__</code>, <code>__getattribute__</code>, <code>__hash__</code>, <code>__new__</code>, <code>__reduce__</code>, <code>__reduce_ex__</code>, <code>__repr__</code>, <code>__setattr__</code>, <code>__sizeof__</code>, <code>__str__</code>, <code>__subclasshook__</code> </p> </td> </tr> </table> <!-- ==================== PROPERTIES ==================== --> <a name="section-Properties"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td align="left" colspan="2" class="table-header"> <span class="table-header">Properties</span></td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>: <code>__class__</code> </p> </td> </tr> </table> <!-- ==================== METHOD DETAILS ==================== --> <a name="section-MethodDetails"></a> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td align="left" colspan="2" class="table-header"> <span class="table-header">Method Details</span></td> </tr> </table> <a name="__init__"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>, <span class="sig-arg">radius</span>)</span> <br /><em class="fname">(Constructor)</em> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>Initialize the filter.</p> <dl class="fields"> <dt>Parameters:</dt> <dd><ul class="nomargin-top"> <li><strong class="pname"><code>radius</code></strong> (number) - Search radius.</li> </ul></dd> <dt>Overrides: object.__init__ </dt> </dl> </td></tr></table> </div> <a name="configure"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">configure</span>(<span class="sig-arg">self</span>, <span class="sig-arg">graph</span>, <span class="sig-arg">spanning_tree</span>)</span> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>Configure the filter.</p> <dl class="fields"> <dt>Parameters:</dt> <dd><ul class="nomargin-top"> <li><strong class="pname"><code>graph</code></strong> (graph) - Graph.</li> <li><strong class="pname"><code>spanning_tree</code></strong> (dictionary) - Spanning tree.</li> </ul></dd> </dl> </td></tr></table> </div> <a name="__call__"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">__call__</span>(<span class="sig-arg">self</span>, <span class="sig-arg">node</span>, <span class="sig-arg">parent</span>)</span> <br /><em class="fname">(Call operator)</em> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>Decide if the given node should be included in the search process.</p> <dl class="fields"> <dt>Parameters:</dt> <dd><ul class="nomargin-top"> <li><strong class="pname"><code>node</code></strong> (node) - Given node.</li> <li><strong class="pname"><code>parent</code></strong> (node) - Given node's parent in the spanning tree.</li> </ul></dd> <dt>Returns: boolean</dt> <dd>Whether the given node should be included in the search process.</dd> </dl> </td></tr></table> </div> <br /> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="pygraph-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" ><a class="navbar" target="_top" href="http://code.google.com/p/python-graph/">python-graph</a></th> </tr></table></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Sat Aug 25 09:56:12 2012 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
{ "content_hash": "e97060230106620da2745353edbfe675", "timestamp": "", "source": "github", "line_count": 314, "max_line_length": 193, "avg_line_length": 35.82484076433121, "alnum_prop": 0.5725842297093074, "repo_name": "wdv4758h/ZipPy", "id": "b98a1f3ba5949b05c25d3658b412aaaf5a1cb6ba", "size": "11249", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "edu.uci.python.benchmark/src/benchmarks/python-graph/docs/pygraph.algorithms.filters.radius.radius-class.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "9447" }, { "name": "C", "bytes": "106932" }, { "name": "CSS", "bytes": "32004" }, { "name": "Groff", "bytes": "27753" }, { "name": "HTML", "bytes": "721863" }, { "name": "Java", "bytes": "1550721" }, { "name": "JavaScript", "bytes": "10581" }, { "name": "Makefile", "bytes": "16156" }, { "name": "PLSQL", "bytes": "22886" }, { "name": "Python", "bytes": "33672733" }, { "name": "R", "bytes": "1959" }, { "name": "Ruby", "bytes": "304" }, { "name": "Scheme", "bytes": "125" }, { "name": "Shell", "bytes": "3119" }, { "name": "Tcl", "bytes": "1048" }, { "name": "TeX", "bytes": "8790" }, { "name": "Visual Basic", "bytes": "481" }, { "name": "XSLT", "bytes": "366202" } ], "symlink_target": "" }
package org.shipengine.hijacker; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandler; import io.netty.handler.codec.ByteToMessageDecoder; /** * Created by kevin on 5/9/17. * @brief IHijacker is used to hijack a protocol data */ public interface IHijacker { // if return is not null, the handler will be added to pipeline at the first ByteToMessageDecoder getRequestDecoder(); // if return is not null, the handler will be added to pipeline at the first ChannelOutboundHandler getRequestEncoder(); // if return is not null, the handler will be added to pipeline at the first ByteToMessageDecoder getResponseDecoder(); // if return is not null, the handler will be added to pipeline at the first ChannelOutboundHandler getResponseEncoder(); // called while data or message is read from client Object onRequest(ChannelHandlerContext ctx, Object msg) throws Exception; // called while data or message is read from server Object onResponse(ChannelHandlerContext ctx, Object msg) throws Exception; }
{ "content_hash": "8e3d8831ee3cb137dd5b1d31c2a26f63", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 80, "avg_line_length": 37.724137931034484, "alnum_prop": 0.7623400365630713, "repo_name": "kuun/dataship", "id": "603c61997295dd2e274465c8d65cddcc7774d3ac", "size": "1094", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "shipengine/src/main/java/org/shipengine/hijacker/IHijacker.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "60388" }, { "name": "Makefile", "bytes": "64" } ], "symlink_target": "" }
pragma aux.synchronous;
{ "content_hash": "ab93c291fa5a2e5a9540ae17bab76075", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 23, "avg_line_length": 23, "alnum_prop": 0.8695652173913043, "repo_name": "bkiers/sqlite-parser", "id": "6a9e54890208b252d5d3a8f3ce714afca4d29a09", "size": "93", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/resources/pragma.test_21.sql", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "20112" }, { "name": "Java", "bytes": "6273" }, { "name": "PLpgSQL", "bytes": "324108" } ], "symlink_target": "" }
package ru.apermyakov.repository;
{ "content_hash": "d62df4d8d0dc2b5c942d9556be889641", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 33, "avg_line_length": 33, "alnum_prop": 0.8787878787878788, "repo_name": "AlexanderZf44/APermyakov", "id": "fd2adf251e9a7f213de62754f02bfff4eefd3a5a", "size": "33", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chapter_011/mvc/src/main/java/ru/apermyakov/repository/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "47897" }, { "name": "Java", "bytes": "778164" }, { "name": "XSLT", "bytes": "539" } ], "symlink_target": "" }
package org.conqat.lib.commons.tree; /** * This interface is used by {@link TreeUtils} to create tree structures. We use * this factory-based approach as this allows us to create trees based on model * elements that do not have to implement any specific interfaces. * * @param <T> * the type of nodes this handler handles * @param <K> * the key used by the nodes to identify children * @author deissenb * @author $Author: kinnen $ * @version $Rev: 41751 $ * @ConQAT.Rating GREEN Hash: D0FEC0BC74E53061979D8555C8260115 */ public interface ITreeNodeHandler<T, K> { /** * Get the nodes child identified by the provided key. If the node has no * child with the specified key, one should be created. */ public T getOrCreateChild(T node, K key); /** Create root of node of the tree. */ public T createRoot(); }
{ "content_hash": "140c299983507b534aa7000758d78a13", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 80, "avg_line_length": 31.59259259259259, "alnum_prop": 0.6963657678780774, "repo_name": "vimaier/conqat", "id": "f90bcd15bc6a177775a871ccd08dcab7b7ba976f", "size": "2084", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "org.conqat.engine.core/external/commons-src/org/conqat/lib/commons/tree/ITreeNodeHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ABAP", "bytes": "83459" }, { "name": "Ada", "bytes": "294088" }, { "name": "C", "bytes": "35787" }, { "name": "C#", "bytes": "2180092" }, { "name": "C++", "bytes": "41027" }, { "name": "CSS", "bytes": "1066" }, { "name": "DOT", "bytes": "865" }, { "name": "Java", "bytes": "12354598" }, { "name": "JavaScript", "bytes": "563333" }, { "name": "Matlab", "bytes": "2070" }, { "name": "Perl", "bytes": "1612" }, { "name": "Python", "bytes": "1646" }, { "name": "Scilab", "bytes": "9" }, { "name": "Shell", "bytes": "404" }, { "name": "Visual Basic", "bytes": "183" }, { "name": "XSLT", "bytes": "128360" } ], "symlink_target": "" }
<?php error_reporting(-1); $host = "localhost"; $root = "afewtaps_main"; $password = "0T;00xTsq@g1"; $database = "afewtaps_fewtap"; const ANDROID_GCM_SEND_URL = "https://android.googleapis.com/gcm/send"; const GOOGLE_API_KEY = "AIzaSyDc_DZ6W_aX3ugET3YC7NCmJ1EqYi1U_oU"; $con = mysqli_connect($host, $root, $password); if ( ! $con) { die("Failed to connect:" . mysqli_connect_error()); } $open_db = mysqli_select_db($con, $database); if ( ! $open_db) { die("Cannot connect to database" . mysqli_error()); } date_default_timezone_set('Asia/Kolkata'); $start_time = mktime (0, 0, 0, date('m'), date('d'), date('Y')); $end_time = mktime (23, 59, 59, date('m'), date('d'), date('Y')); $time = time(); $sql_query = "SELECT `order_id`, `customer_id`, `establishment_id`, `staff_member_id`, `order_time` FROM `ft_order` WHERE `status` = '1' AND `order_time` >= $start_time AND `order_time` <= $end_time AND `threshold_notification` = 0 AND `staff_member_id` != 0"; $result = mysqli_query($con, $sql_query) or die(mysqli_error($con)); if (mysqli_num_rows($result) > 0) { while ($info = mysqli_fetch_object($result)) { $seconds = $time - ($info->order_time); $minutes = floor($seconds / 60); // min $threshold_query = "SELECT `value` FROM `ft_threshold` WHERE `eid` = $info->establishment_id"; $threshold_result = mysqli_query($con, $threshold_query) or die(mysqli_error($con)); if (mysqli_num_rows($threshold_result) > 0) { $threshold_data = mysqli_fetch_object($threshold_result); $threshold_limit = $threshold_data->value; if ($minutes >= $threshold_limit) { $staff_query = "SELECT `device_token` FROM `ft_staff_member` WHERE `id` = $info->staff_member_id"; $staff_res = mysqli_query($con, $staff_query) or die(mysqli_error($con)); $staff_obj = mysqli_fetch_object($staff_res); $staff_token = $staff_obj->device_token; //$amsg = "Order #$info->order_id is still pending for delivery. Its been more than $minutes minutes.Please keep it under priority&orderid=$info->order_id"; $server_msg = "Order #$info->order_id has exceeded restaurant Threshold limit.&orderid=$info->order_id"; $update_query = "UPDATE `ft_order` SET `status` = '5', `threshold_notification` = 1 WHERE `order_id` = $info->order_id"; mysqli_query($con, $update_query) or die(mysqli_error($con)); if ( ! empty($staff_token)) sendNotification($staff_token, $server_msg); $customer_query = "SELECT `device_token` FROM `ft_accounts` WHERE `id` = $info->customer_id"; $customer_res = mysqli_query($con, $customer_query) or die(mysqli_error($con)); $customer_data = mysqli_fetch_object($customer_res); $device_token = $customer_data->device_token; if ( ! empty($device_token)) { $message = "The Service Staff has already been notified and your order #$info->order_id is under priority"; send_notification_ios(array($device_token), array('message' => $message)); $insert_query = "INSERT INTO `ft_order_notification` SET `notification` = '".$message."', `order_id` = $info->order_id, `flag` = 0, `notify_status` = 4, `ttime` = ".time().""; mysqli_query($con, $insert_query) or die(mysqli_error($con)); } } } } } function send_notification_ios($requestIds = array(), $message = array()) { $registration_ids = array_values($requestIds); // Put y$our private key's passphrase here: $passphrase = 'Certificates'; // Put your alert message here: $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', $_SERVER['DOCUMENT_ROOT'].'/fewtaps/files/notification/ck.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); // Open a connection to the APNS server $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); if ($fp) { foreach ($registration_ids as $registration_id) { // Create the payload body if (isset($message['orderid'])) $mainNoti = array('alert' => $message['message'], 'title' => '', 'badge' => '', 'type' => '', 'sound' => 'default', 'orderid' => $message['orderid']); else $mainNoti = array('alert' => $message['message'], 'title' => '', 'badge' => '', 'type' => '', 'sound' => 'default'); //$mainNoti = array_merge($mainNoti,$message); $body['aps'] = $mainNoti; // Encode the payload as JSON $payload = json_encode($body); //echo "<pre>";print_r($payload); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', trim($registration_id)) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); } // Close the connection to the server fclose($fp); } } function sendNotification($reg_id = '', $message = '') { $registatoin_ids = array($reg_id); $message = array('message' => $message, 'title' => 'Fewtaps', 'vibrate' => 1, 'sound' => 1); // Set POST variables $url = ANDROID_GCM_SEND_URL; $fields = array( 'registration_ids' => $registatoin_ids, 'data' => $message, ); $headers = array( 'Authorization: key=' . GOOGLE_API_KEY, 'Content-Type: application/json' ); // Open connection // $ch = curl_init(); // Set the url, number of POST vars, POST data curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Disabling SSL Certificate support temporarly curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); // Execute post $result = curl_exec($ch); // Close connection curl_close($ch); }
{ "content_hash": "4f139dadf33c858a1517c6ced31649d8", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 267, "avg_line_length": 38.5406976744186, "alnum_prop": 0.5534771458741892, "repo_name": "Ekta3012/codeigniter_afewtaps", "id": "bded56a3922f0dd2fdb87bda0cab6a4976d325a9", "size": "6629", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "threshold_notification.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "600" }, { "name": "CSS", "bytes": "1136444" }, { "name": "HTML", "bytes": "9060411" }, { "name": "JavaScript", "bytes": "1915359" }, { "name": "PHP", "bytes": "12828337" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>mathcomp-finmap: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.11.1 / mathcomp-finmap - 1.3.1</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> mathcomp-finmap <small> 1.3.1 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-09-07 08:18:39 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-09-07 08:18:39 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.11.1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Cyril Cohen &lt;cyril.cohen@inria.fr&gt;&quot; homepage: &quot;https://github.com/math-comp/finmap&quot; bug-reports: &quot;https://github.com/math-comp/finmap/issues&quot; dev-repo: &quot;git+https://github.com/math-comp/finmap.git&quot; license: &quot;CeCILL-B&quot; build: [ make &quot;-j&quot; &quot;%{jobs}%&quot; ] install: [ make &quot;install&quot; ] depends: [ &quot;coq&quot; { (&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.11~&quot;) } &quot;coq-mathcomp-ssreflect&quot; { (&gt;= &quot;1.8.0&quot; &amp; &lt; &quot;1.10~&quot;) } &quot;coq-mathcomp-bigenough&quot; { (&gt;= &quot;1.0.0&quot; &amp; &lt; &quot;1.1~&quot;) } ] tags: [ &quot;keyword:finmap&quot; &quot;keyword:finset&quot; &quot;keyword:multiset&quot; &quot;keyword:order&quot; &quot;date:2019-06-13&quot; &quot;logpath:mathcomp.finmap&quot;] authors: [ &quot;Cyril Cohen &lt;cyril.cohen@inria.fr&gt;&quot; &quot;Kazuhiko Sakaguchi &lt;sakaguchi@coins.tsukuba.ac.jp&gt;&quot; ] synopsis: &quot;Finite sets, finite maps, finitely supported functions, orders&quot; description: &quot;&quot;&quot; This library is an extension of mathematical component in order to support finite sets and finite maps on choicetypes (rather that finite types). This includes support for functions with finite support and multisets. The library also contains a generic order and set libary, which will be used to subsume notations for finite sets, eventually.&quot;&quot;&quot; url { src: &quot;https://github.com/math-comp/finmap/archive/1.3.1.tar.gz&quot; checksum: &quot;sha256=5b90b4dbb1c851be7a835493ef81471238260580e2d1b340dc4cf40668c6a15b&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-mathcomp-finmap.1.3.1 coq.8.11.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.1). The following dependencies couldn&#39;t be met: - coq-mathcomp-finmap -&gt; coq &lt; 8.11~ -&gt; ocaml &lt; 4.03.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-finmap.1.3.1</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "574f94cd79d792080210f07f882f5a5e", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 181, "avg_line_length": 44.44642857142857, "alnum_prop": 0.557385830989688, "repo_name": "coq-bench/coq-bench.github.io", "id": "52d5478bcf963363973d6c7ca0b24281b9d32159", "size": "7469", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.6/released/8.11.1/mathcomp-finmap/1.3.1.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="20dp" android:height="20dp" android:viewportWidth="20" android:viewportHeight="20" android:tint="?attr/colorControlNormal"> <path android:fillColor="@android:color/white" android:pathData="M1.167,18.729V1.146H18.833V15.521H4.375Z"/> </vector>
{ "content_hash": "561b3515793a94720881b6aae11ba215", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 67, "avg_line_length": 35.9, "alnum_prop": 0.7075208913649025, "repo_name": "google/material-design-icons", "id": "a84aac84b0d96d54bd8a40248c95b4d05f7e0222", "size": "359", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "symbols/android/chat_bubble/materialsymbolssharp/chat_bubble_wght700gradN25fill1_20px.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>Overview Example</title> <meta charset="utf8"/> <style> html, body { font-family:Arial, Helvetica, sans-serif; margin:0; padding:0; } main{ padding: 0 20px; width: 700px; overflow: hidden; max-width: 100%; margin: 0 auto; box-sizing: border-box; } iframe { border:none; width:100%; height: 400px; margin:10px; } code { line-height: 18px; font-size: 14px; } </style> </head> <body> <main> <h1>cEngine.js</h1> <hr> <p> Welcome! cEngine.js is a small canvas-engine for javascript. This page features examples for the core engine, as well as the plugins included. </p> <hr> <h2>1. Simple canvas drawing</h2> <hr> <p> In this example, we create a new instance of cEngine.js and run one step to draw a square. </p> <hr> <a href="simple.html">Go to the simple canvas drawing example ></a> <hr> <pre><code> var engine = cEngine.create({ step: function (context) { context.fillStyle = 'red' context.fillRect(10, 10, 10, 10) } }).step() </code></pre> <hr> <iframe src="simple.html"></iframe> <hr> <h2>2. Plugin activityTracker</h2> <hr> <p> This example features the activityTracker, which stops the engine when the user loses focus of the window. This plugin will restart the engine when the user focuses on the window. </p> <hr> <a href="plugins/activityTracker.html">Go to the activityTracker example ></a> <hr> <pre><code> var engine = cEngine.create({ plugins: { activityTracker: cEngine.activityTracker.create({ stopOnUserLeave: true }) }, autoClear: true, step: function(context, width, height, dt){ context.fillStyle = 'red' context.fillRect(Math.random()*20, Math.random()*20, 10, 10) } }).start() </code></pre> <hr> <iframe src="plugins/activityTracker.html"></iframe> <hr> <h2>3. Plugin fill</h2> <hr> <a href="plugins/fill.html">Go to fill example ></a> <hr> <pre><code> var engine = cEngine.create({ autoClear: true, height: 512, plugins: { fill: cEngine.fill.create({ mode: 'stretch', aspectRetion: true }) }, step: function(context, width, height){ context.fillStyle = context.fillStyle === 'red' ? 'blue': 'red' context.fillRect(width * Math.random(), height * Math.random(), 10, 10) } }) engine.start() </code></pre> <hr> <iframe src="plugins/fill.html"></iframe> <hr> <h2>Plugin filter</h2> <hr> <a href="plugins/filter.html">Go to filter example ></a> <hr> <p>Code see example page</p> <hr> <iframe src="plugins/filter.html"></iframe> <hr> <h2>Filter-App</h2> <hr> <a href="plugins/filterApp.html">Go to Filter-App ></a> <hr> <iframe src="plugins/filterApp.html"></iframe> <hr> <h2>Plugin frameRate</h2> <hr> <a href="plugins/frameRate.html">Go to frameRate example ></a> <hr> <p>Code see example page</p> <hr> <iframe src="plugins/frameRate.html"></iframe> <hr> <h2>Plugin input</h2> <hr> <a href="plugins/input.html">Go to input example ></a> <hr> <p>Code see example page</p> <hr> <iframe src="plugins/input.html"></iframe> <hr> <h2>Plugin stats</h2> <hr> <a href="plugins/stats.html">Go to stats example ></a> <hr> <pre><code> var obj = { x: 50, y: 50 }; var engine = cEngine.create({ autoClear: true, plugins: { stats: cEngine.stats.create(), filter: cEngine.filter.create({ filters: [{ Shader: cEngine.filter.Shader.greyscale }] }) }, step: function(context){ obj.x += (Math.random() - 0.5) * 10 obj.y += (Math.random() - 0.5) * 10 context.fillStyle = 'red' context.fillRect(obj.x, obj.y, 10, 10) } }).start() </code></pre> <hr> <iframe src="plugins/stats.html"></iframe> <hr> <p> Coded with love by Rene Müller, see more at <a href="https://renmuell.github.io/">https://renmuell.github.io/</a>. </p> </main> </body> </html>
{ "content_hash": "359642f34ffba8a634bc817e1fa0abd6", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 181, "avg_line_length": 21.486187845303867, "alnum_prop": 0.6289534584726151, "repo_name": "renmuell/cEngine", "id": "e8d820000b13c0538af72656af5b32175277c871", "size": "3890", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1560" }, { "name": "JavaScript", "bytes": "39190" } ], "symlink_target": "" }
package com.polydeucesys.eslogging.core; /** * Defines a communication mechanism between the logging framework and * the storage system, whereby documents of type {@code D} can be * submitted and responses of type {@code R} are returned. * @author Kevin McLellan * @version 1.0 * * @param <D> * The type of the documents being submitted * @param <R> * The type of the successful response from the storage */ public interface Connection<D, R> extends LifeCycle{ void setConnectionString(final String connectionString); String getConnectionString(); R submit(final D document) throws LogSubmissionException; void submitAsync( final D document, AsyncSubmitCallback<R> callback); }
{ "content_hash": "2a439942ba647c176c17e766f0b57b33", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 71, "avg_line_length": 35.15, "alnum_prop": 0.7510668563300142, "repo_name": "poldeuce-sys/elasticsearch-logging", "id": "d2973d7158299fd34e5a62e6c007319c1fef153a", "size": "1356", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "elasticsearch-logging-core/src/main/java/com/polydeucesys/eslogging/core/Connection.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "223964" } ], "symlink_target": "" }
namespace MonoGame.PortableUI.Controls { public class TabItem : ContentControl { } }
{ "content_hash": "1d9a89493521370cbfb87e5fb7cd8ef4", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 41, "avg_line_length": 16, "alnum_prop": 0.6979166666666666, "repo_name": "Matt-17/MonoGame.PortableUI", "id": "a9f6938c4fbc88acc087a7362e1a700ca2f9155d", "size": "96", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MonoGame.PortableUI/Controls/TabItem.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "144973" } ], "symlink_target": "" }
{% extends "multiboards/form.html" %} {% block page_title %}Edit multiboard {{multiboard.name}}{% endblock %} {% block content %} <h1>Edit multiboard {{multiboard.name}}</h1> {% include "forms/form.html" %} {% endblock content %}
{ "content_hash": "5604e7469c4a4f80bc1f5aad864dc939", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 71, "avg_line_length": 26.666666666666668, "alnum_prop": 0.6458333333333334, "repo_name": "diegojromerolopez/djanban", "id": "72f1f05d71a5e2686824d587fc10f49d2fe285ef", "size": "240", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/djanban/apps/multiboards/templates/multiboards/edit.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "79709" }, { "name": "HTML", "bytes": "660275" }, { "name": "JavaScript", "bytes": "634320" }, { "name": "Python", "bytes": "993818" }, { "name": "Shell", "bytes": "1732" }, { "name": "TypeScript", "bytes": "71578" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "dbac75a08e8bf4b797a05ed627fd829e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "7276e2fdb0d64d72017256080fb91f7a87fbb01b", "size": "181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Asclepiadaceae/Sarcostemma/Sarcostemma swartzianum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }