text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
@protocol SURBaseControlDelegate <NSObject> @end @interface SURBaseControlViewController : UIViewController @property (strong, nonatomic) XPGWifiDevice *selectedDevice; @property (strong, nonatomic) GIZSDKCommunicateService *serviceForSDK; @property (strong, nonatomic) NSArray *faults; @property (strong, nonatomic) NSArray *alerts; @property (strong, nonatomic) SURProductDataPointModel *productDataModel; - (instancetype)init UNAVAILABLE_ATTRIBUTE; - (void)onDisconnected; @end
{'content_hash': '078ac387a8d91e1540ed1814c7b57ab8', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 73, 'avg_line_length': 25.736842105263158, 'alnum_prop': 0.8098159509202454, 'repo_name': 'KoonChaoSo/Main-proccess-model-gizwits', 'id': 'e95807f5d89185607433403be4225f699ff6e181', 'size': '738', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'main-process-ios/ViewController/Control/SURBaseControlViewController.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '699736'}, {'name': 'Ruby', 'bytes': '629'}]}
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flowable.engine.impl.bpmn.behavior; import static org.flowable.common.engine.impl.util.ExceptionUtil.sneakyThrow; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import org.flowable.bpmn.model.MapExceptionEntry; import org.flowable.common.engine.api.FlowableIllegalStateException; import org.flowable.common.engine.api.delegate.Expression; import org.flowable.common.engine.impl.interceptor.CommandContext; import org.flowable.common.engine.impl.logging.LoggingSessionConstants; import org.flowable.engine.delegate.BpmnError; import org.flowable.engine.delegate.DelegateExecution; import org.flowable.engine.delegate.FutureJavaDelegate; import org.flowable.engine.impl.bpmn.helper.ErrorPropagation; import org.flowable.engine.impl.bpmn.helper.SkipExpressionUtil; import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.flowable.engine.impl.delegate.ActivityBehavior; import org.flowable.engine.impl.delegate.TriggerableActivityBehavior; import org.flowable.engine.impl.delegate.invocation.FutureJavaDelegateInvocation; import org.flowable.engine.impl.persistence.entity.ExecutionEntity; import org.flowable.engine.impl.util.BpmnLoggingSessionUtil; import org.flowable.engine.impl.util.CommandContextUtil; /** * @author Filip Hrisafov */ public class ServiceTaskFutureJavaDelegateActivityBehavior extends TaskActivityBehavior implements ActivityBehavior { private static final long serialVersionUID = 1L; protected FutureJavaDelegate<?> futureJavaDelegate; protected Expression skipExpression; protected boolean triggerable; protected List<MapExceptionEntry> mapExceptions; protected ServiceTaskFutureJavaDelegateActivityBehavior() { } public ServiceTaskFutureJavaDelegateActivityBehavior(FutureJavaDelegate<?> futureJavaDelegate, boolean triggerable, Expression skipExpression, List<MapExceptionEntry> mapExceptions) { this.futureJavaDelegate = futureJavaDelegate; this.triggerable = triggerable; this.skipExpression = skipExpression; this.mapExceptions = mapExceptions; } @Override public void trigger(DelegateExecution execution, String signalName, Object signalData) { CommandContext commandContext = CommandContextUtil.getCommandContext(); ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); if (triggerable && futureJavaDelegate instanceof TriggerableActivityBehavior) { if (processEngineConfiguration.isLoggingSessionEnabled()) { BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_BEFORE_TRIGGER, "Triggering service task with java class " + futureJavaDelegate.getClass().getName(), execution); } ((TriggerableActivityBehavior) futureJavaDelegate).trigger(execution, signalName, signalData); if (processEngineConfiguration.isLoggingSessionEnabled()) { BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_AFTER_TRIGGER, "Triggered service task with java class " + futureJavaDelegate.getClass().getName(), execution); } leave(execution); } else { if (processEngineConfiguration.isLoggingSessionEnabled()) { if (!triggerable) { BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_WRONG_TRIGGER, "Service task with java class triggered but not triggerable " + futureJavaDelegate.getClass().getName(), execution); } else { BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_WRONG_TRIGGER, "Service task with java class triggered but not implementing TriggerableActivityBehavior " + futureJavaDelegate.getClass().getName(), execution); } } } } @Override public void execute(DelegateExecution execution) { CommandContext commandContext = CommandContextUtil.getCommandContext(); String skipExpressionText = null; if (skipExpression != null) { skipExpressionText = skipExpression.getExpressionText(); } boolean isSkipExpressionEnabled = SkipExpressionUtil.isSkipExpressionEnabled(skipExpressionText, execution.getCurrentActivityId(), execution, commandContext); ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); boolean loggingSessionEnabled = processEngineConfiguration.isLoggingSessionEnabled(); if (!isSkipExpressionEnabled || !SkipExpressionUtil.shouldSkipFlowElement(skipExpressionText, execution.getCurrentActivityId(), execution, commandContext)) { try { if (loggingSessionEnabled) { BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_ENTER, "Executing service task with java class " + futureJavaDelegate.getClass().getName(), execution); } FutureJavaDelegate<Object> futureJavaDelegate = (FutureJavaDelegate<Object>) this.futureJavaDelegate; FutureJavaDelegateInvocation invocation = new FutureJavaDelegateInvocation(futureJavaDelegate, execution, processEngineConfiguration.getAsyncTaskInvoker()); processEngineConfiguration.getDelegateInterceptor().handleInvocation(invocation); Object invocationResult = invocation.getInvocationResult(); if (invocationResult instanceof CompletableFuture) { CompletableFuture<Object> future = (CompletableFuture<Object>) invocationResult; CommandContextUtil.getAgenda(commandContext).planFutureOperation(future, new FutureJavaDelegateCompleteAction(futureJavaDelegate, execution, loggingSessionEnabled)); } else { throw new FlowableIllegalStateException( "Invocation result " + invocationResult + " from invocation " + invocation + " was not a CompletableFuture"); } } catch (RuntimeException e) { if (loggingSessionEnabled) { BpmnLoggingSessionUtil.addErrorLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_EXCEPTION, "Service task with java class " + futureJavaDelegate.getClass().getName() + " threw exception " + e.getMessage(), e, execution); } throw e; } } else { if (loggingSessionEnabled) { BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SKIP_TASK, "Skipped service task " + execution.getCurrentActivityId() + " with skip expression " + skipExpressionText, execution); } if (!triggerable) { leave(execution); } } } protected void handleException(Throwable throwable, DelegateExecution execution, boolean loggingSessionEnabled) { if (loggingSessionEnabled) { BpmnLoggingSessionUtil.addErrorLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_EXCEPTION, "Service task with java class " + futureJavaDelegate.getClass().getName() + " threw exception " + throwable.getMessage(), throwable, execution); } if (throwable instanceof BpmnError) { ErrorPropagation.propagateError((BpmnError) throwable, execution); } else if (throwable instanceof Exception) { if (!ErrorPropagation.mapException((Exception) throwable, (ExecutionEntity) execution, mapExceptions)) { sneakyThrow(throwable); } } else { sneakyThrow(throwable); } } protected class FutureJavaDelegateCompleteAction implements BiConsumer<Object, Throwable> { protected final FutureJavaDelegate<Object> delegateInstance; protected final DelegateExecution execution; protected final boolean loggingSessionEnabled; public FutureJavaDelegateCompleteAction(FutureJavaDelegate<Object> delegateInstance, DelegateExecution execution, boolean loggingSessionEnabled) { this.delegateInstance = delegateInstance; this.execution = execution; this.loggingSessionEnabled = loggingSessionEnabled; } @Override public void accept(Object value, Throwable throwable) { if (throwable == null) { try { delegateInstance.afterExecution(execution, value); if (loggingSessionEnabled) { BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_EXIT, "Executed service task with java class " + futureJavaDelegate.getClass().getName(), execution); } if (!triggerable) { leave(execution); } } catch (Exception ex) { handleException(ex, execution, loggingSessionEnabled); } } else { handleException(throwable, execution, loggingSessionEnabled); } } } }
{'content_hash': 'c8f4894a3b7f3ea72cfec95f2b8ad82d', 'timestamp': '', 'source': 'github', 'line_count': 203, 'max_line_length': 187, 'avg_line_length': 50.33497536945813, 'alnum_prop': 0.6865335682129575, 'repo_name': 'paulstapleton/flowable-engine', 'id': 'f1d4335edc1c869ef5ab829b8d85929e2a0cdf80', 'size': '10218', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'modules/flowable-engine/src/main/java/org/flowable/engine/impl/bpmn/behavior/ServiceTaskFutureJavaDelegateActivityBehavior.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '166'}, {'name': 'CSS', 'bytes': '688913'}, {'name': 'Dockerfile', 'bytes': '6367'}, {'name': 'Groovy', 'bytes': '482'}, {'name': 'HTML', 'bytes': '1100650'}, {'name': 'Java', 'bytes': '33678803'}, {'name': 'JavaScript', 'bytes': '12395741'}, {'name': 'PLSQL', 'bytes': '109354'}, {'name': 'PLpgSQL', 'bytes': '11691'}, {'name': 'SQLPL', 'bytes': '1265'}, {'name': 'Shell', 'bytes': '19145'}]}
package com.twitter.finagle import com.twitter.io.Buf import com.twitter.util.{Duration, Time, Try} @deprecated("Use `com.twitter.finagle.context.Deadline` instead", "2016-08-22") class Deadline(timestamp: Time, deadline: Time) extends com.twitter.finagle.context.Deadline(timestamp, deadline) @deprecated("Use `com.twitter.finagle.context.Deadline` instead", "2016-08-22") object Deadline { def current: Option[context.Deadline] = context.Deadline.current def ofTimeout(timeout: Duration): context.Deadline = context.Deadline.ofTimeout(timeout) def combined(d1: Deadline, d2: Deadline): context.Deadline = context.Deadline.combined(d1, d2) def marshal(deadline: Deadline): Buf = context.Deadline.marshal(deadline) def tryUnmarshal(body: Buf): Try[context.Deadline] = context.Deadline.tryUnmarshal(body) }
{'content_hash': 'bf2ec931588e31d0084de2f1746fe968', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 96, 'avg_line_length': 37.54545454545455, 'alnum_prop': 0.7711864406779662, 'repo_name': 'BuoyantIO/finagle', 'id': '3d6e2df5f43e889a7d6e752040f76fcec1b9ace1', 'size': '826', 'binary': False, 'copies': '2', 'ref': 'refs/heads/develop', 'path': 'finagle-core/src/main/scala/com/twitter/finagle/Deadline.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '6179'}, {'name': 'Java', 'bytes': '720333'}, {'name': 'Lua', 'bytes': '15245'}, {'name': 'Python', 'bytes': '54359'}, {'name': 'R', 'bytes': '4245'}, {'name': 'Ruby', 'bytes': '25329'}, {'name': 'Scala', 'bytes': '4703587'}, {'name': 'Shell', 'bytes': '12817'}, {'name': 'Thrift', 'bytes': '20553'}]}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>quicksort-complexity: 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 / quicksort-complexity - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> quicksort-complexity <small> 8.6.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;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/quicksort-complexity&quot; license: &quot;BSD&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/QuicksortComplexity&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: quicksort&quot; &quot;keyword: complexity&quot; &quot;keyword: average-case&quot; &quot;category: Computer Science/Decision Procedures and Certified Algorithms/Correctness proofs of algorithms&quot; &quot;date: 2010-06&quot; ] authors: [ &quot;Eelis&quot; ] bug-reports: &quot;https://github.com/coq-contribs/quicksort-complexity/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/quicksort-complexity.git&quot; synopsis: &quot;Proofs of Quicksort&#39;s worst- and average-case complexity&quot; description: &quot;&quot;&quot; The development contains: - a set of monads and monad transformers for measuring a (possibly nondeterministic) algorithm&#39;s use of designated operations; - monadically expressed deterministic and nondeterministic implementations of Quicksort; - proofs of these implementations&#39; worst- and average case complexity. Most of the development is documented in the TYPES 2008 paper &quot;A Machine-Checked Proof of the Average-Case Complexity of Quicksort in Coq&quot;, available at the homepage.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/quicksort-complexity/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=8e941edc995b59591f737b122b66817c&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-quicksort-complexity.8.6.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-quicksort-complexity -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) 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-quicksort-complexity.8.6.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': 'cadb6dd20a18226a4cf1e0645946ac85', 'timestamp': '', 'source': 'github', 'line_count': 170, 'max_line_length': 249, 'avg_line_length': 45.417647058823526, 'alnum_prop': 0.5643051418210077, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': '257b2ecd47632f180fdf542b68eb4053fc39bd14', 'size': '7746', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.07.1-2.0.6/released/8.15.1/quicksort-complexity/8.6.0.html', 'mode': '33188', 'license': 'mit', 'language': []}
SYNONYM #### According to Index Fungorum #### Published in Nat. Arr. Brit. Pl. (London) 1: 452 (1821) #### Original name Verrucaria glaucoma Hoffm. ### Remarks null
{'content_hash': '10a42b3960d1a68c515576280ab7f635', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 42, 'avg_line_length': 12.923076923076923, 'alnum_prop': 0.6785714285714286, 'repo_name': 'mdoering/backbone', 'id': 'a85f6dba189ae404dba7f3265c95e54e4077fb51', 'size': '223', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Lecanoraceae/Lecanora/Lecanora rupicola/ Syn. Rinodina glaucoma/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
CREATE TABLE QRTZ_JOB_DETAILS( SCHED_NAME VARCHAR(120) NOT NULL, JOB_NAME VARCHAR(200) NOT NULL, JOB_GROUP VARCHAR(200) NOT NULL, DESCRIPTION VARCHAR(250) NULL, JOB_CLASS_NAME VARCHAR(250) NOT NULL, IS_DURABLE VARCHAR(1) NOT NULL, IS_NONCONCURRENT VARCHAR(1) NOT NULL, IS_UPDATE_DATA VARCHAR(1) NOT NULL, REQUESTS_RECOVERY VARCHAR(1) NOT NULL, JOB_DATA BLOB NULL, PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)) ENGINE=InnoDB; CREATE TABLE QRTZ_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, JOB_NAME VARCHAR(200) NOT NULL, JOB_GROUP VARCHAR(200) NOT NULL, DESCRIPTION VARCHAR(250) NULL, NEXT_FIRE_TIME BIGINT(13) NULL, PREV_FIRE_TIME BIGINT(13) NULL, PRIORITY INTEGER NULL, TRIGGER_STATE VARCHAR(16) NOT NULL, TRIGGER_TYPE VARCHAR(8) NOT NULL, START_TIME BIGINT(13) NOT NULL, END_TIME BIGINT(13) NULL, CALENDAR_NAME VARCHAR(200) NULL, MISFIRE_INSTR SMALLINT(2) NULL, JOB_DATA BLOB NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP) REFERENCES QRTZ_JOB_DETAILS(SCHED_NAME,JOB_NAME,JOB_GROUP)) ENGINE=InnoDB; CREATE TABLE QRTZ_SIMPLE_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, REPEAT_COUNT BIGINT(7) NOT NULL, REPEAT_INTERVAL BIGINT(12) NOT NULL, TIMES_TRIGGERED BIGINT(10) NOT NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)) ENGINE=InnoDB; CREATE TABLE QRTZ_CRON_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, CRON_EXPRESSION VARCHAR(120) NOT NULL, TIME_ZONE_ID VARCHAR(80), PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)) ENGINE=InnoDB; CREATE TABLE QRTZ_SIMPROP_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, STR_PROP_1 VARCHAR(512) NULL, STR_PROP_2 VARCHAR(512) NULL, STR_PROP_3 VARCHAR(512) NULL, INT_PROP_1 INT NULL, INT_PROP_2 INT NULL, LONG_PROP_1 BIGINT NULL, LONG_PROP_2 BIGINT NULL, DEC_PROP_1 NUMERIC(13,4) NULL, DEC_PROP_2 NUMERIC(13,4) NULL, BOOL_PROP_1 VARCHAR(1) NULL, BOOL_PROP_2 VARCHAR(1) NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)) ENGINE=InnoDB; CREATE TABLE QRTZ_BLOB_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, BLOB_DATA BLOB NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)) ENGINE=InnoDB; CREATE TABLE QRTZ_CALENDARS ( SCHED_NAME VARCHAR(120) NOT NULL, CALENDAR_NAME VARCHAR(200) NOT NULL, CALENDAR BLOB NOT NULL, PRIMARY KEY (SCHED_NAME,CALENDAR_NAME)) ENGINE=InnoDB; CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP)) ENGINE=InnoDB; CREATE TABLE QRTZ_FIRED_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, ENTRY_ID VARCHAR(95) NOT NULL, TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, INSTANCE_NAME VARCHAR(200) NOT NULL, FIRED_TIME BIGINT(13) NOT NULL, SCHED_TIME BIGINT(13) NOT NULL, PRIORITY INTEGER NOT NULL, STATE VARCHAR(16) NOT NULL, JOB_NAME VARCHAR(200) NULL, JOB_GROUP VARCHAR(200) NULL, IS_NONCONCURRENT VARCHAR(1) NULL, REQUESTS_RECOVERY VARCHAR(1) NULL, PRIMARY KEY (SCHED_NAME,ENTRY_ID)) ENGINE=InnoDB; CREATE TABLE QRTZ_SCHEDULER_STATE ( SCHED_NAME VARCHAR(120) NOT NULL, INSTANCE_NAME VARCHAR(200) NOT NULL, LAST_CHECKIN_TIME BIGINT(13) NOT NULL, CHECKIN_INTERVAL BIGINT(13) NOT NULL, PRIMARY KEY (SCHED_NAME,INSTANCE_NAME)) ENGINE=InnoDB; CREATE TABLE QRTZ_LOCKS ( SCHED_NAME VARCHAR(120) NOT NULL, LOCK_NAME VARCHAR(40) NOT NULL, PRIMARY KEY (SCHED_NAME,LOCK_NAME)) ENGINE=InnoDB;
{'content_hash': 'fcdefe6b118f090809a25bc324bf3898', 'timestamp': '', 'source': 'github', 'line_count': 132, 'max_line_length': 64, 'avg_line_length': 31.71212121212121, 'alnum_prop': 0.774964166268514, 'repo_name': 'Fudan-University/sakai', 'id': '663a9ae7e00010be64316dd94851f373028201b5', 'size': '5031', 'binary': False, 'copies': '50', 'ref': 'refs/heads/master', 'path': 'jobscheduler/scheduler-component-shared/src/sql/mysql/quartz2.sql', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '59098'}, {'name': 'Batchfile', 'bytes': '5172'}, {'name': 'CSS', 'bytes': '2088784'}, {'name': 'ColdFusion', 'bytes': '146057'}, {'name': 'HTML', 'bytes': '6271629'}, {'name': 'Java', 'bytes': '47791818'}, {'name': 'JavaScript', 'bytes': '8942829'}, {'name': 'Lasso', 'bytes': '26436'}, {'name': 'PHP', 'bytes': '606568'}, {'name': 'PLSQL', 'bytes': '2328041'}, {'name': 'Perl', 'bytes': '61738'}, {'name': 'Python', 'bytes': '44698'}, {'name': 'Ruby', 'bytes': '1276'}, {'name': 'Shell', 'bytes': '19259'}, {'name': 'SourcePawn', 'bytes': '2247'}, {'name': 'XSLT', 'bytes': '280557'}]}
/* * BackgroundCheck * http://kennethcachia.com/background-check * * v1.2.1 */ (function (root, factory) { if (typeof define === 'function' && define.amd) { define(factory); } else { root.BackgroundCheck = factory(root); } }(this, function () { 'use strict'; var resizeEvent = window.orientation !== undefined ? 'orientationchange' : 'resize'; var supported; var canvas; var context; var throttleDelay; var viewport; var attrs = {}; /* * Initializer */ function init(a) { if (a === undefined || a.targets === undefined) { throw 'Missing attributes'; } // Default values attrs.debug = checkAttr(a.debug, false); attrs.debugOverlay = checkAttr(a.debugOverlay, false); attrs.targets = getElements(a.targets); attrs.images = getElements(a.images || 'img', true); attrs.changeParent = checkAttr(a.changeParent, false); attrs.threshold = checkAttr(a.threshold, 50); attrs.minComplexity = checkAttr(a.minComplexity, 30); attrs.minOverlap = checkAttr(a.minOverlap, 50); attrs.windowEvents = checkAttr(a.windowEvents, true); attrs.maxDuration = checkAttr(a.maxDuration, 500); attrs.mask = checkAttr(a.mask, { r: 0, g: 255, b: 0 }); attrs.classes = checkAttr(a.classes, { dark: 'background--dark', light: 'background--light', complex: 'background--complex' }); if (supported === undefined) { checkSupport(); if (supported) { canvas.style.position = 'fixed'; canvas.style.top = '0px'; canvas.style.left = '0px'; canvas.style.width = '100%'; canvas.style.height = '100%'; window.addEventListener(resizeEvent, throttle.bind(null, function () { resizeCanvas(); check(); })); window.addEventListener('scroll', throttle.bind(null, check)); resizeCanvas(); check(); } } } /* * Destructor */ function destroy() { supported = null; canvas = null; context = null; attrs = {}; if (throttleDelay) { clearTimeout(throttleDelay); } } /* * Output debug logs */ function log(msg) { if (get('debug')) { console.log(msg); } } /* * Get attribute value, use a default * when undefined */ function checkAttr(value, def) { checkType(value, typeof def); return (value === undefined) ? def : value; } /* * Reject unwanted types */ function checkType(value, type) { if (value !== undefined && typeof value !== type) { throw 'Incorrect attribute type'; } } /* * Convert elements with background-image * to Images */ function checkForCSSImages(els) { var el; var url; var list = []; for (var e = 0; e < els.length; e++) { el = els[e]; list.push(el); if (el.tagName !== 'IMG') { url = window.getComputedStyle(el).backgroundImage; // Ignore multiple backgrounds if (url.split(',').length > 1) { throw 'Multiple backgrounds are not supported'; } if (url && url !== 'none') { list[e] = { img: new Image(), el: list[e] }; url = url.slice(4, -1); url = url.replace(/"/g, ''); list[e].img.src = url; log('CSS Image - ' + url); } else { throw 'Element is not an <img> but does not have a background-image'; } } } return list; } /* * Check for String, Element or NodeList */ function getElements(selector, convertToImages) { var els = selector; if (typeof selector === 'string') { els = document.querySelectorAll(selector); } else if (selector && selector.nodeType === 1) { els = [selector]; } if (!els || els.length === 0 || els.length === undefined) { throw 'Elements not found'; } else { if (convertToImages) { els = checkForCSSImages(els); } els = Array.prototype.slice.call(els); } return els; } /* * Check if browser supports <canvas> */ function checkSupport() { canvas = document.createElement('canvas'); if (canvas && canvas.getContext) { context = canvas.getContext('2d'); supported = true; } else { supported = false; } showDebugOverlay(); } /* * Show <canvas> on top of page */ function showDebugOverlay() { if (get('debugOverlay')) { canvas.style.opacity = 0.5; canvas.style.pointerEvents = 'none'; document.body.appendChild(canvas); } else { // Check if it was previously added if (canvas.parentNode) { canvas.parentNode.removeChild(canvas); } } } /* * Stop if it's slow */ function kill(start) { var duration = new Date().getTime() - start; log('Duration: ' + duration + 'ms'); if (duration > get('maxDuration')) { // Log a message even when debug is false console.log('BackgroundCheck - Killed'); removeClasses(); destroy(); } } /* * Set width and height of <canvas> */ function resizeCanvas() { viewport = { left: 0, top: 0, right: document.body.clientWidth, bottom: window.innerHeight }; canvas.width = document.body.clientWidth; canvas.height = window.innerHeight; } /* * Process px and %, discard anything else */ function getValue(css, parent, delta) { var value; var percentage; if (css.indexOf('px') !== -1) { value = parseFloat(css); } else if (css.indexOf('%') !== -1) { value = parseFloat(css); percentage = value / 100; value = percentage * parent; if (delta) { value -= delta * percentage; } } else { value = parent; } return value; } /* * Calculate top, left, width and height * using the object's CSS */ function calculateAreaFromCSS(obj) { var css = window.getComputedStyle(obj.el); // Force no-repeat and padding-box obj.el.style.backgroundRepeat = 'no-repeat'; obj.el.style.backgroundOrigin = 'padding-box'; // Background Size var size = css.backgroundSize.split(' '); var width = size[0]; var height = size[1] === undefined ? 'auto' : size[1]; var parentRatio = obj.el.clientWidth / obj.el.clientHeight; var imgRatio = obj.img.naturalWidth / obj.img.naturalHeight; if (width === 'cover') { if (parentRatio >= imgRatio) { width = '100%'; height = 'auto'; } else { width = 'auto'; size[0] = 'auto'; height = '100%'; } } else if (width === 'contain') { if (1 / parentRatio < 1 / imgRatio) { width = 'auto'; size[0] = 'auto'; height = '100%'; } else { width = '100%'; height = 'auto'; } } if (width === 'auto') { width = obj.img.naturalWidth; } else { width = getValue(width, obj.el.clientWidth); } if (height === 'auto') { height = (width / obj.img.naturalWidth) * obj.img.naturalHeight; } else { height = getValue(height, obj.el.clientHeight); } if (size[0] === 'auto' && size[1] !== 'auto') { width = (height / obj.img.naturalHeight) * obj.img.naturalWidth; } var position = css.backgroundPosition; // Fix inconsistencies between browsers if (position === 'top') { position = '50% 0%'; } else if (position === 'left') { position = '0% 50%'; } else if (position === 'right') { position = '100% 50%'; } else if (position === 'bottom') { position = '50% 100%'; } else if (position === 'center') { position = '50% 50%'; } position = position.split(' '); var x; var y; // Two-value syntax vs Four-value syntax if (position.length === 4) { x = position[1]; y = position[3]; } else { x = position[0]; y = position[1]; } // Use a default value y = y || '50%'; // Background Position x = getValue(x, obj.el.clientWidth, width); y = getValue(y, obj.el.clientHeight, height); // Take care of ex: background-position: right 20px bottom 20px; if (position.length === 4) { if (position[0] === 'right') { x = obj.el.clientWidth - obj.img.naturalWidth - x; } if (position[2] === 'bottom') { y = obj.el.clientHeight - obj.img.naturalHeight - y; } } x += obj.el.getBoundingClientRect().left; y += obj.el.getBoundingClientRect().top; return { left: Math.floor(x), right: Math.floor(x + width), top: Math.floor(y), bottom: Math.floor(y + height), width: Math.floor(width), height: Math.floor(height) }; } /* * Get Bounding Client Rect */ function getArea(obj) { var area; var image; var parent; if (obj.nodeType) { var rect = obj.getBoundingClientRect(); // Clone ClientRect for modification purposes area = { left: rect.left, right: rect.right, top: rect.top, bottom: rect.bottom, width: rect.width, height: rect.height }; parent = obj.parentNode; image = obj; } else { area = calculateAreaFromCSS(obj); parent = obj.el; image = obj.img; } parent = parent.getBoundingClientRect(); area.imageTop = 0; area.imageLeft = 0; area.imageWidth = image.naturalWidth; area.imageHeight = image.naturalHeight; var ratio = area.imageHeight / area.height; var delta; // Stay within the parent's boundary if (area.top < parent.top) { delta = parent.top - area.top; area.imageTop = ratio * delta; area.imageHeight -= ratio * delta; area.top += delta; area.height -= delta; } if (area.left < parent.left) { delta = parent.left - area.left; area.imageLeft += ratio * delta; area.imageWidth -= ratio * delta; area.width -= delta; area.left += delta; } if (area.bottom > parent.bottom) { delta = area.bottom - parent.bottom; area.imageHeight -= ratio * delta; area.height -= delta; } if (area.right > parent.right) { delta = area.right - parent.right; area.imageWidth -= ratio * delta; area.width -= delta; } area.imageTop = Math.floor(area.imageTop); area.imageLeft = Math.floor(area.imageLeft); area.imageHeight = Math.floor(area.imageHeight); area.imageWidth = Math.floor(area.imageWidth); return area; } /* * Render image on canvas */ function drawImage(image) { var area = getArea(image); image = image.nodeType ? image : image.img; if (area.imageWidth > 0 && area.imageHeight > 0 && area.width > 0 && area.height > 0) { context.drawImage(image, area.imageLeft, area.imageTop, area.imageWidth, area.imageHeight, area.left, area.top, area.width, area.height); } else { log('Skipping image - ' + image.src + ' - area too small'); } } /* * Add/remove classes */ function classList(node, name, mode) { var className = node.className; switch (mode) { case 'add': className += ' ' + name; break; case 'remove': var pattern = new RegExp('(?:^|\\s)' + name + '(?!\\S)', 'g'); className = className.replace(pattern, ''); break; } node.className = className.trim(); } /* * Remove classes from element or * their parents, depending on checkParent */ function removeClasses(el) { var targets = el ? [el] : get('targets'); var target; for (var t = 0; t < targets.length; t++) { target = targets[t]; target = get('changeParent') ? target.parentNode : target; classList(target, get('classes').light, 'remove'); classList(target, get('classes').dark, 'remove'); classList(target, get('classes').complex, 'remove'); } } /* * Calculate average pixel brightness of a region * and add 'light' or 'dark' accordingly */ function calculatePixelBrightness(target) { var dims = target.getBoundingClientRect(); var brightness; var data; var pixels = 0; var delta; var deltaSqr = 0; var mean = 0; var variance; var minOverlap = 0; var mask = get('mask'); if (dims.width > 0 && dims.height > 0) { removeClasses(target); target = get('changeParent') ? target.parentNode : target; data = context.getImageData(dims.left, dims.top, dims.width, dims.height).data; for (var p = 0; p < data.length; p += 4) { if (data[p] === mask.r && data[p + 1] === mask.g && data[p + 2] === mask.b) { minOverlap++; } else { pixels++; brightness = (0.2126 * data[p]) + (0.7152 * data[p + 1]) + (0.0722 * data[p + 2]); delta = brightness - mean; deltaSqr += delta * delta; mean = mean + delta / pixels; } } if (minOverlap <= (data.length / 4) * (1 - (get('minOverlap') / 100))) { variance = Math.sqrt(deltaSqr / pixels) / 255; mean = mean / 255; log('Target: ' + target.className + ' lum: ' + mean + ' var: ' + variance); classList(target, mean <= (get('threshold') / 100) ? get('classes').dark : get('classes').light, 'add'); if (variance > get('minComplexity') / 100) { classList(target, get('classes').complex, 'add'); } } } } /* * Test if a is within b's boundary */ function isInside(a, b) { a = (a.nodeType ? a : a.el).getBoundingClientRect(); b = b === viewport ? b : (b.nodeType ? b : b.el).getBoundingClientRect(); return !(a.right < b.left || a.left > b.right || a.top > b.bottom || a.bottom < b.top); } /* * Process all targets (checkTarget is undefined) * or a single target (checkTarget is a previously set target) * * When not all images are loaded, checkTarget is an image * to avoid processing all targets multiple times */ function processTargets(checkTarget) { var start = new Date().getTime(); var mode = (checkTarget && (checkTarget.tagName === 'IMG' || checkTarget.img)) ? 'image' : 'targets'; var found = checkTarget ? false : true; var total = get('targets').length; var target; for (var t = 0; t < total; t++) { target = get('targets')[t]; if (isInside(target, viewport)) { if (mode === 'targets' && (!checkTarget || checkTarget === target)) { found = true; calculatePixelBrightness(target); } else if (mode === 'image' && isInside(target, checkTarget)) { calculatePixelBrightness(target); } } } if (mode === 'targets' && !found) { throw checkTarget + ' is not a target'; } kill(start); } /* * Find the element's zIndex. Also checks * the zIndex of its parent */ function getZIndex(el) { var calculate = function (el) { var zindex = 0; if (window.getComputedStyle(el).position !== 'static') { zindex = parseInt(window.getComputedStyle(el).zIndex, 10) || 0; // Reserve zindex = 0 for elements with position: static; if (zindex >= 0) { zindex++; } } return zindex; }; var parent = el.parentNode; var zIndexParent = parent ? calculate(parent) : 0; var zIndexEl = calculate(el); return (zIndexParent * 100000) + zIndexEl; } /* * Check zIndexes */ function sortImagesByZIndex(images) { var sorted = false; images.sort(function (a, b) { a = a.nodeType ? a : a.el; b = b.nodeType ? b : b.el; var pos = a.compareDocumentPosition(b); var reverse = 0; a = getZIndex(a); b = getZIndex(b); if (a > b) { sorted = true; } // Reposition if zIndex is the same but the elements are not // sorted according to their document position if (a === b && pos === 2) { reverse = 1; } else if (a === b && pos === 4) { reverse = -1; } return reverse || a - b; }); log('Sorted: ' + sorted); if (sorted) { log(images); } return sorted; } /* * Main function */ function check(target, avoidClear, imageLoaded) { if (supported) { var mask = get('mask'); log('--- BackgroundCheck ---'); log('onLoad event: ' + (imageLoaded && imageLoaded.src)); if (avoidClear !== true) { context.clearRect(0, 0, canvas.width, canvas.height); context.fillStyle = 'rgb(' + mask.r + ', ' + mask.g + ', ' + mask.b + ')'; context.fillRect(0, 0, canvas.width, canvas.height); } var processImages = imageLoaded ? [imageLoaded] : get('images'); var sorted = sortImagesByZIndex(processImages); var image; var imageNode; var loading = false; for (var i = 0; i < processImages.length; i++) { image = processImages[i]; if (isInside(image, viewport)) { imageNode = image.nodeType ? image : image.img; if (imageNode.naturalWidth === 0) { loading = true; log('Loading... ' + image.src); imageNode.removeEventListener('load', check); if (sorted) { // Sorted -- redraw all images imageNode.addEventListener('load', check.bind(null, null, false, null)); } else { // Not sorted -- just draw one image imageNode.addEventListener('load', check.bind(null, target, true, image)); } } else { log('Drawing: ' + image.src); drawImage(image); } } } if (!imageLoaded && !loading) { processTargets(target); } else if (imageLoaded) { processTargets(imageLoaded); } } } /* * Throttle events */ function throttle(callback) { if (get('windowEvents') === true) { if (throttleDelay) { clearTimeout(throttleDelay); } throttleDelay = setTimeout(callback, 200); } } /* * Setter */ function set(property, newValue) { if (attrs[property] === undefined) { throw 'Unknown property - ' + property; } else if (newValue === undefined) { throw 'Missing value for ' + property; } if (property === 'targets' || property === 'images') { try { newValue = getElements(property === 'images' && !newValue ? 'img' : newValue, property === 'images' ? true : false); } catch (err) { newValue = []; throw err; } } else { checkType(newValue, typeof attrs[property]); } removeClasses(); attrs[property] = newValue; check(); if (property === 'debugOverlay') { showDebugOverlay(); } } /* * Getter */ function get(property) { if (attrs[property] === undefined) { throw 'Unknown property - ' + property; } return attrs[property]; } /* * Get position and size of all images. * Used for testing purposes */ function getImageData() { var images = get('images'); var area; var data = []; for (var i = 0; i < images.length; i++) { area = getArea(images[i]); data.push(area); } return data; } return { /* * Init and destroy */ init: init, destroy: destroy, /* * Expose main function */ refresh: check, /* * Setters and getters */ set: set, get: get, /* * Return image data */ getImageData: getImageData }; }));
{'content_hash': '9a8335f99e31bf8ad2dec17a45210554', 'timestamp': '', 'source': 'github', 'line_count': 878, 'max_line_length': 124, 'avg_line_length': 22.626423690205012, 'alnum_prop': 0.5474680358401288, 'repo_name': 'joeyparrish/cdnjs', 'id': 'b3e851c329c18be00e500454d21435fe78343aca', 'size': '19866', 'binary': False, 'copies': '20', 'ref': 'refs/heads/master', 'path': 'ajax/libs/background-check/1.2.1/background-check.js', 'mode': '33188', 'license': 'mit', 'language': []}
""" The LayerMapping class provides a way to map the contents of OGR vector files (e.g. SHP files) to Geographic-enabled Django models. For more information, please consult the GeoDjango documentation: http://geodjango.org/docs/layermapping.html """ import sys from decimal import Decimal from django.core.exceptions import ObjectDoesNotExist from django.db import connections, DEFAULT_DB_ALIAS from django.contrib.gis.db.models import GeometryField from django.contrib.gis.gdal import (CoordTransform, DataSource, OGRException, OGRGeometry, OGRGeomType, SpatialReference) from django.contrib.gis.gdal.field import ( OFTDate, OFTDateTime, OFTInteger, OFTReal, OFTString, OFTTime) from django.db import models, transaction from django.contrib.localflavor.us.models import USStateField # LayerMapping exceptions. class LayerMapError(Exception): pass class InvalidString(LayerMapError): pass class InvalidDecimal(LayerMapError): pass class InvalidInteger(LayerMapError): pass class MissingForeignKey(LayerMapError): pass class LayerMapping(object): "A class that maps OGR Layers to GeoDjango Models." # Acceptable 'base' types for a multi-geometry type. MULTI_TYPES = {1 : OGRGeomType('MultiPoint'), 2 : OGRGeomType('MultiLineString'), 3 : OGRGeomType('MultiPolygon'), OGRGeomType('Point25D').num : OGRGeomType('MultiPoint25D'), OGRGeomType('LineString25D').num : OGRGeomType('MultiLineString25D'), OGRGeomType('Polygon25D').num : OGRGeomType('MultiPolygon25D'), } # Acceptable Django field types and corresponding acceptable OGR # counterparts. FIELD_TYPES = { models.AutoField : OFTInteger, models.IntegerField : (OFTInteger, OFTReal, OFTString), models.FloatField : (OFTInteger, OFTReal), models.DateField : OFTDate, models.DateTimeField : OFTDateTime, models.EmailField : OFTString, models.TimeField : OFTTime, models.DecimalField : (OFTInteger, OFTReal), models.CharField : OFTString, models.SlugField : OFTString, models.TextField : OFTString, models.URLField : OFTString, USStateField : OFTString, models.BigIntegerField : (OFTInteger, OFTReal, OFTString), models.SmallIntegerField : (OFTInteger, OFTReal, OFTString), models.PositiveSmallIntegerField : (OFTInteger, OFTReal, OFTString), } # The acceptable transaction modes. TRANSACTION_MODES = {'autocommit' : transaction.autocommit, 'commit_on_success' : transaction.commit_on_success, } def __init__(self, model, data, mapping, layer=0, source_srs=None, encoding=None, transaction_mode='commit_on_success', transform=True, unique=None, using=DEFAULT_DB_ALIAS): """ A LayerMapping object is initialized using the given Model (not an instance), a DataSource (or string path to an OGR-supported data file), and a mapping dictionary. See the module level docstring for more details and keyword argument usage. """ # Getting the DataSource and the associated Layer. if isinstance(data, basestring): self.ds = DataSource(data) else: self.ds = data self.layer = self.ds[layer] self.using = using self.spatial_backend = connections[using].ops # Setting the mapping & model attributes. self.mapping = mapping self.model = model # Checking the layer -- intitialization of the object will fail if # things don't check out before hand. self.check_layer() # Getting the geometry column associated with the model (an # exception will be raised if there is no geometry column). if self.spatial_backend.mysql: transform = False else: self.geo_field = self.geometry_field() # Checking the source spatial reference system, and getting # the coordinate transformation object (unless the `transform` # keyword is set to False) if transform: self.source_srs = self.check_srs(source_srs) self.transform = self.coord_transform() else: self.transform = transform # Setting the encoding for OFTString fields, if specified. if encoding: # Making sure the encoding exists, if not a LookupError # exception will be thrown. from codecs import lookup lookup(encoding) self.encoding = encoding else: self.encoding = None if unique: self.check_unique(unique) transaction_mode = 'autocommit' # Has to be set to autocommit. self.unique = unique else: self.unique = None # Setting the transaction decorator with the function in the # transaction modes dictionary. if transaction_mode in self.TRANSACTION_MODES: self.transaction_decorator = self.TRANSACTION_MODES[transaction_mode] self.transaction_mode = transaction_mode else: raise LayerMapError('Unrecognized transaction mode: %s' % transaction_mode) #### Checking routines used during initialization #### def check_fid_range(self, fid_range): "This checks the `fid_range` keyword." if fid_range: if isinstance(fid_range, (tuple, list)): return slice(*fid_range) elif isinstance(fid_range, slice): return fid_range else: raise TypeError else: return None def check_layer(self): """ This checks the Layer metadata, and ensures that it is compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer. """ # The geometry field of the model is set here. # TODO: Support more than one geometry field / model. However, this # depends on the GDAL Driver in use. self.geom_field = False self.fields = {} # Getting lists of the field names and the field types available in # the OGR Layer. ogr_fields = self.layer.fields ogr_field_types = self.layer.field_types # Function for determining if the OGR mapping field is in the Layer. def check_ogr_fld(ogr_map_fld): try: idx = ogr_fields.index(ogr_map_fld) except ValueError: raise LayerMapError('Given mapping OGR field "%s" not found in OGR Layer.' % ogr_map_fld) return idx # No need to increment through each feature in the model, simply check # the Layer metadata against what was given in the mapping dictionary. for field_name, ogr_name in self.mapping.items(): # Ensuring that a corresponding field exists in the model # for the given field name in the mapping. try: model_field = self.model._meta.get_field(field_name) except models.fields.FieldDoesNotExist: raise LayerMapError('Given mapping field "%s" not in given Model fields.' % field_name) # Getting the string name for the Django field class (e.g., 'PointField'). fld_name = model_field.__class__.__name__ if isinstance(model_field, GeometryField): if self.geom_field: raise LayerMapError('LayerMapping does not support more than one GeometryField per model.') # Getting the coordinate dimension of the geometry field. coord_dim = model_field.dim try: if coord_dim == 3: gtype = OGRGeomType(ogr_name + '25D') else: gtype = OGRGeomType(ogr_name) except OGRException: raise LayerMapError('Invalid mapping for GeometryField "%s".' % field_name) # Making sure that the OGR Layer's Geometry is compatible. ltype = self.layer.geom_type if not (ltype.name.startswith(gtype.name) or self.make_multi(ltype, model_field)): raise LayerMapError('Invalid mapping geometry; model has %s%s, ' 'layer geometry type is %s.' % (fld_name, (coord_dim == 3 and '(dim=3)') or '', ltype)) # Setting the `geom_field` attribute w/the name of the model field # that is a Geometry. Also setting the coordinate dimension # attribute. self.geom_field = field_name self.coord_dim = coord_dim fields_val = model_field elif isinstance(model_field, models.ForeignKey): if isinstance(ogr_name, dict): # Is every given related model mapping field in the Layer? rel_model = model_field.rel.to for rel_name, ogr_field in ogr_name.items(): idx = check_ogr_fld(ogr_field) try: rel_field = rel_model._meta.get_field(rel_name) except models.fields.FieldDoesNotExist: raise LayerMapError('ForeignKey mapping field "%s" not in %s fields.' % (rel_name, rel_model.__class__.__name__)) fields_val = rel_model else: raise TypeError('ForeignKey mapping must be of dictionary type.') else: # Is the model field type supported by LayerMapping? if not model_field.__class__ in self.FIELD_TYPES: raise LayerMapError('Django field type "%s" has no OGR mapping (yet).' % fld_name) # Is the OGR field in the Layer? idx = check_ogr_fld(ogr_name) ogr_field = ogr_field_types[idx] # Can the OGR field type be mapped to the Django field type? if not issubclass(ogr_field, self.FIELD_TYPES[model_field.__class__]): raise LayerMapError('OGR field "%s" (of type %s) cannot be mapped to Django %s.' % (ogr_field, ogr_field.__name__, fld_name)) fields_val = model_field self.fields[field_name] = fields_val def check_srs(self, source_srs): "Checks the compatibility of the given spatial reference object." if isinstance(source_srs, SpatialReference): sr = source_srs elif isinstance(source_srs, self.spatial_backend.spatial_ref_sys()): sr = source_srs.srs elif isinstance(source_srs, (int, basestring)): sr = SpatialReference(source_srs) else: # Otherwise just pulling the SpatialReference from the layer sr = self.layer.srs if not sr: raise LayerMapError('No source reference system defined.') else: return sr def check_unique(self, unique): "Checks the `unique` keyword parameter -- may be a sequence or string." if isinstance(unique, (list, tuple)): # List of fields to determine uniqueness with for attr in unique: if not attr in self.mapping: raise ValueError elif isinstance(unique, basestring): # Only a single field passed in. if unique not in self.mapping: raise ValueError else: raise TypeError('Unique keyword argument must be set with a tuple, list, or string.') #### Keyword argument retrieval routines #### def feature_kwargs(self, feat): """ Given an OGR Feature, this will return a dictionary of keyword arguments for constructing the mapped model. """ # The keyword arguments for model construction. kwargs = {} # Incrementing through each model field and OGR field in the # dictionary mapping. for field_name, ogr_name in self.mapping.items(): model_field = self.fields[field_name] if isinstance(model_field, GeometryField): # Verify OGR geometry. try: val = self.verify_geom(feat.geom, model_field) except OGRException: raise LayerMapError('Could not retrieve geometry from feature.') elif isinstance(model_field, models.base.ModelBase): # The related _model_, not a field was passed in -- indicating # another mapping for the related Model. val = self.verify_fk(feat, model_field, ogr_name) else: # Otherwise, verify OGR Field type. val = self.verify_ogr_field(feat[ogr_name], model_field) # Setting the keyword arguments for the field name with the # value obtained above. kwargs[field_name] = val return kwargs def unique_kwargs(self, kwargs): """ Given the feature keyword arguments (from `feature_kwargs`) this routine will construct and return the uniqueness keyword arguments -- a subset of the feature kwargs. """ if isinstance(self.unique, basestring): return {self.unique : kwargs[self.unique]} else: return dict((fld, kwargs[fld]) for fld in self.unique) #### Verification routines used in constructing model keyword arguments. #### def verify_ogr_field(self, ogr_field, model_field): """ Verifies if the OGR Field contents are acceptable to the Django model field. If they are, the verified value is returned, otherwise the proper exception is raised. """ if (isinstance(ogr_field, OFTString) and isinstance(model_field, (models.CharField, models.TextField))): if self.encoding: # The encoding for OGR data sources may be specified here # (e.g., 'cp437' for Census Bureau boundary files). val = unicode(ogr_field.value, self.encoding) else: val = ogr_field.value if len(val) > model_field.max_length: raise InvalidString('%s model field maximum string length is %s, given %s characters.' % (model_field.name, model_field.max_length, len(val))) elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField): try: # Creating an instance of the Decimal value to use. d = Decimal(str(ogr_field.value)) except: raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value) # Getting the decimal value as a tuple. dtup = d.as_tuple() digits = dtup[1] d_idx = dtup[2] # index where the decimal is # Maximum amount of precision, or digits to the left of the decimal. max_prec = model_field.max_digits - model_field.decimal_places # Getting the digits to the left of the decimal place for the # given decimal. if d_idx < 0: n_prec = len(digits[:d_idx]) else: n_prec = len(digits) + d_idx # If we have more than the maximum digits allowed, then throw an # InvalidDecimal exception. if n_prec > max_prec: raise InvalidDecimal('A DecimalField with max_digits %d, decimal_places %d must round to an absolute value less than 10^%d.' % (model_field.max_digits, model_field.decimal_places, max_prec)) val = d elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField): # Attempt to convert any OFTReal and OFTString value to an OFTInteger. try: val = int(ogr_field.value) except: raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value) else: val = ogr_field.value return val def verify_fk(self, feat, rel_model, rel_mapping): """ Given an OGR Feature, the related model and its dictionary mapping, this routine will retrieve the related model for the ForeignKey mapping. """ # TODO: It is expensive to retrieve a model for every record -- # explore if an efficient mechanism exists for caching related # ForeignKey models. # Constructing and verifying the related model keyword arguments. fk_kwargs = {} for field_name, ogr_name in rel_mapping.items(): fk_kwargs[field_name] = self.verify_ogr_field(feat[ogr_name], rel_model._meta.get_field(field_name)) # Attempting to retrieve and return the related model. try: return rel_model.objects.using(self.using).get(**fk_kwargs) except ObjectDoesNotExist: raise MissingForeignKey('No ForeignKey %s model found with keyword arguments: %s' % (rel_model.__name__, fk_kwargs)) def verify_geom(self, geom, model_field): """ Verifies the geometry -- will construct and return a GeometryCollection if necessary (for example if the model field is MultiPolygonField while the mapped shapefile only contains Polygons). """ # Downgrade a 3D geom to a 2D one, if necessary. if self.coord_dim != geom.coord_dim: geom.coord_dim = self.coord_dim if self.make_multi(geom.geom_type, model_field): # Constructing a multi-geometry type to contain the single geometry multi_type = self.MULTI_TYPES[geom.geom_type.num] g = OGRGeometry(multi_type) g.add(geom) else: g = geom # Transforming the geometry with our Coordinate Transformation object, # but only if the class variable `transform` is set w/a CoordTransform # object. if self.transform: g.transform(self.transform) # Returning the WKT of the geometry. return g.wkt #### Other model methods #### def coord_transform(self): "Returns the coordinate transformation object." SpatialRefSys = self.spatial_backend.spatial_ref_sys() try: # Getting the target spatial reference system target_srs = SpatialRefSys.objects.using(self.using).get(srid=self.geo_field.srid).srs # Creating the CoordTransform object return CoordTransform(self.source_srs, target_srs) except Exception as msg: raise LayerMapError('Could not translate between the data source and model geometry: %s' % msg) def geometry_field(self): "Returns the GeometryField instance associated with the geographic column." # Use the `get_field_by_name` on the model's options so that we # get the correct field instance if there's model inheritance. opts = self.model._meta fld, model, direct, m2m = opts.get_field_by_name(self.geom_field) return fld def make_multi(self, geom_type, model_field): """ Given the OGRGeomType for a geometry and its associated GeometryField, determine whether the geometry should be turned into a GeometryCollection. """ return (geom_type.num in self.MULTI_TYPES and model_field.__class__.__name__ == 'Multi%s' % geom_type.django) def save(self, verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False): """ Saves the contents from the OGR DataSource Layer into the database according to the mapping dictionary given at initialization. Keyword Parameters: verbose: If set, information will be printed subsequent to each model save executed on the database. fid_range: May be set with a slice or tuple of (begin, end) feature ID's to map from the data source. In other words, this keyword enables the user to selectively import a subset range of features in the geographic data source. step: If set with an integer, transactions will occur at every step interval. For example, if step=1000, a commit would occur after the 1,000th feature, the 2,000th feature etc. progress: When this keyword is set, status information will be printed giving the number of features processed and sucessfully saved. By default, progress information will pe printed every 1000 features processed, however, this default may be overridden by setting this keyword with an integer for the desired interval. stream: Status information will be written to this file handle. Defaults to using `sys.stdout`, but any object with a `write` method is supported. silent: By default, non-fatal error notifications are printed to stdout, but this keyword may be set to disable these notifications. strict: Execution of the model mapping will cease upon the first error encountered. The default behavior is to attempt to continue. """ # Getting the default Feature ID range. default_range = self.check_fid_range(fid_range) # Setting the progress interval, if requested. if progress: if progress is True or not isinstance(progress, int): progress_interval = 1000 else: progress_interval = progress # Defining the 'real' save method, utilizing the transaction # decorator created during initialization. @self.transaction_decorator def _save(feat_range=default_range, num_feat=0, num_saved=0): if feat_range: layer_iter = self.layer[feat_range] else: layer_iter = self.layer for feat in layer_iter: num_feat += 1 # Getting the keyword arguments try: kwargs = self.feature_kwargs(feat) except LayerMapError as msg: # Something borked the validation if strict: raise elif not silent: stream.write('Ignoring Feature ID %s because: %s\n' % (feat.fid, msg)) else: # Constructing the model using the keyword args is_update = False if self.unique: # If we want unique models on a particular field, handle the # geometry appropriately. try: # Getting the keyword arguments and retrieving # the unique model. u_kwargs = self.unique_kwargs(kwargs) m = self.model.objects.using(self.using).get(**u_kwargs) is_update = True # Getting the geometry (in OGR form), creating # one from the kwargs WKT, adding in additional # geometries, and update the attribute with the # just-updated geometry WKT. geom = getattr(m, self.geom_field).ogr new = OGRGeometry(kwargs[self.geom_field]) for g in new: geom.add(g) setattr(m, self.geom_field, geom.wkt) except ObjectDoesNotExist: # No unique model exists yet, create. m = self.model(**kwargs) else: m = self.model(**kwargs) try: # Attempting to save. m.save(using=self.using) num_saved += 1 if verbose: stream.write('%s: %s\n' % (is_update and 'Updated' or 'Saved', m)) except SystemExit: raise except Exception as msg: if self.transaction_mode == 'autocommit': # Rolling back the transaction so that other model saves # will work. transaction.rollback_unless_managed() if strict: # Bailing out if the `strict` keyword is set. if not silent: stream.write('Failed to save the feature (id: %s) into the model with the keyword arguments:\n' % feat.fid) stream.write('%s\n' % kwargs) raise elif not silent: stream.write('Failed to save %s:\n %s\nContinuing\n' % (kwargs, msg)) # Printing progress information, if requested. if progress and num_feat % progress_interval == 0: stream.write('Processed %d features, saved %d ...\n' % (num_feat, num_saved)) # Only used for status output purposes -- incremental saving uses the # values returned here. return num_saved, num_feat nfeat = self.layer.num_feat if step and isinstance(step, int) and step < nfeat: # Incremental saving is requested at the given interval (step) if default_range: raise LayerMapError('The `step` keyword may not be used in conjunction with the `fid_range` keyword.') beg, num_feat, num_saved = (0, 0, 0) indices = range(step, nfeat, step) n_i = len(indices) for i, end in enumerate(indices): # Constructing the slice to use for this step; the last slice is # special (e.g, [100:] instead of [90:100]). if i+1 == n_i: step_slice = slice(beg, None) else: step_slice = slice(beg, end) try: num_feat, num_saved = _save(step_slice, num_feat, num_saved) beg = end except: stream.write('%s\nFailed to save slice: %s\n' % ('=-' * 20, step_slice)) raise else: # Otherwise, just calling the previously defined _save() function. _save()
{'content_hash': '793a3016d584ab84baca2313f7f5452d', 'timestamp': '', 'source': 'github', 'line_count': 600, 'max_line_length': 142, 'avg_line_length': 45.24333333333333, 'alnum_prop': 0.5782435717969499, 'repo_name': 'chrishas35/django-travis-ci', 'id': 'ea3f3d7861831f28456b190a0f80d5641dc0fa5b', 'size': '27205', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'django/contrib/gis/utils/layermapping.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'JavaScript', 'bytes': '89027'}, {'name': 'Python', 'bytes': '8037393'}, {'name': 'Shell', 'bytes': '4241'}]}
package com.alibaba.wasp.plan.parser.druid.dialect; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlHelpStatement; /** * WaspSqlHelpStatement is the same with MySqlHelpStatement logic. * */ public class WaspSqlHelpStatement extends MySqlHelpStatement { private static final long serialVersionUID = 3429056627522601824L; /** * */ public WaspSqlHelpStatement() { // TODO Auto-generated constructor stub } }
{'content_hash': '55085f355027ce1359efef5674633d04', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 76, 'avg_line_length': 22.3, 'alnum_prop': 0.7556053811659192, 'repo_name': 'fengshao0907/wasp', 'id': '02a70cdbaadc047ffdf0d5d7f5600ff284066759', 'size': '1252', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/alibaba/wasp/plan/parser/druid/dialect/WaspSqlHelpStatement.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '932'}, {'name': 'HTML', 'bytes': '1748'}, {'name': 'Java', 'bytes': '3805664'}, {'name': 'JavaScript', 'bytes': '1347'}, {'name': 'Protocol Buffer', 'bytes': '53324'}, {'name': 'Ruby', 'bytes': '72366'}, {'name': 'Shell', 'bytes': '41849'}]}
#!/usr/bin/env php <?php require __DIR__ . '/../src/autoload.php'; $template = file_get_contents(__DIR__ . '/child-class.tpl'); $class = new ReflectionClass('SebastianBergmann\Money\Currency'); $attribute = $class->getProperty('currencies'); $attribute->setAccessible(true); foreach (array_keys($attribute->getValue()) as $currencyCode) { if ($currencyCode == 'TRY') { continue; } file_put_contents( __DIR__ . '/../src/currency/' . $currencyCode . '.php', str_replace( '{currencyCode}', $currencyCode, $template ) ); }
{'content_hash': 'd6ce993c180b68694aab3a18d9c39f7b', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 69, 'avg_line_length': 24.52, 'alnum_prop': 0.5709624796084829, 'repo_name': 'arleincho/money', 'id': '81260860ba199ff59f9ff7614b11e3381c2d3c3a', 'size': '844', 'binary': False, 'copies': '25', 'ref': 'refs/heads/master', 'path': 'build/generate-child-classes.php', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'PHP', 'bytes': '226264'}, {'name': 'Smarty', 'bytes': '743'}]}
Watch-List2 =========== Remake of [Watch-List](https://github.com/ErikAndreas/Watch-List) with AngularJS "replacement" stack; Browserify, Q, Superagent, Routie and RactiveJS with a BDD test stack
{'content_hash': '5255b9ffd99e908a05b6fed7b2b8603b', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 171, 'avg_line_length': 49.25, 'alnum_prop': 0.7411167512690355, 'repo_name': 'ErikAndreas/Watch-List2', 'id': '0a10f19d39b67e79c88675df1d6d2386c524dd42', 'size': '197', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2385'}, {'name': 'JavaScript', 'bytes': '33448'}]}
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head th:replace="common/template :: head (title=#{notedown.templates.login.title})"></head> <body> <div th:replace="common/template :: header (page='app')"></div> <div class="container"> <div class="alert alert-success" th:if="${install}" th:text="#{notedown.templates.login.install-success}"></div> <form class="form-signin" method="post" th:action="@{/login}"> <div class="alert alert-danger" th:if="${error}" th:text="#{notedown.templates.login.login-error}"></div> <div class="alert alert-success" th:if="${logout}" th:text="#{notedown.templates.login.logout-success}"></div> <h2 class="form-signin-heading" th:text="#{notedown.templates.login.login-prompt}"></h2> <input type="text" id="inputEmail" class="form-control" th:placeholder="#{notedown.templates.login.email}" required="required" autofocus="autofocus" name="email"/> <input type="password" id="inputPassword" class="form-control" th:placeholder="#{notedown.templates.login.password}" required="required" name="password"/> <div class="checkbox"> <label> <input type="checkbox" name="remember-me"/> <span th:text="#{notedown.templates.login.remember-me}"></span> </label> </div> <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{notedown.templates.login.login-action}"></button> </form> <div th:replace="common/template :: footer(displayText=true)"></div> </div> </body> </html>
{'content_hash': '3fe01271f08cb232401d2f46bdd99206', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 118, 'avg_line_length': 55.62068965517241, 'alnum_prop': 0.6311221326720396, 'repo_name': 'jchampemont/notedown', 'id': '9bca7a4f6aad86f2876e5f83026f7f4327b1d77e', 'size': '1613', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/resources/templates/login.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '2204'}, {'name': 'HTML', 'bytes': '22238'}, {'name': 'Java', 'bytes': '96180'}, {'name': 'JavaScript', 'bytes': '17938'}]}
// Copyright (c) 2004 OPITZ CONSULTING GmbH package de.oc.dbdoc; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.app.VelocityEngine; import de.oc.dbdoc.ant.Diagram; import de.oc.dbdoc.ant.Styles; import de.oc.dbdoc.export.DotExport; import de.oc.dbdoc.export.DotWriterImpl; import de.oc.dbdoc.graphdata.Graph; import de.oc.dbdoc.graphdata.GraphForDiagram; import de.oc.dbdoc.graphdata.GraphForSingleTable; import de.oc.dbdoc.graphdata.GraphForSingleTableAncestors; import de.oc.dbdoc.graphdata.GraphForSingleTableDescendants; import de.oc.dbdoc.schemadata.Association; import de.oc.dbdoc.schemadata.Schema; import de.oc.dbdoc.schemadata.Table; /** * DOCUMENT ME! * * @author FSA */ public class Main { public static class GraphRef { private Graph _graph; private boolean _isOutref; private String _linkLabel; private List<GraphRef> _otherLinkedGraphRefs = new ArrayList<Main.GraphRef>(); private Schema _schema; public List<GraphRef> getOtherLinkedGraphRefs() { return _otherLinkedGraphRefs; } public GraphRef( Graph pGraph, boolean pIsOutref, Schema pSchema ) { this( pGraph, pIsOutref, pSchema, pGraph.getLabel() ); } public GraphRef( Graph pGraph, boolean pIsOutref, Schema pSchema, String pLinkLabel ) { _graph = pGraph; _isOutref = pIsOutref; _linkLabel = pLinkLabel; _schema = pSchema; } public Graph getGraph() { return _graph; } public void addLinkedGraphRef( GraphRef pGraphRef ) { _otherLinkedGraphRefs.add( pGraphRef ); } public boolean isOutref() { return _isOutref; } public GraphRef createForOtherGraph( Graph pGraph ) { return new GraphRef( pGraph, !_isOutref ? false : _hasOutrefVersion( pGraph, _schema ), _schema ); } public String getLinkLabel() { return _linkLabel; } } public static String readFile( File pFile ) { try { String lReturn = ""; BufferedReader lBufferedReader; lBufferedReader = new BufferedReader( new FileReader( pFile ) ); String lLine = null; while( (lLine = lBufferedReader.readLine()) != null ) { lReturn += lLine + "\n"; } return lReturn; } catch( Exception e ) { throw new RuntimeException( e ); } } public static void writeDiagramsRecursive( Diagram pRootDiagram, Styles pStyles, Schema pSchema, String pHtmlOutDir, String pDotOutDir, String pTableSourcefileFolder ) { try { GraphForDiagram lRootGraph = new GraphForDiagram( pRootDiagram, pStyles, null ); _writeGraphRecursive( lRootGraph, pSchema, pHtmlOutDir, pDotOutDir, pTableSourcefileFolder ); for( Table lTable : pSchema.getTables() ) { Graph lGraphNormal = new GraphForSingleTable( lTable, Collections.singletonList( (Graph)lRootGraph ), pStyles ); boolean lHasOutref = _hasOutrefVersion( lGraphNormal, pSchema ); List<GraphRef> lGraphRefs = new ArrayList<Main.GraphRef>(); if( lHasOutref ) { lGraphRefs.add( new GraphRef( lGraphNormal, true, pSchema, "only outgoing references" ) ); lGraphRefs.add( new GraphRef( lGraphNormal, false, pSchema, "all references" ) ); lGraphRefs.add( new GraphRef( new GraphForSingleTableDescendants( lTable, Collections.singletonList( (Graph)lRootGraph ), pStyles ), false, pSchema, "all descendants" ) ); } else { lGraphRefs.add( new GraphRef( lGraphNormal, false, pSchema, "normal view" ) ); } if( _hasInrefVersion( lGraphNormal, pSchema ) ) { lGraphRefs.add( new GraphRef( new GraphForSingleTableAncestors( lTable, Collections.singletonList( (Graph)lRootGraph ), pStyles ), false, pSchema, "all ancestors" ) ); } for( GraphRef lGraphRef : lGraphRefs ) { for( GraphRef lGraphRefOther : lGraphRefs ) { if( lGraphRef != lGraphRefOther ) { lGraphRef.addLinkedGraphRef( lGraphRefOther ); } } } for( GraphRef lGraphRef : lGraphRefs ) { _writeSingleGraph( lGraphRef, pSchema, pHtmlOutDir, pDotOutDir, pTableSourcefileFolder ); } } } catch( Exception e ) { e.printStackTrace(); throw new RuntimeException( e ); } } private static void _writeGraphRecursive( Graph pGraph, Schema pSchema, String pHtmlOutDir, String pDotOutDir, String pTableSourcefileFolder ) throws Exception { boolean lHasOutref = _hasOutrefVersion( pGraph, pSchema ); GraphRef lGraphRefAllref = new GraphRef( pGraph, false, pSchema, "all references" ); if( lHasOutref ) { GraphRef lGraphRefOutref = new GraphRef( pGraph, true, pSchema, "only outgoing references" ); lGraphRefAllref.addLinkedGraphRef( lGraphRefOutref ); lGraphRefOutref.addLinkedGraphRef( lGraphRefAllref ); _writeSingleGraph( lGraphRefOutref, pSchema, pHtmlOutDir, pDotOutDir, pTableSourcefileFolder ); } _writeSingleGraph( lGraphRefAllref, pSchema, pHtmlOutDir, pDotOutDir, pTableSourcefileFolder ); for( Graph lSubGraph : pGraph.getSubGraphs() ) { _writeGraphRecursive( lSubGraph, pSchema, pHtmlOutDir, pDotOutDir, pTableSourcefileFolder ); } } public static String getNameFromLabel( String pLabel ) { String lReturn = ""; for( int i = 0; i < pLabel.length(); i++ ) { char lChar = pLabel.charAt( i ); if( Character.isLetterOrDigit( lChar ) || lChar == '_' ) { lReturn += lChar; } else { if( lReturn.length() > 0 && lReturn.charAt( lReturn.length() - 1 ) != '_' ) { lReturn += '_'; } } } return lReturn.toLowerCase(); } private static void _writeSingleGraph( GraphRef pGraphRef, Schema pSchema, String pHtmlOutDir, String pDotOutDir, String pTableSourcefileFolder ) throws Exception { System.out.println( "writing graph: " + getFileNameForGraph( pGraphRef, pGraphRef.getGraph().getDotExecutable() ) ); _writeHTML( pHtmlOutDir, pGraphRef, pSchema, pTableSourcefileFolder ); FileWriter lFileWriter = new FileWriter( pDotOutDir + "/" + getFileNameForGraph( pGraphRef, pGraphRef.getGraph().getDotExecutable() ) ); new DotExport().export( pGraphRef.getGraph(), pSchema, new DotWriterImpl( lFileWriter ), pGraphRef.isOutref() ); lFileWriter.close(); } private static boolean _hasOutrefVersion( Graph pGraph, Schema pSchema ) { if( !pGraph.allAssociations() ) { return false; } for( Association lAssociation : pSchema.getAssociations() ) { if( !pGraph.containsTableRecursive( lAssociation.getTableFrom() ) ) { if( pGraph.containsTableRecursive( lAssociation.getTableTo() ) ) { return true; } } } return false; } private static boolean _hasInrefVersion( Graph pGraph, Schema pSchema ) { if( !pGraph.allAssociations() ) { return false; } for( Association lAssociation : pSchema.getAssociations() ) { if( !pGraph.containsTableRecursive( lAssociation.getTableTo() ) ) { if( pGraph.containsTableRecursive( lAssociation.getTableFrom() ) ) { return true; } } } return false; } public static final String TAB_FILE_PREFIX = "tab_"; public static String getFileNameForName( String pName, boolean pIsOutref, String pExtension ) { return getNameFromLabel( pName ) + (pIsOutref ? "_outref" : "") + "." + pExtension; } public static String getFileNameForGraph( GraphRef pGraphRef, String pExtension ) { return getFileNameForName( pGraphRef.getGraph().isRoot() ? "index" : (pGraphRef.getGraph().isSingleTable() ? TAB_FILE_PREFIX : "sg_") + pGraphRef.getGraph().getLabel(), pGraphRef.isOutref(), pExtension ); } public static String getHtmlFileNameForGraph( GraphRef pGraphRef ) { return getFileNameForGraph( pGraphRef, "html" ); } public static String _getImgFileNameForGraph( GraphRef pGraphRef ) { return getFileNameForGraph( pGraphRef, "png" ); } private static String _getHtmlLinkForGraph( GraphRef pGraphRef ) { return "<a href=\"" + getHtmlFileNameForGraph( pGraphRef ) + "\">" + pGraphRef.getLinkLabel() + "</a>"; } private static void _createSubgraphListRecursive( ArrayList<String> pSubGraphLinks, GraphRef pGraphRef, int pLevel ) { if( !pGraphRef.getGraph().isSingleTable() ) { for( Graph lSubGraph : pGraphRef.getGraph().getSubGraphs() ) { if( !lSubGraph.isSingleTable() ) { String lLink = _getHtmlLinkForGraph( pGraphRef.createForOtherGraph( lSubGraph ) ); for( int i = 0; i < pLevel; i++ ) { if( i == pLevel - 1 ) { lLink = "->" + lLink; } else { lLink = "&nbsp;&nbsp;" + lLink; } } pSubGraphLinks.add( lLink ); _createSubgraphListRecursive( pSubGraphLinks, pGraphRef.createForOtherGraph( lSubGraph ), pLevel + 1 ); } } } } private static void _writeHTML( String pHtmlOutDir, GraphRef pGraphRef, Schema pSchema, String pTableSourcefileFolder ) throws Exception { ArrayList<String> lSubGraphLinks = new ArrayList<String>(); ArrayList<String> lSubTableLinks = new ArrayList<String>(); ArrayList<String> lParentGraphLinks = new ArrayList<String>(); ArrayList<Table> lContainedTables = new ArrayList<Table>(); _createSubgraphListRecursive( lSubGraphLinks, pGraphRef, 0 ); for( Table lTable : pSchema.getTables() ) { if( pGraphRef.getGraph().containsTableRecursive( lTable ) ) { lContainedTables.add( lTable ); lSubTableLinks.add( _getHtmlLinkForGraph( pGraphRef.createForOtherGraph( new GraphForSingleTable( lTable, Collections.singletonList( pGraphRef.getGraph() ), null ) ) ) ); } } // Wurzelgraphnamen in Link umwandeln String lParentGraphLink; if( pGraphRef.getGraph().isRoot() || pGraphRef.getGraph().isSingleTable() ) { lParentGraphLink = null; if( pGraphRef.getGraph().isSingleTable() ) { _getHtmlLinksForDiagramsContainingTables( lParentGraphLinks, pGraphRef.createForOtherGraph( pGraphRef.getGraph().getParentGraph() ), lContainedTables.get( 0 ) ); lSubTableLinks.clear(); } } else { lParentGraphLink = ""; Graph lParent = pGraphRef.getGraph().getParentGraph(); do { lParentGraphLink = _getHtmlLinkForGraph( pGraphRef.createForOtherGraph( lParent ) ) + (lParentGraphLink.length() == 0 ? "" : " -> " + lParentGraphLink); if( lParent.isRoot() ) { break; } lParent = lParent.getParentGraph(); } while( true ); } String lGraphChangeLink = ""; for( GraphRef lGraphRef : pGraphRef.getOtherLinkedGraphRefs() ) { lGraphChangeLink += " " + _getHtmlLinkForGraph( lGraphRef ); } lGraphChangeLink = lGraphChangeLink.trim(); if( lGraphChangeLink.length() == 0 ) { lGraphChangeLink = null; } String lTableSource = null; if( pGraphRef.getGraph().isSingleTable() && pTableSourcefileFolder != null && pTableSourcefileFolder.length() > 0 ) { File lFile = new File( pTableSourcefileFolder + "/" + pGraphRef.getGraph().getLabel().toLowerCase() + ".sql" ); if( lFile.exists() ) { lTableSource = readFile( lFile ); } } VelocityEngine lVelocityEngine = new VelocityEngine(); lVelocityEngine.init(); Template lTemplate = Velocity.getTemplate( "graphtemplate.vm" ); VelocityContext lVelocityContext = new VelocityContext(); lVelocityContext.put( "pImageName", _getImgFileNameForGraph( pGraphRef ) ); lVelocityContext.put( "pSvgName", getFileNameForGraph( pGraphRef, "svg" ) ); lVelocityContext.put( "pGraphChangeLink", lGraphChangeLink ); lVelocityContext.put( "pTitle", pGraphRef.getGraph().getLabel() ); lVelocityContext.put( "pParentGraphLink", lParentGraphLink ); lVelocityContext.put( "pParentGraphLinks", lParentGraphLinks.isEmpty() ? null : lParentGraphLinks ); lVelocityContext.put( "pSubGraphLinks", lSubGraphLinks.isEmpty() ? null : lSubGraphLinks ); lVelocityContext.put( "pSubTableLinks", lSubTableLinks.isEmpty() ? null : lSubTableLinks ); lVelocityContext.put( "pTableSource", lTableSource ); FileWriter lFileWriter = new FileWriter( pHtmlOutDir + "/" + getHtmlFileNameForGraph( pGraphRef ) ); lTemplate.merge( lVelocityContext, lFileWriter ); lFileWriter.close(); } private static void _getHtmlLinksForDiagramsContainingTables( ArrayList<String> pDiagramGraphLinks, GraphRef pGraphRef, Table pTable ) { if( pGraphRef.getGraph().containsTableRecursive( pTable ) ) { pDiagramGraphLinks.add( _getHtmlLinkForGraph( pGraphRef ) ); } for( Graph lGraph : pGraphRef.getGraph().getSubGraphs() ) { _getHtmlLinksForDiagramsContainingTables( pDiagramGraphLinks, pGraphRef.createForOtherGraph( lGraph ), pTable ); } } public static void log( String pString ) { System.out.println( pString ); } }
{'content_hash': '40fe6dd6be34da4637b23d7711accfa0', 'timestamp': '', 'source': 'github', 'line_count': 442, 'max_line_length': 194, 'avg_line_length': 30.884615384615383, 'alnum_prop': 0.6604644348399384, 'repo_name': 'opitzconsulting/orcas', 'id': '3761fe226d2b76b91844d5095250979a8b70e481', 'size': '13651', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'orcas_dbdoc/java/src/de/oc/dbdoc/Main.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '2107'}, {'name': 'Groovy', 'bytes': '49636'}, {'name': 'Java', 'bytes': '1278394'}, {'name': 'PLSQL', 'bytes': '56568'}, {'name': 'Shell', 'bytes': '3405'}, {'name': 'XSLT', 'bytes': '33637'}]}
package com.gs.collections.impl.set.strategy.immutable; import com.gs.collections.api.block.HashingStrategy; import com.gs.collections.api.set.ImmutableSet; import com.gs.collections.api.set.MutableSet; import com.gs.collections.impl.block.factory.HashingStrategies; import com.gs.collections.impl.factory.HashingStrategySets; import com.gs.collections.impl.list.Interval; import com.gs.collections.impl.list.mutable.FastList; import com.gs.collections.impl.set.immutable.AbstractImmutableEmptySetTestCase; import com.gs.collections.impl.set.mutable.UnifiedSet; import com.gs.collections.impl.test.Verify; import org.junit.Assert; import org.junit.Test; public class ImmutableEmptySetWithHashingStrategyTest extends AbstractImmutableEmptySetTestCase { //Not using the static factor method in order to have concrete types for test cases private static final HashingStrategy<Integer> HASHING_STRATEGY = HashingStrategies.nullSafeHashingStrategy(new HashingStrategy<Integer>() { public int computeHashCode(Integer object) { return object.hashCode(); } public boolean equals(Integer object1, Integer object2) { return object1.equals(object2); } }); @Override protected ImmutableSet<Integer> classUnderTest() { return new ImmutableEmptySetWithHashingStrategy<>(HASHING_STRATEGY); } @Override @Test public void newWithout() { Assert.assertEquals( HashingStrategySets.immutable.of(HASHING_STRATEGY), HashingStrategySets.immutable.of(HASHING_STRATEGY).newWithout(1)); Assert.assertEquals( HashingStrategySets.immutable.of(HASHING_STRATEGY), HashingStrategySets.immutable.of(HASHING_STRATEGY).newWithoutAll(Interval.oneTo(3))); } @Override @Test public void equalsAndHashCode() { ImmutableSet<Integer> immutable = this.classUnderTest(); MutableSet<Integer> mutable = UnifiedSet.newSet(immutable); Verify.assertEqualsAndHashCode(mutable, immutable); Verify.assertPostSerializedEqualsAndHashCode(immutable); Assert.assertNotEquals(FastList.newList(mutable), immutable); } }
{'content_hash': 'b0c9c4411e360c6ed54185d83f66e1f2', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 141, 'avg_line_length': 36.17741935483871, 'alnum_prop': 0.7302719572001783, 'repo_name': 'mix-juice001/gs-collections', 'id': 'b182e9629f7df43577e11932d2e17d4922a30919', 'size': '2840', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'unit-tests/src/test/java/com/gs/collections/impl/set/strategy/immutable/ImmutableEmptySetWithHashingStrategyTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '11910874'}, {'name': 'Scala', 'bytes': '163387'}]}
CC = g++ CFLAGS = -Og -std=c++14 -Wall -lncurses -pthread INSTALLPATH = ./ EXECUTABLE = cws2 all: cws2 cws2: main.o person.o util.o tribe.o $(CC) $(CFLAGS) main.o person.o util.o tribe.o -o $(EXECUTABLE) main.o: main.cpp tribe.hpp util.hpp $(CC) $(CFLAGS) -c main.cpp person.o: person.cpp person.hpp util.hpp $(CC) $(CFLAGS) -c person.cpp util.o: util.cpp util.hpp $(CC) $(CFLAGS) -c util.cpp tribe.o: tribe.cpp tribe.hpp util.hpp person.hpp $(CC) $(CFLAGS) -c tribe.cpp install: cp ./$(EXECUTABLE) $(INSTALLPATH) uninstall: rm ./$(EXECUTABLE) $(INSTALLPATH) clean: rm -rf *.o $(EXECUTABLE)
{'content_hash': 'd24a47b2182da57ed9785695e15265e3', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 64, 'avg_line_length': 19.64516129032258, 'alnum_prop': 0.6600985221674877, 'repo_name': 'Gabe-Jespersen/CWS2', 'id': '8a3bdb03d53de707e9692c6f728ee5b8d6595dd1', 'size': '609', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Makefile', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '20560'}, {'name': 'Makefile', 'bytes': '609'}]}
#import <XCTest/XCTest.h> #import "MemLogStorage.h" #import "SQLiteLogStorage.h" #import "LogTestHelper.h" @interface CommonLogStorageTests : XCTestCase @end @implementation CommonLogStorageTests - (NSArray *)storagesToTestWithBucketSize:(int64_t)bucketSize recordCount:(int32_t)recordCount { NSMutableArray *storagesToTest = [NSMutableArray array]; [storagesToTest addObject:[[MemLogStorage alloc] initWithBucketSize:bucketSize bucketRecordCount:recordCount]]; [storagesToTest addObject:[[SQLiteLogStorage alloc] initWithDatabaseName:DEFAULT_TEST_DB_NAME bucketSize:bucketSize bucketRecordCount:recordCount]]; return storagesToTest; } - (void)setUp { [super setUp]; NSString *appSupportDir = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES)[0]; NSString *dbPath = [appSupportDir stringByAppendingPathComponent:DEFAULT_TEST_DB_NAME]; [[NSFileManager defaultManager] removeItemAtPath:dbPath error:nil]; } - (void)testRemoval { int64_t maxBucketSize = 10; int32_t maxRecordCount = 4; NSArray *storagesToTest = [self storagesToTestWithBucketSize:maxBucketSize recordCount:maxRecordCount]; for (id<LogStorage> storage in storagesToTest) { LogRecord *record = [LogTestHelper defaultLogRecord]; int32_t insertionCount = 12; int32_t iter = insertionCount; while (iter-- > 0) { [storage addLogRecord:record]; } LogBucket *logBucket = [storage getNextBucket]; XCTAssertTrue([[logBucket logRecords] count] <= maxRecordCount, @"Failure for storage: %@", [(id)storage class]); XCTAssertTrue([self getLogBucketSize:logBucket] <= maxBucketSize, @"Failure for storage: %@", [(id)storage class]); XCTAssertEqual(insertionCount - [[logBucket logRecords] count], [[storage getStatus] getRecordCount], @"Failure for storage: %@", [(id)storage class]); [storage close]; } } - (void)testEmptyLogRecord { int64_t bucketSize = 3; int32_t recordCount = 3; NSArray *storagesToTest = [self storagesToTestWithBucketSize:bucketSize recordCount:recordCount]; for (id<LogStorage> storage in storagesToTest) { LogBucket *bucket = [storage getNextBucket]; XCTAssertNil(bucket, @"Failure for storage: %@", [(id)storage class]); [storage close]; } } - (void)testRecordCountAndConsumedBytes { int64_t maxBucketSize = 3; int32_t maxRecordCount = 3; NSArray *storagesToTest = [self storagesToTestWithBucketSize:maxBucketSize recordCount:maxRecordCount]; for (id<LogStorage> storage in storagesToTest) { LogRecord *record = [LogTestHelper defaultLogRecord]; int32_t insertionCount = 3; int32_t iter = insertionCount; while (iter-- > 0) { [storage addLogRecord:record]; } XCTAssertTrue([[storage getStatus] getRecordCount] == insertionCount, @"Failure for storage: %@", [(id)storage class]); XCTAssertTrue([[storage getStatus] getConsumedVolume] == (insertionCount * [record getSize]), @"Failure for storage: %@", [(id)storage class]); [storage close]; } } - (void)testUniqueIdGenerator { int64_t maxBucketSize = 3; int32_t maxRecordCount = 3; NSArray *storagesToTest = [self storagesToTestWithBucketSize:maxBucketSize recordCount:maxRecordCount]; for (id<LogStorage> storage in storagesToTest) { LogRecord *record = [LogTestHelper defaultLogRecord]; int32_t insertionCount = 3; int32_t iter = insertionCount; while (iter-- > 0) { [storage addLogRecord:record]; } LogBucket *group1 = [storage getNextBucket]; LogBucket *group2 = [storage getNextBucket]; XCTAssertNotEqual([group1 bucketId], [group2 bucketId], @"Failure for storage: %@", [(id)storage class]); [storage close]; } } - (void)testLogRecordAdding { [self helpAddingRecordCount:1 maxBucketSize:3 maxRecordCount:1 expectedCount:1]; [self helpAddingRecordCount:4 maxBucketSize:3 maxRecordCount:2 expectedCount:1]; [self helpAddingRecordCount:3 maxBucketSize:9 maxRecordCount:4 expectedCount:3]; [self helpAddingRecordCount:5 maxBucketSize:5 maxRecordCount:2 expectedCount:1]; } - (void)testGetSameLogBucket { int64_t maxBucketSize = 3; int32_t maxRecordCount = 3; NSArray *storagesToTest = [self storagesToTestWithBucketSize:maxBucketSize recordCount:maxRecordCount]; for (id<LogStorage> storage in storagesToTest) { LogRecord *record = [LogTestHelper defaultLogRecord]; int32_t iter = 3; while (iter-- > 0) { [storage addLogRecord:record]; } LogBucket *group1 = [storage getNextBucket]; [storage rollbackBucketWithId:[group1 bucketId]]; LogBucket *group2 = [storage getNextBucket]; XCTAssertTrue([[group1 logRecords] count] == [[group2 logRecords] count], @"Failure for storage: %@", [(id)storage class]); NSArray *group1Array = [NSArray arrayWithArray:[group1 logRecords]]; NSArray *group2Array = [NSArray arrayWithArray:[group2 logRecords]]; for (int i = 0; i < [group1Array count]; i++) { LogRecord *expected = group1Array[i]; LogRecord *actual = group2Array[i]; XCTAssertTrue([expected getSize] == [actual getSize], @"Failure for storage: %@", [(id)storage class]); XCTAssertEqualObjects([expected data], [actual data], @"Failure for storage: %@", [(id)storage class]); } [storage close]; } } - (void)testRecordRemoval { int64_t bucketSize = 9; int32_t recordCount = 3; NSArray *storagesToTest = [self storagesToTestWithBucketSize:bucketSize recordCount:recordCount]; for (id<LogStorage> storage in storagesToTest) { LogRecord *record = [LogTestHelper defaultLogRecord]; int32_t insertionCount = 7; int32_t iter = insertionCount; while (iter-- > 0) { [storage addLogRecord:record]; } LogBucket *removingBucket = [storage getNextBucket]; insertionCount -= [[removingBucket logRecords] count]; [storage removeBucketWithId:[removingBucket bucketId]]; removingBucket = [storage getNextBucket]; insertionCount -= [[removingBucket logRecords] count]; [storage removeBucketWithId:[removingBucket bucketId]]; LogBucket *leftBucket = [storage getNextBucket]; XCTAssertTrue([[leftBucket logRecords] count] == insertionCount, @"Failure for storage: %@", [(id)storage class]); [storage close]; } } - (void)testComplexRemoval { int64_t bucketSize = 9; int32_t recordCount = 3; NSArray *storagesToTest = [self storagesToTestWithBucketSize:bucketSize recordCount:recordCount]; for (id<LogStorage> storage in storagesToTest) { LogRecord *record = [LogTestHelper defaultLogRecord]; int32_t insertionCount = 8; int32_t iter = insertionCount; while (iter-- > 0) { [storage addLogRecord:record]; } LogBucket *removingBucket1 = [storage getNextBucket]; insertionCount -= [[removingBucket1 logRecords] count]; LogBucket *removingBucket2 = [storage getNextBucket]; insertionCount -= [[removingBucket2 logRecords] count]; LogBucket *removingBucket3 = [storage getNextBucket]; insertionCount -= [[removingBucket3 logRecords] count]; [storage removeBucketWithId:[removingBucket2 bucketId]]; [storage rollbackBucketWithId:[removingBucket1 bucketId]]; insertionCount += [[removingBucket1 logRecords] count]; LogBucket *leftBucket1 = [storage getNextBucket]; LogBucket *leftBucket2 = [storage getNextBucket]; NSInteger leftSize = [[leftBucket1 logRecords] count]; if (leftBucket2) leftSize += [[leftBucket2 logRecords] count]; XCTAssertEqual(leftSize, insertionCount, @"Failure for storage: %@", [(id)storage class]); [storage close]; } } - (void)testLogStorageCountAndVolume { int64_t bucketSize = 9; int32_t recordCount = 3; NSArray *storagesToTest = [self storagesToTestWithBucketSize:bucketSize recordCount:recordCount]; for (id<LogStorage> storage in storagesToTest) { LogRecord *record = [LogTestHelper defaultLogRecord]; int32_t insertionCount = 9; int32_t receivedCount = 0; int32_t iter = insertionCount; while (iter-- > 0) { [storage addLogRecord:record]; } LogBucket *logBucket = [storage getNextBucket]; receivedCount = [self addRecordCountIfNotEmpty:receivedCount toLogBucket:logBucket]; XCTAssertEqual(insertionCount - receivedCount, [[storage getStatus] getRecordCount], @"Failure for storage: %@", [(id)storage class]); XCTAssertEqual((insertionCount - receivedCount) * RECORD_PAYLOAD_SIZE, [[storage getStatus] getConsumedVolume], @"Failure for storage: %@", [(id)storage class]); logBucket = [storage getNextBucket]; receivedCount = [self addRecordCountIfNotEmpty:receivedCount toLogBucket:logBucket]; XCTAssertEqual(insertionCount - receivedCount, [[storage getStatus] getRecordCount], @"Failure for storage: %@", [(id)storage class]); XCTAssertEqual((insertionCount - receivedCount) * RECORD_PAYLOAD_SIZE, [[storage getStatus] getConsumedVolume], @"Failure for storage: %@", [(id)storage class]); logBucket = [storage getNextBucket]; receivedCount = [self addRecordCountIfNotEmpty:receivedCount toLogBucket:logBucket]; XCTAssertEqual(insertionCount - receivedCount, [[storage getStatus] getRecordCount], @"Failure for storage: %@", [(id)storage class]); XCTAssertEqual((insertionCount - receivedCount) * RECORD_PAYLOAD_SIZE, [[storage getStatus] getConsumedVolume], @"Failure for storage: %@", [(id)storage class]); [storage rollbackBucketWithId:[logBucket bucketId]]; receivedCount -= [[logBucket logRecords] count]; XCTAssertEqual(insertionCount - receivedCount, [[storage getStatus] getRecordCount], @"Failure for storage: %@", [(id)storage class]); XCTAssertEqual((insertionCount - receivedCount) * RECORD_PAYLOAD_SIZE, [[storage getStatus] getConsumedVolume], @"Failure for storage: %@", [(id)storage class]); } } - (void)helpAddingRecordCount:(int32_t)addedCount maxBucketSize:(int32_t)maxBucketSize maxRecordCount:(int32_t)maxRecordCount expectedCount:(int32_t)expectedCount { NSArray *storagesToTest = [self storagesToTestWithBucketSize:maxBucketSize recordCount:maxRecordCount]; for (id<LogStorage> storage in storagesToTest) { LogRecord *record = [LogTestHelper defaultLogRecord]; NSMutableArray *expectedArray = [NSMutableArray array]; while (addedCount-- > 0) { [storage addLogRecord:record]; } while (expectedCount-- > 0) { [expectedArray addObject:record]; } LogBucket *group = [storage getNextBucket]; NSArray *actualArray = [group logRecords]; XCTAssertTrue([expectedArray count] == [actualArray count], @"Failure for storage: %@", [(id)storage class]); for (int i = 0; i < [expectedArray count]; i++) { LogRecord *expected = expectedArray[i]; LogRecord *actual = actualArray[i]; XCTAssertTrue([expected getSize] == [actual getSize], @"Failure for storage: %@", [(id)storage class]); XCTAssertEqualObjects([expected data], [actual data], @"Failure for storage: %@", [(id)storage class]); } [storage close]; } } - (int32_t)addRecordCountIfNotEmpty:(int32_t)count toLogBucket:(LogBucket *)logBucket { if (logBucket && [[logBucket logRecords] count] > 0) { count += [[logBucket logRecords] count]; } return count; } - (int64_t)getLogBucketSize:(LogBucket *)logBucket { int64_t size = 0; for (LogRecord *record in [logBucket logRecords]) { size += [record getSize]; } return size; } @end
{'content_hash': 'd8835ceea8f9d8faefaf3b630d2e1ec3', 'timestamp': '', 'source': 'github', 'line_count': 327, 'max_line_length': 131, 'avg_line_length': 39.63914373088685, 'alnum_prop': 0.634778583551921, 'repo_name': 'aglne/kaa', 'id': '219c55791e6e3ca1453d9f185846bd17c1dafc91', 'size': '13568', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'client/client-multi/client-objective-c/KaaTests/logging/storage/CommonLogStorageTests.m', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '19815'}, {'name': 'Arduino', 'bytes': '22520'}, {'name': 'Batchfile', 'bytes': '21336'}, {'name': 'C', 'bytes': '6219408'}, {'name': 'C++', 'bytes': '1729698'}, {'name': 'CMake', 'bytes': '74157'}, {'name': 'CSS', 'bytes': '23111'}, {'name': 'HTML', 'bytes': '6338'}, {'name': 'Java', 'bytes': '10478878'}, {'name': 'JavaScript', 'bytes': '4669'}, {'name': 'Makefile', 'bytes': '15221'}, {'name': 'Objective-C', 'bytes': '305678'}, {'name': 'Python', 'bytes': '128276'}, {'name': 'Shell', 'bytes': '185517'}, {'name': 'Thrift', 'bytes': '21163'}, {'name': 'XSLT', 'bytes': '4062'}]}
package com.hazelcast.jet.impl.execution.init; import com.hazelcast.cluster.Address; import com.hazelcast.internal.cluster.MemberInfo; import com.hazelcast.internal.cluster.impl.MembersView; import com.hazelcast.internal.partition.IPartitionService; import com.hazelcast.jet.JetInstance; import com.hazelcast.jet.config.EdgeConfig; import com.hazelcast.jet.config.JobConfig; import com.hazelcast.jet.core.DAG; import com.hazelcast.jet.core.Edge; import com.hazelcast.jet.core.ProcessorMetaSupplier; import com.hazelcast.jet.core.ProcessorSupplier; import com.hazelcast.jet.core.TopologyChangedException; import com.hazelcast.jet.core.Vertex; import com.hazelcast.jet.impl.execution.init.Contexts.MetaSupplierCtx; import com.hazelcast.logging.ILogger; import com.hazelcast.spi.impl.NodeEngine; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.function.Function; import static com.hazelcast.jet.impl.util.ExceptionUtil.sneakyThrow; import static com.hazelcast.jet.impl.util.PrefixedLogger.prefix; import static com.hazelcast.jet.impl.util.PrefixedLogger.prefixedLogger; import static com.hazelcast.jet.impl.util.Util.checkSerializable; import static com.hazelcast.jet.impl.util.Util.getJetInstance; import static com.hazelcast.jet.impl.util.Util.toList; import static java.util.stream.Collectors.toList; public final class ExecutionPlanBuilder { private ExecutionPlanBuilder() { } public static Map<MemberInfo, ExecutionPlan> createExecutionPlans( NodeEngine nodeEngine, MembersView membersView, DAG dag, long jobId, long executionId, JobConfig jobConfig, long lastSnapshotId ) { final JetInstance instance = getJetInstance(nodeEngine); final int defaultParallelism = instance.getConfig().getInstanceConfig().getCooperativeThreadCount(); final Collection<MemberInfo> members = new HashSet<>(membersView.size()); final Address[] partitionOwners = new Address[nodeEngine.getPartitionService().getPartitionCount()]; initPartitionOwnersAndMembers(nodeEngine, membersView, members, partitionOwners); final List<Address> addresses = toList(members, MemberInfo::getAddress); final int clusterSize = members.size(); final boolean isJobDistributed = clusterSize > 1; final EdgeConfig defaultEdgeConfig = instance.getConfig().getDefaultEdgeConfig(); final Map<MemberInfo, ExecutionPlan> plans = new HashMap<>(); int memberIndex = 0; for (MemberInfo member : members) { plans.put(member, new ExecutionPlan(partitionOwners, jobConfig, lastSnapshotId, memberIndex++, clusterSize)); } final Map<String, Integer> vertexIdMap = assignVertexIds(dag); for (Entry<String, Integer> entry : vertexIdMap.entrySet()) { final Vertex vertex = dag.getVertex(entry.getKey()); final ProcessorMetaSupplier metaSupplier = vertex.getMetaSupplier(); final int vertexId = entry.getValue(); // The local parallelism determination here is effective only // in jobs submitted as DAG. Otherwise, in jobs submitted as // pipeline, we are already doing this determination while // converting it to DAG and there is no vertex left as LP=-1. final int localParallelism = vertex.determineLocalParallelism(defaultParallelism); final int totalParallelism = localParallelism * clusterSize; final List<EdgeDef> inbound = toEdgeDefs(dag.getInboundEdges(vertex.getName()), defaultEdgeConfig, e -> vertexIdMap.get(e.getSourceName()), isJobDistributed); final List<EdgeDef> outbound = toEdgeDefs(dag.getOutboundEdges(vertex.getName()), defaultEdgeConfig, e -> vertexIdMap.get(e.getDestName()), isJobDistributed); String prefix = prefix(jobConfig.getName(), jobId, vertex.getName(), "#PMS"); ILogger logger = prefixedLogger(nodeEngine.getLogger(metaSupplier.getClass()), prefix); try { metaSupplier.init(new MetaSupplierCtx(instance, jobId, executionId, jobConfig, logger, vertex.getName(), localParallelism, totalParallelism, clusterSize, jobConfig.getProcessingGuarantee())); } catch (Exception e) { throw sneakyThrow(e); } Function<? super Address, ? extends ProcessorSupplier> procSupplierFn = metaSupplier.get(addresses); for (Entry<MemberInfo, ExecutionPlan> e : plans.entrySet()) { final ProcessorSupplier processorSupplier = procSupplierFn.apply(e.getKey().getAddress()); checkSerializable(processorSupplier, "ProcessorSupplier in vertex '" + vertex.getName() + '\''); final VertexDef vertexDef = new VertexDef(vertexId, vertex.getName(), processorSupplier, localParallelism); vertexDef.addInboundEdges(inbound); vertexDef.addOutboundEdges(outbound); e.getValue().addVertex(vertexDef); } } return plans; } private static Map<String, Integer> assignVertexIds(DAG dag) { Map<String, Integer> vertexIdMap = new LinkedHashMap<>(); final int[] vertexId = {0}; dag.forEach(v -> vertexIdMap.put(v.getName(), vertexId[0]++)); return vertexIdMap; } private static List<EdgeDef> toEdgeDefs( List<Edge> edges, EdgeConfig defaultEdgeConfig, Function<Edge, Integer> oppositeVtxId, boolean isJobDistributed ) { return edges.stream() .map(edge -> new EdgeDef(edge, edge.getConfig() == null ? defaultEdgeConfig : edge.getConfig(), oppositeVtxId.apply(edge), isJobDistributed)) .collect(toList()); } private static void initPartitionOwnersAndMembers(NodeEngine nodeEngine, MembersView membersView, Collection<MemberInfo> members, Address[] partitionOwners) { IPartitionService partitionService = nodeEngine.getPartitionService(); for (int partitionId = 0; partitionId < partitionOwners.length; partitionId++) { Address address = partitionService.getPartitionOwnerOrWait(partitionId); MemberInfo member; if ((member = membersView.getMember(address)) == null) { // Address in partition table doesn't exist in member list, // it has just joined the cluster. throw new TopologyChangedException("Topology changed, " + address + " is not in original member list"); } // add member to known members members.add(member); partitionOwners[partitionId] = address; } } }
{'content_hash': '42d441c409103ac09ada4474c60d79f7', 'timestamp': '', 'source': 'github', 'line_count': 138, 'max_line_length': 123, 'avg_line_length': 51.30434782608695, 'alnum_prop': 0.6754237288135593, 'repo_name': 'gurbuzali/hazelcast-jet', 'id': '44001b8fb20be505e868a470c66767db7404bcb2', 'size': '7705', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'hazelcast-jet-core/src/main/java/com/hazelcast/jet/impl/execution/init/ExecutionPlanBuilder.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '1568'}, {'name': 'Java', 'bytes': '3684048'}, {'name': 'Shell', 'bytes': '12114'}]}
<?php namespace Zend\Feed\Reader\Feed\Atom; use DOMElement; use DOMXPath; use Zend\Feed\Reader; use Zend\Feed\Reader\Feed; /** */ class Source extends Feed\Atom { /** * Constructor: Create a Source object which is largely just a normal * Zend\Feed\Reader\AbstractFeed object only designed to retrieve feed level * metadata from an Atom entry's source element. * * @param DOMElement $source * @param string $xpathPrefix Passed from parent Entry object * @param string $type Nearly always Atom 1.0 */ public function __construct(DOMElement $source, $xpathPrefix, $type = Reader\Reader::TYPE_ATOM_10) { $this->domDocument = $source->ownerDocument; $this->xpath = new DOMXPath($this->domDocument); $this->data['type'] = $type; $this->registerNamespaces(); $this->loadExtensions(); $manager = Reader\Reader::getExtensionManager(); $extensions = array('Atom\Feed', 'DublinCore\Feed'); foreach ($extensions as $name) { $extension = $manager->get($name); $extension->setDomDocument($this->domDocument); $extension->setType($this->data['type']); $extension->setXpath($this->xpath); $this->extensions[$name] = $extension; } foreach ($this->extensions as $extension) { $extension->setXpathPrefix(rtrim($xpathPrefix, '/') . '/atom:source'); } } /** * Since this is not an Entry carrier but a vehicle for Feed metadata, any * applicable Entry methods are stubbed out and do nothing. */ /** * @return void */ public function count() {} /** * @return void */ public function current() {} /** * @return void */ public function key() {} /** * @return void */ public function next() {} /** * @return void */ public function rewind() {} /** * @return void */ public function valid() {} /** * @return void */ protected function indexEntries() {} }
{'content_hash': 'b787fe123a45381a8c9fcc3b32015492', 'timestamp': '', 'source': 'github', 'line_count': 88, 'max_line_length': 102, 'avg_line_length': 24.920454545454547, 'alnum_prop': 0.555859553123575, 'repo_name': 'trivan/ZF2-Dynamic-Routing', 'id': '2cd3ca12415d0a851488b10d9f50ea894214a8c4', 'size': '2501', 'binary': False, 'copies': '30', 'ref': 'refs/heads/master', 'path': 'vendor/ZF2/library/Zend/Feed/Reader/Feed/Atom/Source.php', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '137753'}, {'name': 'JavaScript', 'bytes': '58458'}, {'name': 'PHP', 'bytes': '10781'}, {'name': 'Perl', 'bytes': '175'}]}
package v1 import ( operatorv1 "github.com/openshift/api/operator/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) // OpenShiftControllerManagerSpecApplyConfiguration represents an declarative configuration of the OpenShiftControllerManagerSpec type for use // with apply. type OpenShiftControllerManagerSpecApplyConfiguration struct { OperatorSpecApplyConfiguration `json:",inline"` } // OpenShiftControllerManagerSpecApplyConfiguration constructs an declarative configuration of the OpenShiftControllerManagerSpec type for use with // apply. func OpenShiftControllerManagerSpec() *OpenShiftControllerManagerSpecApplyConfiguration { return &OpenShiftControllerManagerSpecApplyConfiguration{} } // WithManagementState sets the ManagementState field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ManagementState field is set to the value of the last call. func (b *OpenShiftControllerManagerSpecApplyConfiguration) WithManagementState(value operatorv1.ManagementState) *OpenShiftControllerManagerSpecApplyConfiguration { b.ManagementState = &value return b } // WithLogLevel sets the LogLevel field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the LogLevel field is set to the value of the last call. func (b *OpenShiftControllerManagerSpecApplyConfiguration) WithLogLevel(value operatorv1.LogLevel) *OpenShiftControllerManagerSpecApplyConfiguration { b.LogLevel = &value return b } // WithOperatorLogLevel sets the OperatorLogLevel field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the OperatorLogLevel field is set to the value of the last call. func (b *OpenShiftControllerManagerSpecApplyConfiguration) WithOperatorLogLevel(value operatorv1.LogLevel) *OpenShiftControllerManagerSpecApplyConfiguration { b.OperatorLogLevel = &value return b } // WithUnsupportedConfigOverrides sets the UnsupportedConfigOverrides field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the UnsupportedConfigOverrides field is set to the value of the last call. func (b *OpenShiftControllerManagerSpecApplyConfiguration) WithUnsupportedConfigOverrides(value runtime.RawExtension) *OpenShiftControllerManagerSpecApplyConfiguration { b.UnsupportedConfigOverrides = &value return b } // WithObservedConfig sets the ObservedConfig field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ObservedConfig field is set to the value of the last call. func (b *OpenShiftControllerManagerSpecApplyConfiguration) WithObservedConfig(value runtime.RawExtension) *OpenShiftControllerManagerSpecApplyConfiguration { b.ObservedConfig = &value return b }
{'content_hash': '16f101ebcf47019935d1be1c26688dda', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 169, 'avg_line_length': 55.43103448275862, 'alnum_prop': 0.8332814930015552, 'repo_name': 'openshift/origin', 'id': '01a66394f7470886abdae39091a7b208e8b88f93', 'size': '3274', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'vendor/github.com/openshift/client-go/operator/applyconfigurations/operator/v1/openshiftcontrollermanagerspec.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '921'}, {'name': 'Go', 'bytes': '4434721'}, {'name': 'HTML', 'bytes': '23575'}, {'name': 'Makefile', 'bytes': '2855'}, {'name': 'Shell', 'bytes': '225125'}]}
 $(document).ready(function () { window.setTimeout(SetImageSize, 100); $("#TreeView1").treeview(); window.setTimeout(function () { ScrollIntoView($("UL#TreeView1"), $(".selected")); }, 0); window.setTimeout(function () { ScrollIntoView($(".statisentry"), $(".checked")); }, 0); }); function SetImageSize() { var oldwidth = $("#HiddenField_imageWidth").val(); if (oldwidth == "") { //var right = $("#Chart1").parent()[0]; //$("#HiddenField_imageWidth").val(right.clientWidth - 16); var width = $("#Chart1").parent().width(); var height = $("UL#TreeView1").parent().height() + $(".statisentry").parent().height() - $("#DropDownList_chartType").height(); $("#HiddenField_imageWidth").val(width + "," + height); if (oldwidth == "") { // LangPostBack(); $(".treebutton.hidden").trigger("click"); } } } function SetImageSize0() { var right = $("#Chart1").parent()[0]; var chart = document.getElementById("Chart1"); var width = right.clientWidth - 16; chart.style.height = Math.round(width * 0.46) + "px"; // chart.style.height = "460px"; chart.style.width = width + "px"; } function SetImageSize1() { var header_height = 0; if ($('TABLE.title:visible').length > 0) header_height = $('TABLE.title:visible').height(); var columnbar = $('TABLE.columnbar')[0]; var left = $("td.left")[0]; var message = document.getElementById("Chart1"); // message.style.height = (document.documentElement.clientHeight - header_height - columnbar.clientHeight - 30) + "px"; message.style.width = (document.documentElement.clientWidth - left.clientWidth - 40 - 16) + "px"; }
{'content_hash': '2c0ca332cdc27d645339ea360ec6925b', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 135, 'avg_line_length': 32.425925925925924, 'alnum_prop': 0.5853797829811537, 'repo_name': 'renyh1013/dp2', 'id': '48ee09fa80a7fe0ed338bcbd0d8613d8c9cfe6ad', 'size': '1753', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'dp2OPAC/statischart.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '219049'}, {'name': 'Batchfile', 'bytes': '4200'}, {'name': 'C#', 'bytes': '44914579'}, {'name': 'CSS', 'bytes': '806240'}, {'name': 'HTML', 'bytes': '1339609'}, {'name': 'JavaScript', 'bytes': '379570'}, {'name': 'PHP', 'bytes': '36009'}, {'name': 'PowerShell', 'bytes': '87046'}, {'name': 'Roff', 'bytes': '3758'}, {'name': 'Smalltalk', 'bytes': '39606'}, {'name': 'XSLT', 'bytes': '64230'}]}
using System; using System.Web.Mvc; namespace SeoPack.Url { [AttributeUsage(AttributeTargets.Method)] public class CanonicalUrlAttribute : ActionFilterAttribute { private string _urlPath; public CanonicalUrlAttribute(string urlPath) { if (string.IsNullOrEmpty(urlPath)) { throw new ArgumentException("url not set"); } _urlPath = urlPath; } public CanonicalUrlAttribute() { } public override void OnActionExecuting(ActionExecutingContext filterContext) { string fullUrl; if (string.IsNullOrEmpty(_urlPath)) { fullUrl = filterContext.RequestContext.HttpContext.Request.Url.AbsoluteUri; var query = filterContext.RequestContext.HttpContext.Request.Url.Query; if (query.Length > 0) { fullUrl = fullUrl.Replace(query, ""); } } else { var currentPageUrl = filterContext.RequestContext.HttpContext.Request.Url; fullUrl = string.Format("{0}://{1}/{2}", currentPageUrl.Scheme, currentPageUrl.Authority, _urlPath.Trim('/')); if (fullUrl.IndexOf("{") != -1) { foreach (var actionParam in filterContext.ActionParameters) { UpdateUrlPlaceholders(actionParam.Key, actionParam.Value, ref fullUrl); } } } var canonicalUrl = new CanonicalUrl(fullUrl).Value.AbsoluteUri; filterContext.RequestContext.HttpContext.Items["CanonicalUrl"] = canonicalUrl; base.OnActionExecuting(filterContext); } private void UpdateUrlPlaceholders(string key, object value, ref string fullUrl) { var type = value.GetType(); if (!type.Equals(typeof(string)) && !type.IsPrimitive) { foreach (var property in type.GetProperties()) { var propertyValue = property.GetValue(value, null); if (propertyValue == null) continue; UpdateUrlPlaceholders(property.Name, propertyValue, ref fullUrl); } } else { fullUrl = fullUrl.Replace("{" + key + "}", value.ToString(), StringComparison.InvariantCultureIgnoreCase); } } } }
{'content_hash': '6cacb9ea6421a90f3351c62745db7110', 'timestamp': '', 'source': 'github', 'line_count': 78, 'max_line_length': 95, 'avg_line_length': 33.14102564102564, 'alnum_prop': 0.5323017408123791, 'repo_name': 'oopanuga/Seo-Pack', 'id': '8fcaff24675eeb6624eab5863408c0062e624c82', 'size': '2587', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SeoPack/Url/CanonicalUrlAttribute.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '191'}, {'name': 'C#', 'bytes': '144282'}]}
package directionsreduction; import java.util.Arrays; /** * Created by Iryna Guzenko on 02.12.2015. */ public class Directions { public static String[] dirReduc(String[] arr) { StringBuilder route = new StringBuilder(); Arrays.stream(arr).forEachOrdered(route::append); String newRoute = getIt(route); if (newRoute.isEmpty()) return new String[0]; return newRoute.replaceAll("TH", "TH ").replaceAll("ST", "ST ").trim().split(" "); } public static void main(String[] args) { String[] arr = new String[]{"NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH"}; Arrays.stream(dirReduc(arr)).forEachOrdered(System.out::println); System.out.println("."); } private static String getIt(StringBuilder route) { StringBuilder newRoute = new StringBuilder(); Arrays.stream(route.toString().split("(NORTHSOUTH|SOUTHNORTH|WESTEAST|EASTWEST)")) .forEachOrdered(newRoute::append); if (!route.toString().equals(newRoute.toString())) return getIt(newRoute); return route.toString(); } }
{'content_hash': '16aeefbd9871ee7332627f035e26d6bc', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 90, 'avg_line_length': 36.96666666666667, 'alnum_prop': 0.6384129846708747, 'repo_name': 'irynaguzenko/codewars', 'id': '1b2918492aa2c386b7e3f15f8891296ae32dcf91', 'size': '1109', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/directionsreduction/Directions.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '39683'}, {'name': 'JavaScript', 'bytes': '681'}]}
namespace Microsoft.Azure.Management.Network.Models { using Azure; using Management; using Network; /// <summary> /// Defines values for AssociationType. /// </summary> public static class AssociationType { public const string Associated = "Associated"; public const string Contains = "Contains"; } }
{'content_hash': '99d6cace8025f3603ec01b20d33021c2', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 54, 'avg_line_length': 22.1875, 'alnum_prop': 0.647887323943662, 'repo_name': 'JasonYang-MSFT/azure-sdk-for-net', 'id': '499473b5658476bdf9168a5eaca88d12fee770a2', 'size': '674', 'binary': False, 'copies': '11', 'ref': 'refs/heads/vs17Dev', 'path': 'src/SDKs/Network/Management.Network/Generated/Models/AssociationType.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '118'}, {'name': 'Batchfile', 'bytes': '33797'}, {'name': 'C#', 'bytes': '49260345'}, {'name': 'CSS', 'bytes': '685'}, {'name': 'JavaScript', 'bytes': '7875'}, {'name': 'PowerShell', 'bytes': '24250'}, {'name': 'Shell', 'bytes': '20492'}, {'name': 'XSLT', 'bytes': '6114'}]}
export declare class TextBox { private static div_work_area_; private static dom_style_tag_; private static textbox_elem_count; private static lang_; private static speeds_; static global_write_by_line_: boolean; static global_speed_: number | null; private static tag_keywords; private static self_closing_tags; private static re_str_tags_; private static regex_; private textbox_name; private textbox_elem; private file_content; private building_style; private style_text; private building_script; private script_text; private dump_style; private dump_script; private write_by_line; private speed; private forced_speed; private open_tags; private cur_str; private str_to_render; private advance_chars; private next_textbox; _expanded: boolean; constructor(file_name: string); static setLang_(lang: string): void; static setSpeeds_(speeds: { [key: string]: number; }): void; setSpeed(speeds_index: string): void; setForcedSpeed(speeds_index: string): void; expanded: boolean; run(): { textbox: string; delay: number; }; private renderContent(); private processTags(); private processTextBlock(text); private dumpTextBlock(); getFileContent(): Promise<string>; private determineSpeed(); scrollToBottom(): void; private static addStyleTags_(text); private static addScriptTags_(text); private static createTextBoxElem_(elem_id); }
{'content_hash': '816f258bafbe62ff0c51defc4939b4f3', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 47, 'avg_line_length': 29.169811320754718, 'alnum_prop': 0.6714100905562742, 'repo_name': 'PedroHenriques/www.pedrojhenriques.com', 'id': '86ba794430947992870397c7d99df1ef936ed9ca', 'size': '1546', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'assets/ts/declarations/classes/TextBox.d.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2268'}, {'name': 'PHP', 'bytes': '19306'}, {'name': 'TypeScript', 'bytes': '60605'}]}
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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. /** * @fileoverview Implementation of a progress bar. * * @see ../demos/progressbar.html */ goog.provide('goog.ui.ProgressBar'); goog.provide('goog.ui.ProgressBar.Orientation'); goog.require('goog.dom'); goog.require('goog.dom.a11y'); goog.require('goog.dom.classes'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('goog.ui.Component'); goog.require('goog.ui.Component.EventType'); goog.require('goog.ui.RangeModel'); goog.require('goog.userAgent'); /** * This creates a progress bar object. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. * @constructor * @extends {goog.ui.Component} */ goog.ui.ProgressBar = function(opt_domHelper) { goog.ui.Component.call(this, opt_domHelper); /** * The underlying data model for the progress bar. * @type {goog.ui.RangeModel} * @private */ this.rangeModel_ = new goog.ui.RangeModel; goog.events.listen(this.rangeModel_, goog.ui.Component.EventType.CHANGE, this.handleChange_, false, this); }; goog.inherits(goog.ui.ProgressBar, goog.ui.Component); /** * Enum for representing the orientation of the progress bar. * * @enum {string} */ goog.ui.ProgressBar.Orientation = { VERTICAL: 'vertical', HORIZONTAL: 'horizontal' }; /** * Map from progress bar orientation to CSS class names. * @type {Object} * @private */ goog.ui.ProgressBar.ORIENTATION_TO_CSS_NAME_ = {}; goog.ui.ProgressBar.ORIENTATION_TO_CSS_NAME_[ goog.ui.ProgressBar.Orientation.VERTICAL] = goog.getCssName('progress-bar-vertical'); goog.ui.ProgressBar.ORIENTATION_TO_CSS_NAME_[ goog.ui.ProgressBar.Orientation.HORIZONTAL] = goog.getCssName('progress-bar-horizontal'); /** * Creates the DOM nodes needed for the progress bar */ goog.ui.ProgressBar.prototype.createDom = function() { this.thumbElement_ = this.createThumb_(); var cs = goog.ui.ProgressBar.ORIENTATION_TO_CSS_NAME_[this.orientation_]; this.setElementInternal( this.getDomHelper().createDom('div', cs, this.thumbElement_)); this.setValueState_(); this.setMinimumState_(); this.setMaximumState_(); }; /** * Called when the DOM for the component is for sure in the document. */ goog.ui.ProgressBar.prototype.enterDocument = function() { goog.ui.ProgressBar.superClass_.enterDocument.call(this); this.attachEvents_(); this.updateUi_(); // state live = polite will notify the user of updates, // but will not interrupt ongoing feedback goog.dom.a11y.setRole(this.getElement(), 'progressbar'); goog.dom.a11y.setState(this.getElement(), 'live', 'polite'); }; /** * Called when the DOM for the component is for sure in the document. */ goog.ui.ProgressBar.prototype.exitDocument = function() { goog.ui.ProgressBar.superClass_.exitDocument.call(this); this.detachEvents_(); }; /** * This creates the thumb element. * @private * @return {HTMLDivElement} The created thumb element. */ goog.ui.ProgressBar.prototype.createThumb_ = function() { return /** @type {HTMLDivElement} */ (this.getDomHelper().createDom('div', goog.getCssName('progress-bar-thumb'))); }; /** * Adds the initial event listeners to the element. * @private */ goog.ui.ProgressBar.prototype.attachEvents_ = function() { if (goog.userAgent.IE && goog.userAgent.VERSION < 7) { goog.events.listen(this.getElement(), goog.events.EventType.RESIZE, this.updateUi_, false, this); } }; /** * Adds the initial event listeners to the element. * @private */ goog.ui.ProgressBar.prototype.detachEvents_ = function() { if (goog.userAgent.IE && goog.userAgent.VERSION < 7) { goog.events.unlisten(this.getElement(), goog.events.EventType.RESIZE, this.updateUi_, false, this); } }; /** * Decorates an existing HTML DIV element as a progress bar input. If the * element contains a child with a class name of 'progress-bar-thumb' that will * be used as the thumb. * @param {HTMLElement} element The HTML element to decorate. */ goog.ui.ProgressBar.prototype.decorateInternal = function(element) { goog.ui.ProgressBar.superClass_.decorateInternal.call(this, element); goog.dom.classes.add(this.getElement(), goog.ui.ProgressBar. ORIENTATION_TO_CSS_NAME_[this.orientation_]); // find thumb var thumb = goog.dom.getElementsByTagNameAndClass( null, goog.getCssName('progress-bar-thumb'), this.getElement())[0]; if (!thumb) { thumb = this.createThumb_(); this.getElement().appendChild(thumb); } this.thumbElement_ = thumb; }; /** * @return {number} The value. */ goog.ui.ProgressBar.prototype.getValue = function() { return this.rangeModel_.getValue(); }; /** * Sets the value * @param {number} v The value. */ goog.ui.ProgressBar.prototype.setValue = function(v) { this.rangeModel_.setValue(v); if (this.getElement()) { this.setValueState_(); } }; /** * Sets the state for a11y of the current value. * @private */ goog.ui.ProgressBar.prototype.setValueState_ = function() { goog.dom.a11y.setState(this.getElement(), 'valuenow', this.getValue()); }; /** * @return {number} The minimum value. */ goog.ui.ProgressBar.prototype.getMinimum = function() { return this.rangeModel_.getMinimum(); }; /** * Sets the minimum number * @param {number} v The minimum value. */ goog.ui.ProgressBar.prototype.setMinimum = function(v) { this.rangeModel_.setMinimum(v); if (this.getElement()) { this.setMinimumState_(); } }; /** * Sets the state for a11y of the minimum value. * @private */ goog.ui.ProgressBar.prototype.setMinimumState_ = function() { goog.dom.a11y.setState(this.getElement(), 'valuemin', this.getMinimum()); }; /** * @return {number} The maximum value. */ goog.ui.ProgressBar.prototype.getMaximum = function() { return this.rangeModel_.getMaximum(); }; /** * Sets the maximum number * @param {number} v The maximum value. */ goog.ui.ProgressBar.prototype.setMaximum = function(v) { this.rangeModel_.setMaximum(v); if (this.getElement()) { this.setMaximumState_(); } }; /** * Sets the state for a11y of the maximum valiue. * @private */ goog.ui.ProgressBar.prototype.setMaximumState_ = function() { goog.dom.a11y.setState(this.getElement(), 'valuemax', this.getMaximum()); }; /** * * @type {goog.ui.ProgressBar.Orientation} * @private */ goog.ui.ProgressBar.prototype.orientation_ = goog.ui.ProgressBar.Orientation.HORIZONTAL; /** * Call back when the internal range model changes * @param {goog.events.Event} e The event object. * @private */ goog.ui.ProgressBar.prototype.handleChange_ = function(e) { this.updateUi_(); this.dispatchEvent(goog.ui.Component.EventType.CHANGE); }; /** * This is called when we need to update the size of the thumb. This happens * when first created as well as when the value and the orientation changes. * @private */ goog.ui.ProgressBar.prototype.updateUi_ = function() { if (this.thumbElement_) { var min = this.getMinimum(); var max = this.getMaximum(); var val = this.getValue(); var ratio = (val - min) / (max - min); var size = Math.round(ratio * 100); if (this.orientation_ == goog.ui.ProgressBar.Orientation.VERTICAL) { // Note(user): IE up to version 6 has some serious computation bugs when // using percentages or bottom. We therefore first set the height to // 100% and measure that and base the top and height on that size instead. if (goog.userAgent.IE && goog.userAgent.VERSION < 7) { this.thumbElement_.style.top = 0; this.thumbElement_.style.height = '100%'; var h = this.thumbElement_.offsetHeight; var bottom = Math.round(ratio * h); this.thumbElement_.style.top = h - bottom + 'px'; this.thumbElement_.style.height = bottom + 'px'; } else { this.thumbElement_.style.top = (100 - size) + '%'; this.thumbElement_.style.height = size + '%'; } } else { this.thumbElement_.style.width = size + '%'; } } }; /** * This is called when we need to setup the UI sizes and positions. This * happens when we create the element and when we change the orientation. * @private */ goog.ui.ProgressBar.prototype.initializeUi_ = function() { var tStyle = this.thumbElement_.style; if (this.orientation_ == goog.ui.ProgressBar.Orientation.VERTICAL) { tStyle.left = 0; tStyle.width = '100%'; } else { tStyle.top = tStyle.left = 0; tStyle.height = '100%'; } }; /** * Changes the orientation * @param {goog.ui.ProgressBar.Orientation} orient The orientation. */ goog.ui.ProgressBar.prototype.setOrientation = function(orient) { if (this.orientation_ != orient) { var oldCss = goog.ui.ProgressBar.ORIENTATION_TO_CSS_NAME_[this.orientation_]; var newCss = goog.ui.ProgressBar.ORIENTATION_TO_CSS_NAME_[orient]; this.orientation_ = orient; // Update the DOM if (this.getElement()) { goog.dom.classes.swap(this.getElement(), oldCss, newCss); this.initializeUi_(); this.updateUi_(); } } }; /** * @return {goog.ui.ProgressBar.Orientation} The orientation of the * progress bar. */ goog.ui.ProgressBar.prototype.getOrientation = function() { return this.orientation_; }; /** @inheritDoc */ goog.ui.ProgressBar.prototype.disposeInternal = function() { this.detachEvents_(); goog.ui.ProgressBar.superClass_.disposeInternal.call(this); this.thumbElement_ = null; this.rangeModel_.dispose(); }; /** * @return {?number} The step value used to determine how to round the value. */ goog.ui.ProgressBar.prototype.getStep = function() { return this.rangeModel_.getStep(); }; /** * Sets the step value. The step value is used to determine how to round the * value. * @param {?number} step The step size. */ goog.ui.ProgressBar.prototype.setStep = function(step) { this.rangeModel_.setStep(step); };
{'content_hash': '2ef89dac40892b3d01e2c5800352dded', 'timestamp': '', 'source': 'github', 'line_count': 390, 'max_line_length': 80, 'avg_line_length': 27.04871794871795, 'alnum_prop': 0.6841406768414068, 'repo_name': 'gatapia/nclosure', 'id': '55bd0a10c36fee248ea2ef27d59df99acb9ea0fe', 'size': '10549', 'binary': False, 'copies': '45', 'ref': 'refs/heads/master', 'path': 'third_party/closure-library/closure/goog/ui/progressbar.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '25148'}, {'name': 'HTML', 'bytes': '1060176'}, {'name': 'JavaScript', 'bytes': '227078'}]}
import { Observable } from '../Observable'; /** * @throws {ArgumentOutOfRangeError} When using `takeLast(i)`, it delivers an * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`. * @param total * @return {any} * @method takeLast * @owner Observable */ export declare function takeLast<T>(total: number): Observable<T>; export interface TakeLastSignature<T> { (total: number): Observable<T>; }
{'content_hash': 'c81f2fdb761fcc1c31cb39f4379e8a4d', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 77, 'avg_line_length': 32.53846153846154, 'alnum_prop': 0.7044917257683215, 'repo_name': 'thuongho/dream-machine', 'id': 'd953b43cfb1a1408b5b6056c7fdb800678684adb', 'size': '423', 'binary': False, 'copies': '73', 'ref': 'refs/heads/master', 'path': 'node_modules/rxjs/operator/takeLast.d.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2305'}, {'name': 'HTML', 'bytes': '5185'}, {'name': 'JavaScript', 'bytes': '13577'}, {'name': 'TypeScript', 'bytes': '7705'}]}
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flowable.engine.impl.db; import org.flowable.engine.ProcessEngines; import org.flowable.engine.common.impl.interceptor.Command; import org.flowable.engine.common.impl.interceptor.CommandConfig; import org.flowable.engine.common.impl.interceptor.CommandContext; import org.flowable.engine.common.impl.interceptor.CommandExecutor; import org.flowable.engine.impl.ProcessEngineImpl; import org.flowable.engine.impl.util.CommandContextUtil; /** * @author Tom Baeyens */ public class DbSchemaUpdate { public static void main(String[] args) { ProcessEngineImpl processEngine = (ProcessEngineImpl) ProcessEngines.getDefaultProcessEngine(); CommandExecutor commandExecutor = processEngine.getProcessEngineConfiguration().getCommandExecutor(); CommandConfig config = new CommandConfig().transactionNotSupported(); commandExecutor.execute(config, new Command<Object>() { @Override public Object execute(CommandContext commandContext) { CommandContextUtil.getProcessEngineConfiguration(commandContext).getDbSchemaManager().dbSchemaUpdate(); return null; } }); } }
{'content_hash': '4c932198607eef1e236ebc13a940f5f2', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 119, 'avg_line_length': 41.666666666666664, 'alnum_prop': 0.7462857142857143, 'repo_name': 'marcus-nl/flowable-engine', 'id': '9f42ac1e246d01518e36d15832a88ed736f35f7b', 'size': '1750', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'modules/flowable-engine/src/main/java/org/flowable/engine/impl/db/DbSchemaUpdate.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '166'}, {'name': 'CSS', 'bytes': '686223'}, {'name': 'Groovy', 'bytes': '482'}, {'name': 'HTML', 'bytes': '957634'}, {'name': 'Java', 'bytes': '27813319'}, {'name': 'JavaScript', 'bytes': '13046505'}, {'name': 'PLSQL', 'bytes': '81662'}, {'name': 'PLpgSQL', 'bytes': '9191'}, {'name': 'Shell', 'bytes': '15993'}]}
'use strict'; /** * VBO. * * @class VboBuffer * @constructor */ var VboBuffer = function(dataTarget) { if (!(this instanceof VboBuffer)) { throw new Error(Messages.CONSTRUCT_ERROR); } /** * VBO data array. * @type {TypedArray} * @default undefined */ this.dataArray; /** * VBO data array length. * @type {Number} * @default undefined */ this.dataLength; /** * VBO data array type. (5120 : signed byte), (5121 : unsigned byte), (5122 : signed short), (5123 : unsigned short), (5126 : float). * @type {Number} * @default undefined */ this.dataGlType; /** * Webgl vbo identifier. * @type {WebGLBuffer} * @default undefined */ this.key; /** * Webgl data target. It can be gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER. In WebGl2 added(gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, gl.TRANSFORM_FEEDBACK_BUFFER, gl.UNIFORM_BUFFER, gl.PIXEL_PACK_BUFFER, gl.PIXEL_UNPACK_BUFFER). * @type {Number} * @default 34962 gl.ARRAY_BUFFER */ this.dataTarget; if (dataTarget !== undefined) { this.dataTarget = dataTarget; } else { this.dataTarget = 34962; } // 34962 = gl.ARRAY_BUFFER. Default value. }; /** * Deletes all objects. * @param {VboMemoryManager} vboMemManager. */ VboBuffer.prototype.deleteGlObjects = function(vboMemManager) { if (this.key !== undefined) { var gl = vboMemManager.gl; if (this.dataTarget === gl.ARRAY_BUFFER) { vboMemManager.storeClassifiedBufferKey(gl, this.key, this.dataLength); } else if (this.dataTarget === gl.ELEMENT_ARRAY_BUFFER) { vboMemManager.storeClassifiedElementKey(gl, this.key, this.dataLength); } } this.dataArray = undefined; this.dataLength = undefined; this.dataGlType = undefined; this.key = undefined; this.dataTarget = undefined; }; /** * Sets the data array. * @param {TypedArray} dataArray The heading value in degrees. * @param {VboMemoryManager} vboMemManager. */ VboBuffer.prototype.setDataArray = function(dataArray, vboMemManager) { if (dataArray === undefined) { return; } this.dataGlType = VboBuffer.getGlTypeOfArray(dataArray); var arrayElemsCount = dataArray.length; var classifiedPosByteSize = arrayElemsCount; // Init value. if (vboMemManager.enableMemoryManagement) { classifiedPosByteSize = vboMemManager.getClassifiedBufferSize(arrayElemsCount); this.dataArray = VboBuffer.newTypedArray(classifiedPosByteSize, this.dataGlType); this.dataArray.set(dataArray); } else { this.dataArray = dataArray; } this.dataLength = arrayElemsCount; }; /** * 어떤 일을 하고 있습니까? */ VboBuffer.prototype.isReady = function(gl, vboMemManager) { if (this.key === undefined) { if (this.dataArray === undefined) { return false; } if (this.dataLength === undefined) { this.dataLength = this.dataArray.length; } this.key = vboMemManager.getClassifiedBufferKey(gl, this.dataLength); if (this.key === undefined) { return false; } gl.bindBuffer(this.dataTarget, this.key); gl.bufferData(this.dataTarget, this.dataArray, gl.STATIC_DRAW); this.dataArray = undefined; return true; } return true; }; /** * 어떤 일을 하고 있습니까? */ VboBuffer.getGlTypeOfArray = function(dataArray) { var glType = -1; if (dataArray.constructor === Float32Array) { glType = 5126; } // gl.FLOAT. else if (dataArray.constructor === Int16Array) { glType = 5122; } // gl.SHORT. else if (dataArray.constructor === Uint16Array) { glType = 5123; } // gl.UNSIGNED_SHORT. else if (dataArray.constructor === Int8Array) { glType = 5120; } // gl.BYTE. else if (dataArray.constructor === Uint8Array) { glType = 5121; } // gl.UNSIGNED_BYTE. return glType; }; /** * 어떤 일을 하고 있습니까? */ VboBuffer.newTypedArray = function(arrayLength, glType) { var typedArray; if (glType === 5126)// gl.FLOAT. { typedArray = new Float32Array(arrayLength); } else if (glType === 5122)// gl.SHORT. { typedArray = new Int16Array(arrayLength); } else if (glType === 5123)// gl.UNSIGNED_SHORT. { typedArray = new Uint16Array(arrayLength); } else if (glType === 5120)// gl.BYTE. { typedArray = new Int8Array(arrayLength); } else if (glType === 5121)// gl.UNSIGNED_BYTE. { typedArray = new Uint8Array(arrayLength); } return typedArray; };
{'content_hash': '097d689f1a8773e4afa68597ffe8eae4', 'timestamp': '', 'source': 'github', 'line_count': 170, 'max_line_length': 231, 'avg_line_length': 24.694117647058825, 'alnum_prop': 0.68532634587899, 'repo_name': 'Gaia3D/mago3djs', 'id': 'c091f6ae5321148f8e56461c35a9cd3d0350e53b', 'size': '4258', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/mago3d/core/VboBuffer.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '43838'}, {'name': 'GLSL', 'bytes': '78515'}, {'name': 'JavaScript', 'bytes': '59213287'}]}
package com.tvd12.ezyfox.monitor.test; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.util.List; public class GCMainTest { @SuppressWarnings({"unused", "BusyWait", "InfiniteLoopStatement"}) public static void main(String[] args) throws Exception { while (true) { byte[] bytes = new byte[1000000]; Thread.sleep(50); Integer abc = 10; printGc(); Thread.sleep(1000); } } public static void printGc() { List<GarbageCollectorMXBean> gcmxb = ManagementFactory.getGarbageCollectorMXBeans(); StringBuilder builder = new StringBuilder(); builder.append("count: ").append(gcmxb.size()); long time = 0; int count = 0; for (GarbageCollectorMXBean x : gcmxb) { time += x.getCollectionTime(); count += x.getCollectionCount(); } builder.append(", time: ").append(time).append(", count: ").append(count); System.out.println(builder); } }
{'content_hash': '9e4e679c1c7e1bc98f13641cfa2183e7', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 92, 'avg_line_length': 32.78787878787879, 'alnum_prop': 0.6155268022181146, 'repo_name': 'youngmonkeys/ezyfox', 'id': 'aedd44941a438de748f29e8753ab94c077b1ed25', 'size': '1082', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ezyfox-monitor/src/test/java/com/tvd12/ezyfox/monitor/test/GCMainTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '100'}, {'name': 'Java', 'bytes': '2124702'}, {'name': 'Shell', 'bytes': '138'}]}
package org.apache.druid.segment.data; import org.apache.druid.java.util.common.StringUtils; import org.apache.druid.segment.writeout.OffHeapMemorySegmentWriteOutMedium; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.Channels; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; @RunWith(Parameterized.class) public class CompressedLongsAutoEncodingSerdeTest { @Parameterized.Parameters(name = "{0} {1} {2}") public static Iterable<Object[]> compressionStrategies() { List<Object[]> data = new ArrayList<>(); for (long bpv : bitsPerValueParameters) { for (CompressionStrategy strategy : CompressionStrategy.values()) { data.add(new Object[]{bpv, strategy, ByteOrder.BIG_ENDIAN}); data.add(new Object[]{bpv, strategy, ByteOrder.LITTLE_ENDIAN}); } } return data; } private static final long[] bitsPerValueParameters = new long[]{1, 2, 4, 7, 11, 14, 18, 23, 31, 39, 46, 55, 62}; protected final CompressionFactory.LongEncodingStrategy encodingStrategy = CompressionFactory.LongEncodingStrategy.AUTO; protected final CompressionStrategy compressionStrategy; protected final ByteOrder order; protected final long bitsPerValue; public CompressedLongsAutoEncodingSerdeTest( long bitsPerValue, CompressionStrategy compressionStrategy, ByteOrder order ) { this.bitsPerValue = bitsPerValue; this.compressionStrategy = compressionStrategy; this.order = order; } @Test public void testFidelity() throws Exception { final long bound = 1L << bitsPerValue; // big enough to have at least 2 blocks, and a handful of sizes offset by 1 from each other int blockSize = 1 << 16; int numBits = (Long.SIZE - Long.numberOfLeadingZeros(1 << (bitsPerValue - 1))); double numValuesPerByte = 8.0 / (double) numBits; int numRows = (int) (blockSize * numValuesPerByte) * 2 + ThreadLocalRandom.current().nextInt(1, 101); long chunk[] = new long[numRows]; for (int i = 0; i < numRows; i++) { chunk[i] = ThreadLocalRandom.current().nextLong(bound); } testValues(chunk); numRows++; chunk = new long[numRows]; for (int i = 0; i < numRows; i++) { chunk[i] = ThreadLocalRandom.current().nextLong(bound); } testValues(chunk); } public void testValues(long[] values) throws Exception { ColumnarLongsSerializer serializer = CompressionFactory.getLongSerializer( new OffHeapMemorySegmentWriteOutMedium(), "test", order, encodingStrategy, compressionStrategy ); serializer.open(); for (long value : values) { serializer.add(value); } Assert.assertEquals(values.length, serializer.size()); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); serializer.writeTo(Channels.newChannel(baos), null); Assert.assertEquals(baos.size(), serializer.getSerializedSize()); CompressedColumnarLongsSupplier supplier = CompressedColumnarLongsSupplier.fromByteBuffer(ByteBuffer.wrap(baos.toByteArray()), order); ColumnarLongs longs = supplier.get(); assertIndexMatchesVals(longs, values); longs.close(); } private void assertIndexMatchesVals(ColumnarLongs indexed, long[] vals) { Assert.assertEquals(vals.length, indexed.size()); for (int i = 0; i < indexed.size(); ++i) { Assert.assertEquals( StringUtils.format( "Value [%d] at row '%d' does not match [%d]", indexed.get(i), i, vals[i] ), vals[i], indexed.get(i) ); } } }
{'content_hash': 'ce751c9c3ae51e3375c680c8582e54d1', 'timestamp': '', 'source': 'github', 'line_count': 121, 'max_line_length': 122, 'avg_line_length': 31.8099173553719, 'alnum_prop': 0.6877110937905949, 'repo_name': 'liquidm/druid', 'id': '8fe0bf8ac3ad6ded897a97dd765734d6f837db1d', 'size': '4656', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'processing/src/test/java/org/apache/druid/segment/data/CompressedLongsAutoEncodingSerdeTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '4141'}, {'name': 'CSS', 'bytes': '41839'}, {'name': 'Dockerfile', 'bytes': '6007'}, {'name': 'HTML', 'bytes': '20699'}, {'name': 'Java', 'bytes': '23022993'}, {'name': 'JavaScript', 'bytes': '308250'}, {'name': 'Makefile', 'bytes': '1572'}, {'name': 'PostScript', 'bytes': '5'}, {'name': 'R', 'bytes': '17002'}, {'name': 'Roff', 'bytes': '3617'}, {'name': 'Shell', 'bytes': '43333'}, {'name': 'TSQL', 'bytes': '6493'}, {'name': 'TeX', 'bytes': '399508'}, {'name': 'Thrift', 'bytes': '1003'}, {'name': 'TypeScript', 'bytes': '158576'}]}
package de.lessvoid.nifty.examples.slick2d.helloworld; import de.lessvoid.nifty.examples.helloworld.ResizeExample; import de.lessvoid.nifty.examples.slick2d.SlickExampleLoader; /** * Demo class to execute the resize demonstration. * * @author Martin Karing &lt;[email protected]&gt; */ public class ResizeDemoMain { /** * Execute the demonstration. * * @param args call arguments - have no effect */ public static void main(final String[] args) { SlickExampleLoader.createGame(new SlickExampleLoader(new ResizeExample())); } }
{'content_hash': 'ddc29932c22c36adad714a324a6ef0f5', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 79, 'avg_line_length': 28.85, 'alnum_prop': 0.7175043327556326, 'repo_name': 'void256/nifty-gui', 'id': 'aef2523cb7ddb45236a9e7ab42b5870544012ab4', 'size': '577', 'binary': False, 'copies': '7', 'ref': 'refs/heads/1.4', 'path': 'nifty-examples-slick2d/src/main/java/de/lessvoid/nifty/examples/slick2d/helloworld/ResizeDemoMain.java', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'GLSL', 'bytes': '474'}, {'name': 'HTML', 'bytes': '23455'}, {'name': 'Java', 'bytes': '3195182'}, {'name': 'Processing', 'bytes': '41792'}]}
namespace Microsoft.Azure.Search.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Linq; /// <summary> /// Tokenizer for path-like hierarchies. This tokenizer is implemented /// using Apache Lucene. /// <see /// href="http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/path/PathHierarchyTokenizer.html" /// /> /// </summary> [Newtonsoft.Json.JsonObject("#Microsoft.Azure.Search.PathHierarchyTokenizerV2")] public partial class PathHierarchyTokenizerV2 : Tokenizer { /// <summary> /// Initializes a new instance of the PathHierarchyTokenizerV2 class. /// </summary> public PathHierarchyTokenizerV2() { CustomInit(); } /// <summary> /// Initializes a new instance of the PathHierarchyTokenizerV2 class. /// </summary> /// <param name="name">The name of the tokenizer. It must only contain /// letters, digits, spaces, dashes or underscores, can only start and /// end with alphanumeric characters, and is limited to 128 /// characters.</param> /// <param name="delimiter">The delimiter character to use. Default is /// "/".</param> /// <param name="replacement">A value that, if set, replaces the /// delimiter character. Default is "/".</param> /// <param name="maxTokenLength">The maximum token length. Default and /// maximum is 300.</param> /// <param name="reverseTokenOrder">A value indicating whether to /// generate tokens in reverse order. Default is false.</param> /// <param name="numberOfTokensToSkip">The number of initial tokens to /// skip. Default is 0.</param> public PathHierarchyTokenizerV2(string name, char? delimiter = default(char?), char? replacement = default(char?), int? maxTokenLength = default(int?), bool? reverseTokenOrder = default(bool?), int? numberOfTokensToSkip = default(int?)) : base(name) { Delimiter = delimiter; Replacement = replacement; MaxTokenLength = maxTokenLength; ReverseTokenOrder = reverseTokenOrder; NumberOfTokensToSkip = numberOfTokensToSkip; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the delimiter character to use. Default is "/". /// </summary> [JsonProperty(PropertyName = "delimiter")] public char? Delimiter { get; set; } /// <summary> /// Gets or sets a value that, if set, replaces the delimiter /// character. Default is "/". /// </summary> [JsonProperty(PropertyName = "replacement")] public char? Replacement { get; set; } /// <summary> /// Gets or sets the maximum token length. Default and maximum is 300. /// </summary> [JsonProperty(PropertyName = "maxTokenLength")] public int? MaxTokenLength { get; set; } /// <summary> /// Gets or sets a value indicating whether to generate tokens in /// reverse order. Default is false. /// </summary> [JsonProperty(PropertyName = "reverse")] public bool? ReverseTokenOrder { get; set; } /// <summary> /// Gets or sets the number of initial tokens to skip. Default is 0. /// </summary> [JsonProperty(PropertyName = "skip")] public int? NumberOfTokensToSkip { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public override void Validate() { base.Validate(); if (MaxTokenLength > 300) { throw new ValidationException(ValidationRules.InclusiveMaximum, "MaxTokenLength", 300); } } } }
{'content_hash': '7ba0e0c20e0fd30d93844e838dad56de', 'timestamp': '', 'source': 'github', 'line_count': 105, 'max_line_length': 244, 'avg_line_length': 39.42857142857143, 'alnum_prop': 0.5958937198067633, 'repo_name': 'DheerendraRathor/azure-sdk-for-net', 'id': 'bacb24191429eaabd36030c539f4902d4419850c', 'size': '4493', 'binary': False, 'copies': '14', 'ref': 'refs/heads/psSdkJson6', 'path': 'src/SDKs/Search/DataPlane/Microsoft.Azure.Search.Service/Generated/Models/PathHierarchyTokenizerV2.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '118'}, {'name': 'Batchfile', 'bytes': '15938'}, {'name': 'C#', 'bytes': '74830057'}, {'name': 'CSS', 'bytes': '685'}, {'name': 'JavaScript', 'bytes': '7875'}, {'name': 'PowerShell', 'bytes': '21530'}, {'name': 'Shell', 'bytes': '9959'}, {'name': 'XSLT', 'bytes': '6114'}]}
<!DOCTYPE html> <html ng-app="blocJams"> <head lang="en"> <meta charset="UTF-8"> <title>Bloc Base Project</title> <link rel="stylesheet" href="/styles/style.css"> </head> <body> <nav class="navbar"><!-- navigation bar --> <a href="index.html" class="logo"> <img src="assets/images/bloc_jams_logo.png" alt="bloc jams logo"> </a> <div class="links-container"> <a href="collection.html" class="navbar-link">collection</a> </div> </nav> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> <script src="/scripts/app.js"></script> </body> </html>
{'content_hash': '19eef51766842c533f7aa18fea8acb26', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 96, 'avg_line_length': 31.761904761904763, 'alnum_prop': 0.5952023988005997, 'repo_name': 'kosCode/bloc-jams-angular', 'id': '642b5cfd55af9e9038a2c3a3c68d612782c7fa25', 'size': '667', 'binary': False, 'copies': '2', 'ref': 'refs/heads/checkpoint-2-Configuration', 'path': 'dist/index.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '9407'}, {'name': 'HTML', 'bytes': '1370'}, {'name': 'JavaScript', 'bytes': '3697'}]}
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Sabio.Web.Domain.Tests { public class TestEmployee { public int Id { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public DateTime Dob { get; set; } public string Title { get; set; } public int Status { get; set; } } }
{'content_hash': 'd8fbc0885ae49df2b7b5a973bc90a0ee', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 45, 'avg_line_length': 20.09090909090909, 'alnum_prop': 0.581447963800905, 'repo_name': 'yushigomi/ATeam', 'id': '7e8d3b45f40727c3218c7807f7f6abb12230db75', 'size': '444', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Sabio.Web/Domain/Tests/TestEmployee.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '101'}, {'name': 'C#', 'bytes': '316955'}, {'name': 'CSS', 'bytes': '1309'}, {'name': 'HTML', 'bytes': '17073'}, {'name': 'JavaScript', 'bytes': '44153'}, {'name': 'PowerShell', 'bytes': '2714'}]}
/** * ngrinder monitor share package, include the share class used by both monitor server and client. */ package org.ngrinder.monitor.share;
{'content_hash': '94d1c02677d9e1a45a428d5f41cb745d', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 98, 'avg_line_length': 28.8, 'alnum_prop': 0.7569444444444444, 'repo_name': 'bwahn/ngrinder', 'id': '24795d79a722940d669e8e9e6c65883938f60602', 'size': '144', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'ngrinder-core/src/main/java/org/ngrinder/monitor/share/package-info.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '1479'}, {'name': 'CSS', 'bytes': '75784'}, {'name': 'Groff', 'bytes': '51750'}, {'name': 'Groovy', 'bytes': '6731'}, {'name': 'HTML', 'bytes': '308'}, {'name': 'Java', 'bytes': '1743501'}, {'name': 'JavaScript', 'bytes': '405721'}, {'name': 'Python', 'bytes': '2890'}, {'name': 'Shell', 'bytes': '4944'}]}
<!DOCTYPE html> <p>Test that a relatively positioned spanner is positioned correctly.</p> <p>Below there should be a green square, and nothing else.</p> <div style="-webkit-columns:3; line-height:3em; width:9em;"> <br> <div> <br> <div style="-webkit-column-span:all; position:relative; top:9em; height:9em; background:green;"></div> <div style="background:red;">FAIL<br>FAIL<br>FAIL<br>FAIL<br>FAIL<br>FAIL<br>FAIL<br>FAIL<br>FAIL</div> </div> </div>
{'content_hash': '3c5dcd4adf7aad8825fd9b8ede033788', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 111, 'avg_line_length': 44.27272727272727, 'alnum_prop': 0.6652977412731006, 'repo_name': 'XiaosongWei/chromium-crosswalk', 'id': 'e0200e27dccf8320c458d3794c629fcb95804316', 'size': '487', 'binary': False, 'copies': '46', 'ref': 'refs/heads/master', 'path': 'third_party/WebKit/LayoutTests/fast/multicol/span/relpos-in-block.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
package com.braintreepayments.api.internal; public class HttpResponse { private int mResponseCode; private String mResponseBody; public HttpResponse(int responseCode, String responseBody) { mResponseCode = responseCode; mResponseBody = responseBody; } public int getResponseCode() { return mResponseCode; } public String getResponseBody() { return mResponseBody; } }
{'content_hash': '83f9f89c33f4906fa77071444f546ed0', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 64, 'avg_line_length': 21.8, 'alnum_prop': 0.6880733944954128, 'repo_name': 'marviktintor/braintree_android', 'id': '108775732024793e19b968c12124b087cdb668ef', 'size': '436', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'BraintreeApi/src/main/java/com/braintreepayments/api/internal/HttpResponse.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '623404'}, {'name': 'Ruby', 'bytes': '7608'}, {'name': 'Shell', 'bytes': '3124'}]}
<div class="form-group"> <label for="{{formName+index}}" class="col-sm-4 control-label" ng-class="{'df-required':required}"> {{label}} {{inputText}} </label> <div class="col-sm-8"> <select ng-options="item.key as item.text for item in options | rmHiddens" id="{{formName+index}}" class="form-control" ng-model="inputText" ng-init="inputText = inputText || options[0]" validator-required="{{required}}" validator-group="{{formName}}" ng-if="!item.hidden"> <option value=""> - <option> </select> <p class="help-block">{{description}}</p> </div> </div>
{'content_hash': 'c90233f714433ce3479b26752fb2b60a', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 277, 'avg_line_length': 52.72727272727273, 'alnum_prop': 0.6413793103448275, 'repo_name': 'sebt-team/angular-deform', 'id': 'ee6fde10a95596e0055f7e21005057bcb35b04f2', 'size': '580', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/app/components/builder/templates/form_objects/select.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '6995'}, {'name': 'HTML', 'bytes': '24515'}, {'name': 'JavaScript', 'bytes': '95126'}]}
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.services.gcm; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.annotation.MainThread; import org.chromium.base.Log; import org.chromium.components.background_task_scheduler.BackgroundTask; import org.chromium.components.background_task_scheduler.TaskParameters; import org.chromium.components.gcm_driver.GCMMessage; /** * Processes jobs that have been scheduled for delivering GCM messages to the native GCM Driver, * processing for which may exceed the lifetime of the GcmListenerService. */ @TargetApi(Build.VERSION_CODES.N) public class GCMBackgroundTask implements BackgroundTask { private static final String TAG = "GCMBackgroundTask"; /** * Called when a GCM message is ready to be delivered to the GCM Driver consumer. Because we * don't yet know when a message has been fully processed, the task returns that processing has * been completed, and we hope that the system keeps us alive long enough to finish processing. * * @return Boolean indicating whether the WakeLock for this task must be maintained. */ @MainThread @Override public boolean onStartTask( Context context, TaskParameters taskParameters, TaskFinishedCallback callback) { Bundle extras = taskParameters.getExtras(); if (!GCMMessage.validateBundle(extras)) { Log.e(TAG, "The received bundle containing message data could not be validated."); return false; } ChromeGcmListenerService.dispatchMessageToDriver(context, new GCMMessage(extras)); return false; } /** * Called when the system has determined that processing the GCM message must be stopped. * * @return Boolean indicating whether the task has to be rescheduled. */ @MainThread @Override public boolean onStopTask(Context context, TaskParameters taskParameters) { // The GCM Driver has no mechanism for aborting previously dispatched messages. return false; } @MainThread @Override public void reschedule(Context context) { // Needs appropriate implementation. } }
{'content_hash': '57360c19d76252c70e9bfc5702f53982', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 99, 'avg_line_length': 37.703125, 'alnum_prop': 0.7306257770410277, 'repo_name': 'mogoweb/365browser', 'id': '5372c5307148ae7f027b39a385840d6b21b75c7c', 'size': '2413', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/src/main/java/org/chromium/chrome/browser/services/gcm/GCMBackgroundTask.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '18549237'}, {'name': 'Makefile', 'bytes': '10559'}, {'name': 'Python', 'bytes': '44749'}]}
package apiserver import ( "context" "encoding/json" "fmt" "reflect" "testing" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" "k8s.io/apiextensions-apiserver/test/integration/fixtures" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/types" genericfeatures "k8s.io/apiserver/pkg/features" utilfeature "k8s.io/apiserver/pkg/util/feature" "k8s.io/client-go/dynamic" featuregatetesting "k8s.io/component-base/featuregate/testing" apiservertesting "k8s.io/kubernetes/cmd/kube-apiserver/app/testing" "k8s.io/kubernetes/test/integration/framework" ) // TestApplyCRDNoSchema tests that CRDs and CRs can both be applied to with a PATCH request with the apply content type // when there is no validation field provided. func TestApplyCRDNoSchema(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, genericfeatures.ServerSideApply, true)() server, err := apiservertesting.StartTestServer(t, apiservertesting.NewDefaultTestServerOptions(), nil, framework.SharedEtcd()) if err != nil { t.Fatal(err) } defer server.TearDownFn() config := server.ClientConfig apiExtensionClient, err := clientset.NewForConfig(config) if err != nil { t.Fatal(err) } dynamicClient, err := dynamic.NewForConfig(config) if err != nil { t.Fatal(err) } noxuDefinition := fixtures.NewMultipleVersionNoxuCRD(apiextensionsv1beta1.ClusterScoped) noxuDefinition, err = fixtures.CreateNewCustomResourceDefinition(noxuDefinition, apiExtensionClient, dynamicClient) if err != nil { t.Fatal(err) } kind := noxuDefinition.Spec.Names.Kind apiVersion := noxuDefinition.Spec.Group + "/" + noxuDefinition.Spec.Version name := "mytest" rest := apiExtensionClient.Discovery().RESTClient() yamlBody := []byte(fmt.Sprintf(` apiVersion: %s kind: %s metadata: name: %s spec: replicas: 1`, apiVersion, kind, name)) result, err := rest.Patch(types.ApplyPatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Param("fieldManager", "apply_test"). Body(yamlBody). DoRaw(context.TODO()) if err != nil { t.Fatalf("failed to create custom resource with apply: %v:\n%v", err, string(result)) } verifyReplicas(t, result, 1) // Patch object to change the number of replicas result, err = rest.Patch(types.MergePatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Body([]byte(`{"spec":{"replicas": 5}}`)). DoRaw(context.TODO()) if err != nil { t.Fatalf("failed to update number of replicas with merge patch: %v:\n%v", err, string(result)) } verifyReplicas(t, result, 5) // Re-apply, we should get conflicts now, since the number of replicas was changed. result, err = rest.Patch(types.ApplyPatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Param("fieldManager", "apply_test"). Body(yamlBody). DoRaw(context.TODO()) if err == nil { t.Fatalf("Expecting to get conflicts when applying object after updating replicas, got no error: %s", result) } status, ok := err.(*apierrors.StatusError) if !ok { t.Fatalf("Expecting to get conflicts as API error") } if len(status.Status().Details.Causes) != 1 { t.Fatalf("Expecting to get one conflict when applying object after updating replicas, got: %v", status.Status().Details.Causes) } // Re-apply with force, should work fine. result, err = rest.Patch(types.ApplyPatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Param("force", "true"). Param("fieldManager", "apply_test"). Body(yamlBody). DoRaw(context.TODO()) if err != nil { t.Fatalf("failed to apply object with force after updating replicas: %v:\n%v", err, string(result)) } verifyReplicas(t, result, 1) // Try to set managed fields using a subresource and verify that it has no effect existingManagedFields, err := getManagedFields(result) if err != nil { t.Fatalf("failed to get managedFields from response: %v", err) } updateBytes := []byte(`{ "metadata": { "managedFields": [{ "manager":"testing", "operation":"Update", "apiVersion":"v1", "fieldsType":"FieldsV1", "fieldsV1":{ "f:spec":{ "f:containers":{ "k:{\"name\":\"testing\"}":{ ".":{}, "f:image":{}, "f:name":{} } } } } }] } }`) result, err = rest.Patch(types.MergePatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). SubResource("status"). Name(name). Param("fieldManager", "subresource_test"). Body(updateBytes). DoRaw(context.TODO()) if err != nil { t.Fatalf("Error updating subresource: %v ", err) } newManagedFields, err := getManagedFields(result) if err != nil { t.Fatalf("failed to get managedFields from response: %v", err) } if !reflect.DeepEqual(existingManagedFields, newManagedFields) { t.Fatalf("Expected managed fields to not have changed when trying manually settting them via subresoures.\n\nExpected: %#v\n\nGot: %#v", existingManagedFields, newManagedFields) } // However, it is possible to modify managed fields using the main resource result, err = rest.Patch(types.MergePatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Param("fieldManager", "subresource_test"). Body([]byte(`{"metadata":{"managedFields":[{}]}}`)). DoRaw(context.TODO()) if err != nil { t.Fatalf("Error updating managed fields of the main resource: %v ", err) } newManagedFields, err = getManagedFields(result) if err != nil { t.Fatalf("failed to get managedFields from response: %v", err) } if len(newManagedFields) != 0 { t.Fatalf("Expected managed fields to have been reset, but got: %v", newManagedFields) } } // TestApplyCRDStructuralSchema tests that when a CRD has a structural schema in its validation field, // it will be used to construct the CR schema used by apply. func TestApplyCRDStructuralSchema(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, genericfeatures.ServerSideApply, true)() server, err := apiservertesting.StartTestServer(t, apiservertesting.NewDefaultTestServerOptions(), nil, framework.SharedEtcd()) if err != nil { t.Fatal(err) } defer server.TearDownFn() config := server.ClientConfig apiExtensionClient, err := clientset.NewForConfig(config) if err != nil { t.Fatal(err) } dynamicClient, err := dynamic.NewForConfig(config) if err != nil { t.Fatal(err) } noxuDefinition := fixtures.NewMultipleVersionNoxuCRD(apiextensionsv1beta1.ClusterScoped) var c apiextensionsv1beta1.CustomResourceValidation err = json.Unmarshal([]byte(`{ "openAPIV3Schema": { "type": "object", "properties": { "spec": { "type": "object", "x-kubernetes-preserve-unknown-fields": true, "properties": { "cronSpec": { "type": "string", "pattern": "^(\\d+|\\*)(/\\d+)?(\\s+(\\d+|\\*)(/\\d+)?){4}$" }, "ports": { "type": "array", "x-kubernetes-list-map-keys": [ "containerPort", "protocol" ], "x-kubernetes-list-type": "map", "items": { "properties": { "containerPort": { "format": "int32", "type": "integer" }, "hostIP": { "type": "string" }, "hostPort": { "format": "int32", "type": "integer" }, "name": { "type": "string" }, "protocol": { "type": "string" } }, "required": [ "containerPort", "protocol" ], "type": "object" } } } } } } }`), &c) if err != nil { t.Fatal(err) } noxuDefinition.Spec.Validation = &c falseBool := false noxuDefinition.Spec.PreserveUnknownFields = &falseBool noxuDefinition, err = fixtures.CreateNewCustomResourceDefinition(noxuDefinition, apiExtensionClient, dynamicClient) if err != nil { t.Fatal(err) } kind := noxuDefinition.Spec.Names.Kind apiVersion := noxuDefinition.Spec.Group + "/" + noxuDefinition.Spec.Version name := "mytest" rest := apiExtensionClient.Discovery().RESTClient() yamlBody := []byte(fmt.Sprintf(` apiVersion: %s kind: %s metadata: name: %s finalizers: - test-finalizer spec: cronSpec: "* * * * */5" replicas: 1 ports: - name: x containerPort: 80 protocol: TCP`, apiVersion, kind, name)) result, err := rest.Patch(types.ApplyPatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Param("fieldManager", "apply_test"). Body(yamlBody). DoRaw(context.TODO()) if err != nil { t.Fatalf("failed to create custom resource with apply: %v:\n%v", err, string(result)) } verifyNumFinalizers(t, result, 1) verifyFinalizersIncludes(t, result, "test-finalizer") verifyReplicas(t, result, 1) verifyNumPorts(t, result, 1) // Patch object to add another finalizer to the finalizers list result, err = rest.Patch(types.MergePatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Body([]byte(`{"metadata":{"finalizers":["test-finalizer","another-one"]}}`)). DoRaw(context.TODO()) if err != nil { t.Fatalf("failed to add finalizer with merge patch: %v:\n%v", err, string(result)) } verifyNumFinalizers(t, result, 2) verifyFinalizersIncludes(t, result, "test-finalizer") verifyFinalizersIncludes(t, result, "another-one") // Re-apply the same config, should work fine, since finalizers should have the list-type extension 'set'. result, err = rest.Patch(types.ApplyPatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Param("fieldManager", "apply_test"). SetHeader("Accept", "application/json"). Body(yamlBody). DoRaw(context.TODO()) if err != nil { t.Fatalf("failed to apply same config after adding a finalizer: %v:\n%v", err, string(result)) } verifyNumFinalizers(t, result, 2) verifyFinalizersIncludes(t, result, "test-finalizer") verifyFinalizersIncludes(t, result, "another-one") // Patch object to change the number of replicas result, err = rest.Patch(types.MergePatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Body([]byte(`{"spec":{"replicas": 5}}`)). DoRaw(context.TODO()) if err != nil { t.Fatalf("failed to update number of replicas with merge patch: %v:\n%v", err, string(result)) } verifyReplicas(t, result, 5) // Re-apply, we should get conflicts now, since the number of replicas was changed. result, err = rest.Patch(types.ApplyPatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Param("fieldManager", "apply_test"). Body(yamlBody). DoRaw(context.TODO()) if err == nil { t.Fatalf("Expecting to get conflicts when applying object after updating replicas, got no error: %s", result) } status, ok := err.(*apierrors.StatusError) if !ok { t.Fatalf("Expecting to get conflicts as API error") } if len(status.Status().Details.Causes) != 1 { t.Fatalf("Expecting to get one conflict when applying object after updating replicas, got: %v", status.Status().Details.Causes) } // Re-apply with force, should work fine. result, err = rest.Patch(types.ApplyPatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Param("force", "true"). Param("fieldManager", "apply_test"). Body(yamlBody). DoRaw(context.TODO()) if err != nil { t.Fatalf("failed to apply object with force after updating replicas: %v:\n%v", err, string(result)) } verifyReplicas(t, result, 1) // New applier tries to edit an existing list item, we should get conflicts. result, err = rest.Patch(types.ApplyPatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Param("fieldManager", "apply_test_2"). Body([]byte(fmt.Sprintf(` apiVersion: %s kind: %s metadata: name: %s spec: ports: - name: "y" containerPort: 80 protocol: TCP`, apiVersion, kind, name))). DoRaw(context.TODO()) if err == nil { t.Fatalf("Expecting to get conflicts when a different applier updates existing list item, got no error: %s", result) } status, ok = err.(*apierrors.StatusError) if !ok { t.Fatalf("Expecting to get conflicts as API error") } if len(status.Status().Details.Causes) != 1 { t.Fatalf("Expecting to get one conflict when a different applier updates existing list item, got: %v", status.Status().Details.Causes) } // New applier tries to add a new list item, should work fine. result, err = rest.Patch(types.ApplyPatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Param("fieldManager", "apply_test_2"). Body([]byte(fmt.Sprintf(` apiVersion: %s kind: %s metadata: name: %s spec: ports: - name: "y" containerPort: 8080 protocol: TCP`, apiVersion, kind, name))). SetHeader("Accept", "application/json"). DoRaw(context.TODO()) if err != nil { t.Fatalf("failed to add a new list item to the object as a different applier: %v:\n%v", err, string(result)) } verifyNumPorts(t, result, 2) // UpdateOnCreate notExistingYAMLBody := []byte(fmt.Sprintf(` { "apiVersion": "%s", "kind": "%s", "metadata": { "name": "%s", "finalizers": [ "test-finalizer" ] }, "spec": { "cronSpec": "* * * * */5", "replicas": 1, "ports": [ { "name": "x", "containerPort": 80 } ] }, "protocol": "TCP" }`, apiVersion, kind, "should-not-exist")) _, err = rest.Put(). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name("should-not-exist"). Param("fieldManager", "apply_test"). Body(notExistingYAMLBody). DoRaw(context.TODO()) if !apierrors.IsNotFound(err) { t.Fatalf("create on update should fail with notFound, got %v", err) } } // verifyNumFinalizers checks that len(.metadata.finalizers) == n func verifyNumFinalizers(t *testing.T, b []byte, n int) { obj := unstructured.Unstructured{} err := obj.UnmarshalJSON(b) if err != nil { t.Fatalf("failed to unmarshal response: %v", err) } if actual, expected := len(obj.GetFinalizers()), n; actual != expected { t.Fatalf("expected %v finalizers but got %v:\n%v", expected, actual, string(b)) } } // verifyFinalizersIncludes checks that .metadata.finalizers includes e func verifyFinalizersIncludes(t *testing.T, b []byte, e string) { obj := unstructured.Unstructured{} err := obj.UnmarshalJSON(b) if err != nil { t.Fatalf("failed to unmarshal response: %v", err) } for _, a := range obj.GetFinalizers() { if a == e { return } } t.Fatalf("expected finalizers to include %q but got: %v", e, obj.GetFinalizers()) } // verifyReplicas checks that .spec.replicas == r func verifyReplicas(t *testing.T, b []byte, r int) { obj := unstructured.Unstructured{} err := obj.UnmarshalJSON(b) if err != nil { t.Fatalf("failed to find replicas number in response: %v:\n%v", err, string(b)) } spec, ok := obj.Object["spec"] if !ok { t.Fatalf("failed to find replicas number in response:\n%v", string(b)) } specMap, ok := spec.(map[string]interface{}) if !ok { t.Fatalf("failed to find replicas number in response:\n%v", string(b)) } replicas, ok := specMap["replicas"] if !ok { t.Fatalf("failed to find replicas number in response:\n%v", string(b)) } replicasNumber, ok := replicas.(int64) if !ok { t.Fatalf("failed to find replicas number in response: expected int64 but got: %v", reflect.TypeOf(replicas)) } if actual, expected := replicasNumber, int64(r); actual != expected { t.Fatalf("expected %v ports but got %v:\n%v", expected, actual, string(b)) } } // verifyNumPorts checks that len(.spec.ports) == n func verifyNumPorts(t *testing.T, b []byte, n int) { obj := unstructured.Unstructured{} err := obj.UnmarshalJSON(b) if err != nil { t.Fatalf("failed to find ports list in response: %v:\n%v", err, string(b)) } spec, ok := obj.Object["spec"] if !ok { t.Fatalf("failed to find ports list in response:\n%v", string(b)) } specMap, ok := spec.(map[string]interface{}) if !ok { t.Fatalf("failed to find ports list in response:\n%v", string(b)) } ports, ok := specMap["ports"] if !ok { t.Fatalf("failed to find ports list in response:\n%v", string(b)) } portsList, ok := ports.([]interface{}) if !ok { t.Fatalf("failed to find ports list in response: expected array but got: %v", reflect.TypeOf(ports)) } if actual, expected := len(portsList), n; actual != expected { t.Fatalf("expected %v ports but got %v:\n%v", expected, actual, string(b)) } } // TestApplyCRDUnhandledSchema tests that when a CRD has a schema that kube-openapi ToProtoModels cannot handle correctly, // apply falls back to non-schema behavior func TestApplyCRDUnhandledSchema(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, genericfeatures.ServerSideApply, true)() server, err := apiservertesting.StartTestServer(t, apiservertesting.NewDefaultTestServerOptions(), nil, framework.SharedEtcd()) if err != nil { t.Fatal(err) } defer server.TearDownFn() config := server.ClientConfig apiExtensionClient, err := clientset.NewForConfig(config) if err != nil { t.Fatal(err) } dynamicClient, err := dynamic.NewForConfig(config) if err != nil { t.Fatal(err) } noxuDefinition := fixtures.NewNoxuCustomResourceDefinition(apiextensionsv1beta1.ClusterScoped) // This is a schema that kube-openapi ToProtoModels does not handle correctly. // https://github.com/kubernetes/kubernetes/blob/38752f7f99869ed65fb44378360a517649dc2f83/vendor/k8s.io/kube-openapi/pkg/util/proto/document.go#L184 var c apiextensionsv1beta1.CustomResourceValidation err = json.Unmarshal([]byte(`{ "openAPIV3Schema": { "properties": { "TypeFooBar": { "type": "array" } } } }`), &c) if err != nil { t.Fatal(err) } noxuDefinition.Spec.Validation = &c noxuDefinition, err = fixtures.CreateNewCustomResourceDefinition(noxuDefinition, apiExtensionClient, dynamicClient) if err != nil { t.Fatal(err) } kind := noxuDefinition.Spec.Names.Kind apiVersion := noxuDefinition.Spec.Group + "/" + noxuDefinition.Spec.Version name := "mytest" rest := apiExtensionClient.Discovery().RESTClient() yamlBody := []byte(fmt.Sprintf(` apiVersion: %s kind: %s metadata: name: %s spec: replicas: 1`, apiVersion, kind, name)) result, err := rest.Patch(types.ApplyPatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Param("fieldManager", "apply_test"). Body(yamlBody). DoRaw(context.TODO()) if err != nil { t.Fatalf("failed to create custom resource with apply: %v:\n%v", err, string(result)) } verifyReplicas(t, result, 1) // Patch object to change the number of replicas result, err = rest.Patch(types.MergePatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Body([]byte(`{"spec":{"replicas": 5}}`)). DoRaw(context.TODO()) if err != nil { t.Fatalf("failed to update number of replicas with merge patch: %v:\n%v", err, string(result)) } verifyReplicas(t, result, 5) // Re-apply, we should get conflicts now, since the number of replicas was changed. result, err = rest.Patch(types.ApplyPatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Param("fieldManager", "apply_test"). Body(yamlBody). DoRaw(context.TODO()) if err == nil { t.Fatalf("Expecting to get conflicts when applying object after updating replicas, got no error: %s", result) } status, ok := err.(*apierrors.StatusError) if !ok { t.Fatalf("Expecting to get conflicts as API error") } if len(status.Status().Details.Causes) != 1 { t.Fatalf("Expecting to get one conflict when applying object after updating replicas, got: %v", status.Status().Details.Causes) } // Re-apply with force, should work fine. result, err = rest.Patch(types.ApplyPatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Version, noxuDefinition.Spec.Names.Plural). Name(name). Param("force", "true"). Param("fieldManager", "apply_test"). Body(yamlBody). DoRaw(context.TODO()) if err != nil { t.Fatalf("failed to apply object with force after updating replicas: %v:\n%v", err, string(result)) } verifyReplicas(t, result, 1) } func getManagedFields(rawResponse []byte) ([]metav1.ManagedFieldsEntry, error) { obj := unstructured.Unstructured{} if err := obj.UnmarshalJSON(rawResponse); err != nil { return nil, err } return obj.GetManagedFields(), nil } func TestDefaultMissingKeyCRD(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, genericfeatures.ServerSideApply, true)() server, err := apiservertesting.StartTestServer(t, apiservertesting.NewDefaultTestServerOptions(), nil, framework.SharedEtcd()) if err != nil { t.Fatal(err) } defer server.TearDownFn() config := server.ClientConfig apiExtensionClient, err := clientset.NewForConfig(config) if err != nil { t.Fatal(err) } dynamicClient, err := dynamic.NewForConfig(config) if err != nil { t.Fatal(err) } noxuDefinition := fixtures.NewNoxuV1CustomResourceDefinition(apiextensionsv1.ClusterScoped) err = json.Unmarshal([]byte(`{ "openAPIV3Schema": { "type": "object", "properties": { "spec": { "type": "object", "x-kubernetes-preserve-unknown-fields": true, "properties": { "cronSpec": { "type": "string", "pattern": "^(\\d+|\\*)(/\\d+)?(\\s+(\\d+|\\*)(/\\d+)?){4}$" }, "ports": { "type": "array", "x-kubernetes-list-map-keys": [ "containerPort", "protocol" ], "x-kubernetes-list-type": "map", "items": { "properties": { "containerPort": { "format": "int32", "type": "integer" }, "hostIP": { "type": "string" }, "hostPort": { "format": "int32", "type": "integer" }, "name": { "type": "string" }, "protocol": { "default": "TCP", "type": "string" } }, "required": [ "containerPort" ], "type": "object" } } } } } } }`), &noxuDefinition.Spec.Versions[0].Schema) if err != nil { t.Fatal(err) } noxuDefinition, err = fixtures.CreateNewV1CustomResourceDefinition(noxuDefinition, apiExtensionClient, dynamicClient) if err != nil { t.Fatal(err) } kind := noxuDefinition.Spec.Names.Kind apiVersion := noxuDefinition.Spec.Group + "/" + noxuDefinition.Spec.Versions[0].Name name := "mytest" rest := apiExtensionClient.Discovery().RESTClient() yamlBody := []byte(fmt.Sprintf(` apiVersion: %s kind: %s metadata: name: %s finalizers: - test-finalizer spec: cronSpec: "* * * * */5" replicas: 1 ports: - name: x containerPort: 80`, apiVersion, kind, name)) result, err := rest.Patch(types.ApplyPatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Versions[0].Name, noxuDefinition.Spec.Names.Plural). Name(name). Param("fieldManager", "apply_test"). Body(yamlBody). DoRaw(context.TODO()) if err != nil { t.Fatalf("failed to create custom resource with apply: %v:\n%v", err, string(result)) } // New applier tries to edit an existing list item, we should get conflicts. result, err = rest.Patch(types.ApplyPatchType). AbsPath("/apis", noxuDefinition.Spec.Group, noxuDefinition.Spec.Versions[0].Name, noxuDefinition.Spec.Names.Plural). Name(name). Param("fieldManager", "apply_test_2"). Body([]byte(fmt.Sprintf(` apiVersion: %s kind: %s metadata: name: %s spec: ports: - name: "y" containerPort: 80 protocol: TCP`, apiVersion, kind, name))). DoRaw(context.TODO()) if err == nil { t.Fatalf("Expecting to get conflicts when a different applier updates existing list item, got no error: %s", result) } status, ok := err.(*apierrors.StatusError) if !ok { t.Fatalf("Expecting to get conflicts as API error") } if len(status.Status().Details.Causes) != 1 { t.Fatalf("Expecting to get one conflict when a different applier updates existing list item, got: %v", status.Status().Details.Causes) } }
{'content_hash': '12a6c163c2f8ede848ff7917817f151d', 'timestamp': '', 'source': 'github', 'line_count': 793, 'max_line_length': 179, 'avg_line_length': 32.0063051702396, 'alnum_prop': 0.6812182341121311, 'repo_name': 'JacobTanenbaum/kubernetes', 'id': '342a638cd8a81dd4d701af11de10a985a65aa104', 'size': '25950', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'test/integration/apiserver/apply/apply_crd_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '2840'}, {'name': 'Dockerfile', 'bytes': '60691'}, {'name': 'Go', 'bytes': '47242733'}, {'name': 'HTML', 'bytes': '38'}, {'name': 'Lua', 'bytes': '17200'}, {'name': 'Makefile', 'bytes': '74510'}, {'name': 'PowerShell', 'bytes': '99342'}, {'name': 'Python', 'bytes': '3236039'}, {'name': 'Ruby', 'bytes': '431'}, {'name': 'Shell', 'bytes': '1572563'}, {'name': 'sed', 'bytes': '12331'}]}
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pcloud.networking.serialization; import java.io.ObjectInputStream; import java.io.ObjectStreamClass; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Magic that creates instances of arbitrary concrete classes. Derived from Gson's UnsafeAllocator * and ConstructorConstructor classes. * * @author Joel Leitch * @author Jesse Wilson */ abstract class ClassFactory<T> { abstract T newInstance() throws InvocationTargetException, IllegalAccessException, InstantiationException; static <T> ClassFactory<T> get(final Class<T> rawType) { // Try to find a no-args constructor. May be any visibility including private. try { final Constructor<?> constructor = rawType.getDeclaredConstructor(); constructor.setAccessible(true); return new ClassFactory<T>() { @SuppressWarnings("unchecked") // T is the same raw type as is requested @Override public T newInstance() throws IllegalAccessException, InvocationTargetException, InstantiationException { return (T) constructor.newInstance((Object[]) null); } @Override public String toString() { return rawType.getName(); } }; } catch (NoSuchMethodException ignored) { // No no-args constructor. Fall back to something more magical... } // Try the JVM's Unsafe mechanism. // public class Unsafe { // public Object allocateInstance(Class<?> type); // } try { Class<?> unsafeClass = Class.forName("sun.misc.Unsafe"); Field f = unsafeClass.getDeclaredField("theUnsafe"); f.setAccessible(true); final Object unsafe = f.get(null); final Method allocateInstance = unsafeClass.getMethod("allocateInstance", Class.class); return new ClassFactory<T>() { @SuppressWarnings("unchecked") @Override public T newInstance() throws InvocationTargetException, IllegalAccessException { return (T) allocateInstance.invoke(unsafe, rawType); } @Override public String toString() { return rawType.getName(); } }; } catch (IllegalAccessException e) { throw new AssertionError(); } catch (ClassNotFoundException | NoSuchMethodException | NoSuchFieldException ignored) { // Not the expected version of the Oracle Java library! } // Try (post-Gingerbread) Dalvik/libcore's ObjectStreamClass mechanism. // public class ObjectStreamClass { // private static native int getConstructorId(Class<?> c); // private static native Object newInstance(Class<?> instantiationClass, int methodId); // } try { Method getConstructorId = ObjectStreamClass.class.getDeclaredMethod( "getConstructorId", Class.class); getConstructorId.setAccessible(true); final int constructorId = (Integer) getConstructorId.invoke(null, Object.class); final Method newInstance = ObjectStreamClass.class.getDeclaredMethod("newInstance", Class.class, int.class); newInstance.setAccessible(true); return new ClassFactory<T>() { @SuppressWarnings("unchecked") @Override public T newInstance() throws InvocationTargetException, IllegalAccessException { return (T) newInstance.invoke(null, rawType, constructorId); } @Override public String toString() { return rawType.getName(); } }; } catch (IllegalAccessException e) { throw new AssertionError(); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException ignored) { // Not the expected version of Dalvik/libcore! } // Try (pre-Gingerbread) Dalvik/libcore's ObjectInputStream mechanism. // public class ObjectInputStream { // private static native Object newInstance( // Class<?> instantiationClass, Class<?> constructorClass); // } try { final Method newInstance = ObjectInputStream.class.getDeclaredMethod( "newInstance", Class.class, Class.class); newInstance.setAccessible(true); return new ClassFactory<T>() { @SuppressWarnings("unchecked") @Override public T newInstance() throws InvocationTargetException, IllegalAccessException { return (T) newInstance.invoke(null, rawType, Object.class); } @Override public String toString() { return rawType.getName(); } }; } catch (Throwable ignored) { //Empty } throw new IllegalArgumentException("cannot construct instances of " + rawType.getName()); } }
{'content_hash': '119593b4c8040a081eeb5634d738367b', 'timestamp': '', 'source': 'github', 'line_count': 148, 'max_line_length': 99, 'avg_line_length': 40.729729729729726, 'alnum_prop': 0.6046781685467817, 'repo_name': 'pCloud/pcloud-networking-java', 'id': 'a269c1ee8356427e038c740f79f30a0fd251e762', 'size': '6628', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'serialization/src/main/java/com/pcloud/networking/serialization/ClassFactory.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '666075'}]}
/* ccapi/server/ccs_credentials_iterator.h */ /* * Copyright 2006 Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ #ifndef CCS_CREDENTIALS_ITERATOR_H #define CCS_CREDENTIALS_ITERATOR_H #include "ccs_types.h" cc_int32 ccs_credentials_iterator_handle_message (ccs_credentials_iterator_t io_credentials_iterator, ccs_ccache_t io_ccache, enum cci_msg_id_t in_request_name, k5_ipc_stream in_request_data, k5_ipc_stream *out_reply_data); #endif /* CCS_CREDENTIALS_ITERATOR_H */
{'content_hash': 'a9a14ffb050584ce86538806a8b2c5cd', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 103, 'avg_line_length': 50.567567567567565, 'alnum_prop': 0.6654195617316943, 'repo_name': 'gerritjvv/cryptoplayground', 'id': 'fc81a82b7180eb22d8412f323f316f05d35dcd47', 'size': '1871', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'kerberos/kdc/src/krb5-1.16/src/ccapi/server/ccs_credentials_iterator.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '40918'}, {'name': 'Awk', 'bytes': '10967'}, {'name': 'Batchfile', 'bytes': '2734'}, {'name': 'C', 'bytes': '14209534'}, {'name': 'C++', 'bytes': '822611'}, {'name': 'CMake', 'bytes': '486373'}, {'name': 'CSS', 'bytes': '72712'}, {'name': 'Emacs Lisp', 'bytes': '6797'}, {'name': 'HTML', 'bytes': '10177760'}, {'name': 'Java', 'bytes': '88477'}, {'name': 'JavaScript', 'bytes': '91201'}, {'name': 'Lex', 'bytes': '1395'}, {'name': 'M4', 'bytes': '25420'}, {'name': 'Makefile', 'bytes': '4976551'}, {'name': 'NSIS', 'bytes': '94536'}, {'name': 'Perl', 'bytes': '138102'}, {'name': 'Perl 6', 'bytes': '7955'}, {'name': 'Python', 'bytes': '493201'}, {'name': 'RPC', 'bytes': '5974'}, {'name': 'Roff', 'bytes': '340434'}, {'name': 'Shell', 'bytes': '103572'}, {'name': 'TeX', 'bytes': '2040204'}, {'name': 'Yacc', 'bytes': '34752'}, {'name': 'sed', 'bytes': '613'}]}
package com.amazonaws.services.macie2.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/macie2-2020-01-01/GetAllowList" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetAllowListRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The unique identifier for the Amazon Macie resource that the request applies to. * </p> */ private String id; /** * <p> * The unique identifier for the Amazon Macie resource that the request applies to. * </p> * * @param id * The unique identifier for the Amazon Macie resource that the request applies to. */ public void setId(String id) { this.id = id; } /** * <p> * The unique identifier for the Amazon Macie resource that the request applies to. * </p> * * @return The unique identifier for the Amazon Macie resource that the request applies to. */ public String getId() { return this.id; } /** * <p> * The unique identifier for the Amazon Macie resource that the request applies to. * </p> * * @param id * The unique identifier for the Amazon Macie resource that the request applies to. * @return Returns a reference to this object so that method calls can be chained together. */ public GetAllowListRequest withId(String id) { setId(id); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getId() != null) sb.append("Id: ").append(getId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetAllowListRequest == false) return false; GetAllowListRequest other = (GetAllowListRequest) obj; if (other.getId() == null ^ this.getId() == null) return false; if (other.getId() != null && other.getId().equals(this.getId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode()); return hashCode; } @Override public GetAllowListRequest clone() { return (GetAllowListRequest) super.clone(); } }
{'content_hash': '72a83c05edbcf635ee3ac65d430d903f', 'timestamp': '', 'source': 'github', 'line_count': 113, 'max_line_length': 119, 'avg_line_length': 27.327433628318584, 'alnum_prop': 0.6016839378238342, 'repo_name': 'aws/aws-sdk-java', 'id': 'fc85feb9021b1884f353efc1ed9b285fd0dbe969', 'size': '3668', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aws-java-sdk-macie2/src/main/java/com/amazonaws/services/macie2/model/GetAllowListRequest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/common'; import { NgFormControl, FORM_DIRECTIVES } from '@angular/common'; import { EventEmitter, HostListener } from '@angular/core'; import { Input, Output, Component } from '@angular/core'; import { Provider, forwardRef } from '@angular/core'; // Directives import { MdlUpgradeDirective } from '../../directives/mdl-upgrade.directive' const MDL_SELECT_VALUE_ACCESSOR = new Provider(NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => MdlSelectComponent), multi: true } ); @Component({ selector: 'mdlSelect, mdl-select', template: ` <div class="mdl-selectfield mdl-js-selectfield" [ngClass]="class" mdl-upgrade> <select class="mdl-selectfield__select" [value]="value" #select [id]="id" (blur)="onTouched()" (change)="changes.emit(select.value)"> <ng-content></ng-content> </select> <label class="mdl-selectfield__label" [attr.for]="id">{{label}}</label> <!-- <span class="mdl-selectfield__error">Select aw value</span> --> </div> `, directives: [ MdlUpgradeDirective ], providers: [ MDL_SELECT_VALUE_ACCESSOR ] }) export class MdlSelectComponent implements ControlValueAccessor { @Input() id: string; @Input() value: string; @Input() label: string; @Input() class: string; @Output() changes = new EventEmitter(); // Needed to properly implement ControlValueAccessor. @HostListener('changes', ['$event']) onChange = (_) => { console.log(); }; @HostListener('blur', ['$event']) onTouched = () => { console.log(); }; writeValue(value: any): void { this.value = value; } registerOnChange(fn: (_: any) => void): void { this.onChange = fn; } registerOnTouched(fn: () => void): void { this.onTouched = fn; } }
{'content_hash': 'e97a57ba710067c84d8148280b298f5c', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 82, 'avg_line_length': 37.208333333333336, 'alnum_prop': 0.6567749160134378, 'repo_name': 'AutoQuotes/ng2-mdl', 'id': '6e15a3f7a513aafe0756ae744c396057beffbf15', 'size': '1811', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/components/mdl-select/mdl-select.component.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '21613'}, {'name': 'JavaScript', 'bytes': '40123'}, {'name': 'TypeScript', 'bytes': '31128'}]}
create class tb( col1 varchar, col2 char(10), col3 string ); insert into tb values('varchar01', 'char01', 'string01'); insert into tb values('varchar02', 'char02', 'string02'); insert into tb values('varchar03', 'char03', 'string03'); select count(count(col1)) from tb group by col1; drop class tb;
{'content_hash': '8a2cd0a9de443c239803581617847fa8', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 57, 'avg_line_length': 23.846153846153847, 'alnum_prop': 0.6935483870967742, 'repo_name': 'CUBRID/cubrid-testcases', 'id': '466a117a5d093d14ed65da313e5858d73c634cc6', 'size': '361', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'sql/_04_operator_function/_06_aggragate_func/_002_count/cases/1008.sql', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'PLSQL', 'bytes': '682246'}, {'name': 'Roff', 'bytes': '23262735'}, {'name': 'TSQL', 'bytes': '5619'}, {'name': 'eC', 'bytes': '710'}]}
#ifndef AERON_RING_BUFFER_DESCRIPTOR_H #define AERON_RING_BUFFER_DESCRIPTOR_H #include <functional> #include "util/Index.h" #include "util/BitUtil.h" namespace aeron { namespace concurrent { namespace ringbuffer { /** The read handler function signature */ typedef std::function<void(std::int32_t, concurrent::AtomicBuffer &, util::index_t, util::index_t)> handler_t; using namespace aeron::util::BitUtil; namespace RingBufferDescriptor { static const util::index_t TAIL_POSITION_OFFSET = CACHE_LINE_LENGTH * 2; static const util::index_t HEAD_CACHE_POSITION_OFFSET = CACHE_LINE_LENGTH * 4; static const util::index_t HEAD_POSITION_OFFSET = CACHE_LINE_LENGTH * 6; static const util::index_t CORRELATION_COUNTER_OFFSET = CACHE_LINE_LENGTH * 8; static const util::index_t CONSUMER_HEARTBEAT_OFFSET = CACHE_LINE_LENGTH * 10; /** Total length of the trailer in bytes. */ static const util::index_t TRAILER_LENGTH = CACHE_LINE_LENGTH * 12; inline static void checkCapacity(util::index_t capacity) { if (!util::BitUtil::isPowerOfTwo(capacity)) { throw util::IllegalArgumentException( "Capacity must be a positive power of 2 + TRAILER_LENGTH: capacity=" + std::to_string(capacity), SOURCEINFO); } } } }}} #endif
{'content_hash': 'ed8e1a85f137cefb8e5586e3d6ef801f', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 112, 'avg_line_length': 32.31707317073171, 'alnum_prop': 0.6883018867924529, 'repo_name': 'mikeb01/Aeron', 'id': 'bf1fbef2eb5f0921a7f82312f93052ab60000129', 'size': '1929', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aeron-client/src/main/cpp/concurrent/ringbuffer/RingBufferDescriptor.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '41480'}, {'name': 'C', 'bytes': '2135180'}, {'name': 'C++', 'bytes': '2826597'}, {'name': 'CMake', 'bytes': '81425'}, {'name': 'Dockerfile', 'bytes': '2186'}, {'name': 'Java', 'bytes': '7084749'}, {'name': 'Shell', 'bytes': '65347'}]}
if (package.path == nil) then package.path = "" end package.path = package.path .. ";./Resources/Scripts/?.lua" require "util" function catchExit() print("Can't exit game from console.") end if (ANGEL_MOBILE == false) then function angelPrint(...) local arg = {...} local str str = "" for i=1, #arg do if (str ~= "") then str = str .. '\t' end str = str .. tostring(arg[i]) end LuaWrite(str) end end function angelStart() -- merge everything into the global namespace for k, v in pairs(angel) do if (nil == _G[k]) then -- keep from overriding any built-ins _G[k] = v end end angel = nil -- override the built-in exit os.exit = catchExit -- override printing to go to in-game console if (ANGEL_MOBILE == false) then print = angelPrint io.write = angelPrint end -- stir up some syntactic sugar require("sugar") -- configuration loading require("conf_load") ReloadActorDefs() ReloadLevelDefs() -- autocompletion require("autocomplete") -- run the client code require("client_start") end function errorHandler(err) print(err) end local status, err = xpcall(angelStart, errorHandler)
{'content_hash': '5c608b482aec07c73852a2ee6d1569a5', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 64, 'avg_line_length': 19.109375, 'alnum_prop': 0.6271463614063778, 'repo_name': 'TabitaPL/Pasjans', 'id': '5356be32424a46b32aa0c263c6f1fd31c7994b30', 'size': '3019', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'Angel-3.2/Code/Solitaire/Resources/Scripts/start.lua', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ada', 'bytes': '89080'}, {'name': 'Assembly', 'bytes': '143356'}, {'name': 'Awk', 'bytes': '3965'}, {'name': 'C', 'bytes': '18701685'}, {'name': 'C#', 'bytes': '55726'}, {'name': 'C++', 'bytes': '7534444'}, {'name': 'CLIPS', 'bytes': '6933'}, {'name': 'CSS', 'bytes': '66497'}, {'name': 'Erlang', 'bytes': '3872'}, {'name': 'IDL', 'bytes': '1448'}, {'name': 'JavaScript', 'bytes': '43025'}, {'name': 'Lua', 'bytes': '513526'}, {'name': 'OCaml', 'bytes': '6380'}, {'name': 'Objective-C', 'bytes': '158255'}, {'name': 'PHP', 'bytes': '2855'}, {'name': 'Pascal', 'bytes': '40318'}, {'name': 'Perl', 'bytes': '263955'}, {'name': 'Pike', 'bytes': '583'}, {'name': 'Prolog', 'bytes': '935'}, {'name': 'Python', 'bytes': '202527'}, {'name': 'Ruby', 'bytes': '234'}, {'name': 'SAS', 'bytes': '1711'}, {'name': 'Scheme', 'bytes': '9578'}, {'name': 'Shell', 'bytes': '2261018'}, {'name': 'TeX', 'bytes': '144346'}]}
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>c:\users\manue\documents\work\fatima\assets\integratedauthoringtool\dtos\charactersourcedto.cs</title> <script type="text/javascript" src="../js/dotcover.sourceview.js"></script> <link rel="stylesheet" type="text/css" href="../css/dotcover.report.css" /> </head> <body> <pre id="content" class="source-code"> using System; namespace IntegratedAuthoringTool.DTOs { [Serializable] public class CharacterSourceDTO { public int Id { get; set; } public string Source { get; set; } public string RelativePath { get; set; } } } </pre> <script type="text/javascript"> highlightRanges([[8,25,8,29,0],[8,30,8,34,0],[9,32,9,36,0],[9,37,9,41,0],[10,38,10,42,0],[10,43,10,47,0]]); </script> </body> </html>
{'content_hash': '7379e58611fdb36f7da34dfc76f54a67', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 113, 'avg_line_length': 30.620689655172413, 'alnum_prop': 0.6362612612612613, 'repo_name': 'GAIPS-INESC-ID/FAtiMA-Toolkit', 'id': 'f20eb6b3e04edcf3f16138e9a0fc6b823213eb4f', 'size': '888', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'docs/coverage/CoverageReport/src/106.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '389'}, {'name': 'C#', 'bytes': '1299043'}]}
from __future__ import unicode_literals from buffer_tests import * from document_tests import * from inputstream_tests import * from key_binding_tests import * from screen_tests import * from regular_languages_tests import * from layout_tests import * from contrib_tests import * import unittest # Import modules for syntax checking. import prompt_toolkit import prompt_toolkit.application import prompt_toolkit.buffer import prompt_toolkit.clipboard import prompt_toolkit.completion import prompt_toolkit.contrib.completers import prompt_toolkit.contrib.regular_languages import prompt_toolkit.contrib.telnet import prompt_toolkit.contrib.validators import prompt_toolkit.document import prompt_toolkit.enums import prompt_toolkit.eventloop.base import prompt_toolkit.eventloop.inputhook import prompt_toolkit.eventloop.posix import prompt_toolkit.eventloop.posix_utils import prompt_toolkit.eventloop.utils import prompt_toolkit.focus_stack import prompt_toolkit.history import prompt_toolkit.input import prompt_toolkit.interface import prompt_toolkit.key_binding import prompt_toolkit.keys import prompt_toolkit.layout import prompt_toolkit.output import prompt_toolkit.reactive import prompt_toolkit.renderer import prompt_toolkit.search_state import prompt_toolkit.selection import prompt_toolkit.shortcuts import prompt_toolkit.styles import prompt_toolkit.terminal import prompt_toolkit.terminal.vt100_input import prompt_toolkit.terminal.vt100_output import prompt_toolkit.utils import prompt_toolkit.validation if __name__ == '__main__': unittest.main()
{'content_hash': '80a81d3a4a38db3a0b4374d1d290b800', 'timestamp': '', 'source': 'github', 'line_count': 52, 'max_line_length': 47, 'avg_line_length': 30.23076923076923, 'alnum_prop': 0.8377862595419847, 'repo_name': 'amjith/python-prompt-toolkit', 'id': '61ded294dfc2751b01c1bc5bc94dcc3c5126af9b', 'size': '1594', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/run_tests.py', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'Python', 'bytes': '594539'}]}
<!DOCTYPE html> <html> <head> <title>Iniciar Sesi&oacute;n</title> <link type="text/css" rel="stylesheet" href="../css/infotecno.css"/> </head> <body> <div id="screen-header"> <h3><a href="anuncios.html">< Entretenimiento</a></h3> </div><br> <div id="content"> <p>Ven a disfrutar de este parque acu&aacute;tico</p> <img src="images/entre.png" alt="cuartos" height="142" width="242"> </div> <script> tabs = document.getElementsByClassName("tabs")[0]; anunciosTab = tabs.getElementsByClassName("tab")[1]; anunciosTab.setAttribute("class", "tab-active"); </script> </body> </html>
{'content_hash': 'b4f8cb4ce5918ab975d5382bbf78e6b3', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 71, 'avg_line_length': 27.217391304347824, 'alnum_prop': 0.6389776357827476, 'repo_name': 'opgomar/infotecno', 'id': '59db655d535fd4cc421acca1eeca7649633d7680', 'size': '626', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'html/entretenimiento.html', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '6703'}, {'name': 'JavaScript', 'bytes': '502'}, {'name': 'Shell', 'bytes': '41'}]}
import six, hashlib # Use cPickle in python 2 and pickle in python 3 try: import cPickle as pickle except ImportError: import pickle # Adapt hashlib.md5 to eat str in python 3 if six.PY2: md5 = hashlib.md5 else: class md5: def __init__(self, s=None): self.md5 = hashlib.md5() if s is not None: self.update(s) def update(self, s): return self.md5.update(s.encode('utf-8')) def hexdigest(self): return self.md5.hexdigest() def md5hex(s): return md5(s).hexdigest()
{'content_hash': '68eb4ceb2734df0ce68e7c4d4270bd6b', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 53, 'avg_line_length': 22.115384615384617, 'alnum_prop': 0.5878260869565217, 'repo_name': 'th13f/django-cacheops', 'id': '8b1c914630af9766769de90448a96075f7c732ce', 'size': '575', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'cacheops/cross.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Lua', 'bytes': '2959'}, {'name': 'Python', 'bytes': '105318'}]}
package priorities import ( "sync" "github.com/golang/glog" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/util/workqueue" "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates" priorityutil "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) type InterPodAffinity struct { info predicates.NodeInfo nodeLister algorithm.NodeLister podLister algorithm.PodLister hardPodAffinityWeight int failureDomains priorityutil.Topologies } func NewInterPodAffinityPriority( info predicates.NodeInfo, nodeLister algorithm.NodeLister, podLister algorithm.PodLister, hardPodAffinityWeight int, failureDomains []string) algorithm.PriorityFunction { interPodAffinity := &InterPodAffinity{ info: info, nodeLister: nodeLister, podLister: podLister, hardPodAffinityWeight: hardPodAffinityWeight, failureDomains: priorityutil.Topologies{DefaultKeys: failureDomains}, } return interPodAffinity.CalculateInterPodAffinityPriority } type podAffinityPriorityMap struct { sync.Mutex // nodes contain all nodes that should be considered nodes []*v1.Node // counts store the mapping from node name to so-far computed score of // the node. counts map[string]float64 // failureDomains contain default failure domains keys failureDomains priorityutil.Topologies // The first error that we faced. firstError error } func newPodAffinityPriorityMap(nodes []*v1.Node, failureDomains priorityutil.Topologies) *podAffinityPriorityMap { return &podAffinityPriorityMap{ nodes: nodes, counts: make(map[string]float64, len(nodes)), failureDomains: failureDomains, } } func (p *podAffinityPriorityMap) setError(err error) { p.Lock() defer p.Unlock() if p.firstError == nil { p.firstError = err } } func (p *podAffinityPriorityMap) processTerm(term *v1.PodAffinityTerm, podDefiningAffinityTerm, podToCheck *v1.Pod, fixedNode *v1.Node, weight float64) { namespaces := priorityutil.GetNamespacesFromPodAffinityTerm(podDefiningAffinityTerm, term) selector, err := metav1.LabelSelectorAsSelector(term.LabelSelector) if err != nil { p.setError(err) return } match := priorityutil.PodMatchesTermsNamespaceAndSelector(podToCheck, namespaces, selector) if match { func() { p.Lock() defer p.Unlock() for _, node := range p.nodes { if p.failureDomains.NodesHaveSameTopologyKey(node, fixedNode, term.TopologyKey) { p.counts[node.Name] += weight } } }() } } func (p *podAffinityPriorityMap) processTerms(terms []v1.WeightedPodAffinityTerm, podDefiningAffinityTerm, podToCheck *v1.Pod, fixedNode *v1.Node, multiplier int) { for i := range terms { term := &terms[i] p.processTerm(&term.PodAffinityTerm, podDefiningAffinityTerm, podToCheck, fixedNode, float64(term.Weight*int32(multiplier))) } } // compute a sum by iterating through the elements of weightedPodAffinityTerm and adding // "weight" to the sum if the corresponding PodAffinityTerm is satisfied for // that node; the node(s) with the highest sum are the most preferred. // Symmetry need to be considered for preferredDuringSchedulingIgnoredDuringExecution from podAffinity & podAntiAffinity, // symmetry need to be considered for hard requirements from podAffinity func (ipa *InterPodAffinity) CalculateInterPodAffinityPriority(pod *v1.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*v1.Node) (schedulerapi.HostPriorityList, error) { affinity := pod.Spec.Affinity hasAffinityConstraints := affinity != nil && affinity.PodAffinity != nil hasAntiAffinityConstraints := affinity != nil && affinity.PodAntiAffinity != nil allNodeNames := make([]string, 0, len(nodeNameToInfo)) for name := range nodeNameToInfo { allNodeNames = append(allNodeNames, name) } // convert the topology key based weights to the node name based weights var maxCount float64 var minCount float64 // priorityMap stores the mapping from node name to so-far computed score of // the node. pm := newPodAffinityPriorityMap(nodes, ipa.failureDomains) processPod := func(existingPod *v1.Pod) error { existingPodNode, err := ipa.info.GetNodeInfo(existingPod.Spec.NodeName) if err != nil { return err } existingPodAffinity := existingPod.Spec.Affinity existingHasAffinityConstraints := existingPodAffinity != nil && existingPodAffinity.PodAffinity != nil existingHasAntiAffinityConstraints := existingPodAffinity != nil && existingPodAffinity.PodAntiAffinity != nil if hasAffinityConstraints { // For every soft pod affinity term of <pod>, if <existingPod> matches the term, // increment <pm.counts> for every node in the cluster with the same <term.TopologyKey> // value as that of <existingPods>`s node by the term`s weight. terms := affinity.PodAffinity.PreferredDuringSchedulingIgnoredDuringExecution pm.processTerms(terms, pod, existingPod, existingPodNode, 1) } if hasAntiAffinityConstraints { // For every soft pod anti-affinity term of <pod>, if <existingPod> matches the term, // decrement <pm.counts> for every node in the cluster with the same <term.TopologyKey> // value as that of <existingPod>`s node by the term`s weight. terms := affinity.PodAntiAffinity.PreferredDuringSchedulingIgnoredDuringExecution pm.processTerms(terms, pod, existingPod, existingPodNode, -1) } if existingHasAffinityConstraints { // For every hard pod affinity term of <existingPod>, if <pod> matches the term, // increment <pm.counts> for every node in the cluster with the same <term.TopologyKey> // value as that of <existingPod>'s node by the constant <ipa.hardPodAffinityWeight> if ipa.hardPodAffinityWeight > 0 { terms := existingPodAffinity.PodAffinity.RequiredDuringSchedulingIgnoredDuringExecution // TODO: Uncomment this block when implement RequiredDuringSchedulingRequiredDuringExecution. //if len(existingPodAffinity.PodAffinity.RequiredDuringSchedulingRequiredDuringExecution) != 0 { // terms = append(terms, existingPodAffinity.PodAffinity.RequiredDuringSchedulingRequiredDuringExecution...) //} for _, term := range terms { pm.processTerm(&term, existingPod, pod, existingPodNode, float64(ipa.hardPodAffinityWeight)) } } // For every soft pod affinity term of <existingPod>, if <pod> matches the term, // increment <pm.counts> for every node in the cluster with the same <term.TopologyKey> // value as that of <existingPod>'s node by the term's weight. terms := existingPodAffinity.PodAffinity.PreferredDuringSchedulingIgnoredDuringExecution pm.processTerms(terms, existingPod, pod, existingPodNode, 1) } if existingHasAntiAffinityConstraints { // For every soft pod anti-affinity term of <existingPod>, if <pod> matches the term, // decrement <pm.counts> for every node in the cluster with the same <term.TopologyKey> // value as that of <existingPod>'s node by the term's weight. terms := existingPodAffinity.PodAntiAffinity.PreferredDuringSchedulingIgnoredDuringExecution pm.processTerms(terms, existingPod, pod, existingPodNode, -1) } return nil } processNode := func(i int) { nodeInfo := nodeNameToInfo[allNodeNames[i]] if hasAffinityConstraints || hasAntiAffinityConstraints { // We need to process all the nodes. for _, existingPod := range nodeInfo.Pods() { if err := processPod(existingPod); err != nil { pm.setError(err) } } } else { // The pod doesn't have any constraints - we need to check only existing // ones that have some. for _, existingPod := range nodeInfo.PodsWithAffinity() { if err := processPod(existingPod); err != nil { pm.setError(err) } } } } workqueue.Parallelize(16, len(allNodeNames), processNode) if pm.firstError != nil { return nil, pm.firstError } for _, node := range nodes { if pm.counts[node.Name] > maxCount { maxCount = pm.counts[node.Name] } if pm.counts[node.Name] < minCount { minCount = pm.counts[node.Name] } } // calculate final priority score for each node result := make(schedulerapi.HostPriorityList, 0, len(nodes)) for _, node := range nodes { fScore := float64(0) if (maxCount - minCount) > 0 { fScore = 10 * ((pm.counts[node.Name] - minCount) / (maxCount - minCount)) } result = append(result, schedulerapi.HostPriority{Host: node.Name, Score: int(fScore)}) if glog.V(10) { // We explicitly don't do glog.V(10).Infof() to avoid computing all the parameters if this is // not logged. There is visible performance gain from it. glog.V(10).Infof("%v -> %v: InterPodAffinityPriority, Score: (%d)", pod.Name, node.Name, int(fScore)) } } return result, nil }
{'content_hash': '49515c866aae058d3ad2e92cc8317eb2', 'timestamp': '', 'source': 'github', 'line_count': 224, 'max_line_length': 186, 'avg_line_length': 39.86607142857143, 'alnum_prop': 0.7417693169092945, 'repo_name': 'peay/kubernetes', 'id': '7478d63e51261c2ecfe6269aa525e824898328d8', 'size': '9499', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'plugin/pkg/scheduler/algorithm/priorities/interpod_affinity.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '2539'}, {'name': 'Go', 'bytes': '41764458'}, {'name': 'HTML', 'bytes': '2600590'}, {'name': 'Makefile', 'bytes': '76987'}, {'name': 'Nginx', 'bytes': '1608'}, {'name': 'PowerShell', 'bytes': '4261'}, {'name': 'Protocol Buffer', 'bytes': '622561'}, {'name': 'Python', 'bytes': '1350552'}, {'name': 'SaltStack', 'bytes': '55192'}, {'name': 'Shell', 'bytes': '1704660'}]}
J2OBJC_INTERFACE_TYPE_LITERAL_SOURCE(AMHttpProvider)
{'content_hash': '72a60f7edd251c947c565b7dba32cf2d', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 52, 'avg_line_length': 53.0, 'alnum_prop': 0.8679245283018868, 'repo_name': 'yaoliyc/actor-platform', 'id': 'aeb8fff7e4d05a40522d2dc6c05eeddc05157a3d', 'size': '436', 'binary': False, 'copies': '42', 'ref': 'refs/heads/master', 'path': 'actor-apps/core-cocoa/src/im/actor/model/HttpProvider.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '62973'}, {'name': 'HTML', 'bytes': '1914'}, {'name': 'Java', 'bytes': '4039434'}, {'name': 'JavaScript', 'bytes': '188488'}, {'name': 'Kotlin', 'bytes': '23681'}, {'name': 'Objective-C', 'bytes': '6271271'}, {'name': 'PLSQL', 'bytes': '66'}, {'name': 'Protocol Buffer', 'bytes': '20402'}, {'name': 'Ruby', 'bytes': '2686'}, {'name': 'Scala', 'bytes': '960619'}, {'name': 'Shell', 'bytes': '9516'}, {'name': 'Swift', 'bytes': '547698'}]}
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{'content_hash': '5c59913595406997b4c1d571ed105ba4', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': 'e9bec1fe57fbbd539176789acd169fcf39cbac7a', 'size': '199', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Disa/Disa spathulata/ Syn. Herschelianthe spathulata/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
// Type definitions for Apache Cordova Push plugin. // Project: https://github.com/phonegap-build/PushPlugin // Definitions by: Microsoft Open Technologies, Inc. <http://msopentech.com> // Definitions: https://github.com/borisyankov/DefinitelyTyped // // Copyright (c) Microsoft Open Technologies, Inc. // Licensed under the MIT license. interface Window { plugins: Plugins } interface Plugins { /** * This plugin allows to receive push notifications. The Android implementation uses * Google's GCM (Google Cloud Messaging) service, * whereas the iOS version is based on Apple APNS Notifications */ pushNotification: PushNotification } /** * This plugin allows to receive push notifications. The Android implementation uses * Google's GCM (Google Cloud Messaging) service, * whereas the iOS version is based on Apple APNS Notifications */ interface PushNotification { /** * Registers as push notification receiver. * @param successCallback Called when a plugin method returns without error. * @param errorCallback Called when the plugin returns an error. * @param registrationOptions Options for registration process. */ register( successCallback: (registrationId: string) => void, errorCallback: (error: any) => void, registrationOptions: RegistrationOptions): void; /** * Unregisters as push notification receiver. * @param successCallback Called when a plugin method returns without error. * @param errorCallback Called when the plugin returns an error. */ unregister( successCallback: (result: any) => void, errorCallback: (error: any) => void): void; /** * Sets the badge count visible when the app is not running. iOS only. * @param successCallback Called when a plugin method returns without error. * @param errorCallback Called when the plugin returns an error. * @param badgeCount An integer indicating what number should show up in the badge. Passing 0 will clear the badge. */ setApplicationIconBadgeNumber( successCallback: (result: any) => void, errorCallback: (error: any) => void, badgeCount: number): void; } /** Options for registration process. */ interface RegistrationOptions { /** This is the Google project ID you need to obtain by registering your application for GCM. Android only */ senderID?: string; /** WP8 only */ channelName?: string; /** Callback, that is fired when notification arrived */ ecb?: string; badge?: boolean; sound?: boolean; alert?: boolean }
{'content_hash': 'd6a27d0474c437cd4674e8adb53d1d2b', 'timestamp': '', 'source': 'github', 'line_count': 70, 'max_line_length': 124, 'avg_line_length': 38.871428571428574, 'alnum_prop': 0.6736493936052922, 'repo_name': 'nordleif/Memo', 'id': 'd77ed416b26c7eaed18fc640221b28581ec164f5', 'size': '2721', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'scripts/typings/cordova/plugins/Push.d.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '32532'}, {'name': 'C++', 'bytes': '36218'}, {'name': 'CSS', 'bytes': '777720'}, {'name': 'HTML', 'bytes': '136475'}, {'name': 'Java', 'bytes': '37525'}, {'name': 'JavaScript', 'bytes': '719128'}, {'name': 'Objective-C', 'bytes': '45335'}, {'name': 'TypeScript', 'bytes': '20594'}]}
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Inocybe nodulispora Peck ### Remarks null
{'content_hash': '145b62eb204fbb938049ab8653b7e464', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 24, 'avg_line_length': 9.923076923076923, 'alnum_prop': 0.7131782945736435, 'repo_name': 'mdoering/backbone', 'id': 'a8f718e9bcf414461d987bc3300f8999438058cf', 'size': '177', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Inocybaceae/Inocybe/Inocybe nodulispora/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
Quickly deploy OpenStack components in distributed environments.
{'content_hash': '6ecd2986e6c250c999341213acaee56a', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 64, 'avg_line_length': 65.0, 'alnum_prop': 0.8769230769230769, 'repo_name': 'ridewindx/flystack', 'id': '2ae603894cb377e27ff3a3e0de4867e11b87269f', 'size': '76', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '2179'}]}
package org.supercsv.cellprocessor.constraint; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.supercsv.cellprocessor.CellProcessorAdaptor; import org.supercsv.cellprocessor.ift.BoolCellProcessor; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.cellprocessor.ift.DateCellProcessor; import org.supercsv.cellprocessor.ift.DoubleCellProcessor; import org.supercsv.cellprocessor.ift.LongCellProcessor; import org.supercsv.cellprocessor.ift.StringCellProcessor; import org.supercsv.exception.SuperCsvCellProcessorException; import org.supercsv.exception.SuperCsvConstraintViolationException; import org.supercsv.util.CsvContext; /** * This processor ensures that the input value belongs to a specific set of (unchangeable) values. If you want to check * if the value is an element of a (possibly changing) Collection, then use {@link IsElementOf} instead. * * @since 1.50 * @author Dominique De Vito * @author James Bassett */ public class IsIncludedIn extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, DoubleCellProcessor, LongCellProcessor, StringCellProcessor { private final Set<Object> possibleValues = new HashSet<Object>(); /** * Constructs a new <tt>IsIncludedIn</tt> processor, which ensures that the input value belongs to a specific set of * given values. * * @param possibleValues * the Set of values * @throws NullPointerException * if possibleValues is null * @throws IllegalArgumentException * if possibleValues is empty */ public IsIncludedIn(final Set<Object> possibleValues) { super(); checkPreconditions(possibleValues); this.possibleValues.addAll(possibleValues); } /** * Constructs a new <tt>IsIncludedIn</tt> processor, which ensures that the input value belongs to a specific set of * given values, then calls the next processor in the chain. * * @param possibleValues * the Set of values * @param next * the next processor in the chain * @throws NullPointerException * if possibleValues or next is null * @throws IllegalArgumentException * if possibleValues is empty */ public IsIncludedIn(final Set<Object> possibleValues, final CellProcessor next) { super(next); checkPreconditions(possibleValues); this.possibleValues.addAll(possibleValues); } /** * Constructs a new <tt>IsIncludedIn</tt> processor, which ensures that the input value belongs to a specific set of * given values. * * @param possibleValues * the array of values * @throws NullPointerException * if possibleValues is null * @throws IllegalArgumentException * if possibleValues is empty */ public IsIncludedIn(final Object[] possibleValues) { super(); checkPreconditions(possibleValues); Collections.addAll(this.possibleValues, possibleValues); } /** * Constructs a new <tt>IsIncludedIn</tt> processor, which ensures that the input value belongs to a specific set of * given values, then calls the next processor in the chain. * * @param possibleValues * the array of values * @param next * the next processor in the chain * @throws NullPointerException * if possibleValues or next is null * @throws IllegalArgumentException * if possibleValues is empty */ public IsIncludedIn(final Object[] possibleValues, final CellProcessor next) { super(next); checkPreconditions(possibleValues); Collections.addAll(this.possibleValues, possibleValues); } /** * Checks the preconditions for creating a new IsIncludedIn processor with a Set of Objects. * * @param possibleValues * the Set of possible values * @throws NullPointerException * if possibleValues is null * @throws IllegalArgumentException * if possibleValues is empty */ private static void checkPreconditions(final Set<Object> possibleValues) { if( possibleValues == null ) { throw new NullPointerException("possibleValues Set should not be null"); } else if( possibleValues.isEmpty() ) { throw new IllegalArgumentException("possibleValues Set should not be empty"); } } /** * Checks the preconditions for creating a new IsIncludedIn processor with a array of Objects. * * @param possibleValues * the array of possible values * @throws NullPointerException * if possibleValues is null * @throws IllegalArgumentException * if possibleValues is empty */ private static void checkPreconditions(final Object... possibleValues) { if( possibleValues == null ) { throw new NullPointerException("possibleValues array should not be null"); } else if( possibleValues.length == 0 ) { throw new IllegalArgumentException("possibleValues array should not be empty"); } } /** * {@inheritDoc} * * @throws SuperCsvCellProcessorException * if value is null * @throws SuperCsvConstraintViolationException * if value isn't one of the possible values */ public Object execute(final Object value, final CsvContext context) { validateInputNotNull(value, context); if( !possibleValues.contains(value) ) { throw new SuperCsvConstraintViolationException(String.format( "'%s' is not included in the allowed set of values", value), context, this); } return next.execute(value, context); } }
{'content_hash': '00a9fb6a87771bcc9e52687bf49201ce', 'timestamp': '', 'source': 'github', 'line_count': 158, 'max_line_length': 119, 'avg_line_length': 34.90506329113924, 'alnum_prop': 0.7205802357207616, 'repo_name': 'jamesbassett/super-csv', 'id': '6c915f52b4bb0626abb83110743b3db2457e7c4f', 'size': '6120', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'super-csv/src/main/java/org/supercsv/cellprocessor/constraint/IsIncludedIn.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1159572'}]}
PDFKit.configure do |config| config.wkhtmltopdf = '/usr/local/bin/wkhtmltopdf '.to_s.strip config.default_options = { :page_size => 'Letter', :orientation => 'Landscape', :print_media_type => true, :margin_top => '0.35in', :margin_right => '0.25in', :margin_bottom => '0.35in', :margin_left => '0.25in' } config.root_url = "http://localhost" # Use only if your external hostname is unavailable on the server. end
{'content_hash': 'c64930bad929dad4a46303443273730b', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 105, 'avg_line_length': 33.07142857142857, 'alnum_prop': 0.6177105831533477, 'repo_name': 'er1chu/Ziin', 'id': '401574846bf63e52a87cf82c41551e7c71faf7d5', 'size': '463', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'config/initializers/pdfkit.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CoffeeScript', 'bytes': '229'}, {'name': 'JavaScript', 'bytes': '828'}, {'name': 'Ruby', 'bytes': '30246'}]}
@interface FMDatabasePool() - (void)pushDatabaseBackInPool:(FMDatabase*)db; - (FMDatabase*)db; @end @implementation FMDatabasePool @synthesize path=_path; @synthesize delegate=_delegate; @synthesize maximumNumberOfDatabasesToCreate=_maximumNumberOfDatabasesToCreate; + (instancetype)databasePoolWithPath:(NSString*)aPath { return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]); } - (instancetype)initWithPath:(NSString*)aPath { self = [super init]; if (self != nil) { _path = [aPath copy]; _lockQueue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); _databaseInPool = FMDBReturnRetained([NSMutableArray array]); _databaseOutPool = FMDBReturnRetained([NSMutableArray array]); } return self; } - (void)dealloc { _delegate = 0x00; FMDBRelease(_path); FMDBRelease(_databaseInPool); FMDBRelease(_databaseOutPool); if (_lockQueue) { FMDBDispatchQueueRelease(_lockQueue); _lockQueue = 0x00; } #if ! __has_feature(objc_arc) [super dealloc]; #endif } - (void)executeLocked:(void (^)(void))aBlock { dispatch_sync(_lockQueue, aBlock); } - (void)pushDatabaseBackInPool:(FMDatabase*)db { if (!db) { // db can be null if we set an upper bound on the # of databases to create. return; } [self executeLocked:^() { if ([_databaseInPool containsObject:db]) { [[NSException exceptionWithName:@"Database already in pool" reason:@"The FMDatabase being put back into the pool is already present in the pool" userInfo:nil] raise]; } [_databaseInPool addObject:db]; [_databaseOutPool removeObject:db]; }]; } - (FMDatabase*)db { __block FMDatabase *db; [self executeLocked:^() { db = [_databaseInPool lastObject]; if (db) { [_databaseOutPool addObject:db]; [_databaseInPool removeLastObject]; } else { if (_maximumNumberOfDatabasesToCreate) { NSUInteger currentCount = [_databaseOutPool count] + [_databaseInPool count]; if (currentCount >= _maximumNumberOfDatabasesToCreate) { NSLog(@"Maximum number of databases (%ld) has already been reached!", (long)currentCount); return; } } db = [FMDatabase databaseWithPath:_path]; } //This ensures that the db is opened before returning if ([db open]) { if ([_delegate respondsToSelector:@selector(databasePool:shouldAddDatabaseToPool:)] && ![_delegate databasePool:self shouldAddDatabaseToPool:db]) { [db close]; db = 0x00; } else { //It should not get added in the pool twice if lastObject was found if (![_databaseOutPool containsObject:db]) { [_databaseOutPool addObject:db]; } } } else { NSLog(@"Could not open up the database at path %@", _path); db = 0x00; } }]; return db; } - (NSUInteger)countOfCheckedInDatabases { __block NSUInteger count; [self executeLocked:^() { count = [_databaseInPool count]; }]; return count; } - (NSUInteger)countOfCheckedOutDatabases { __block NSUInteger count; [self executeLocked:^() { count = [_databaseOutPool count]; }]; return count; } - (NSUInteger)countOfOpenDatabases { __block NSUInteger count; [self executeLocked:^() { count = [_databaseOutPool count] + [_databaseInPool count]; }]; return count; } - (void)releaseAllDatabases { [self executeLocked:^() { [_databaseOutPool removeAllObjects]; [_databaseInPool removeAllObjects]; }]; } - (void)inDatabase:(void (^)(FMDatabase *db))block { FMDatabase *db = [self db]; block(db); [self pushDatabaseBackInPool:db]; } - (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { BOOL shouldRollback = NO; FMDatabase *db = [self db]; if (useDeferred) { [db beginDeferredTransaction]; } else { [db beginTransaction]; } block(db, &shouldRollback); if (shouldRollback) { [db rollback]; } else { [db commit]; } [self pushDatabaseBackInPool:db]; } - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { [self beginTransaction:YES withBlock:block]; } - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { [self beginTransaction:NO withBlock:block]; } #if SQLITE_VERSION_NUMBER >= 3007000 - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { static unsigned long savePointIdx = 0; NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; BOOL shouldRollback = NO; FMDatabase *db = [self db]; NSError *err = 0x00; if (![db startSavePointWithName:name error:&err]) { [self pushDatabaseBackInPool:db]; return err; } block(db, &shouldRollback); if (shouldRollback) { // We need to rollback and release this savepoint to remove it [db rollbackToSavePointWithName:name error:&err]; } [db releaseSavePointWithName:name error:&err]; [self pushDatabaseBackInPool:db]; return err; } #endif @end
{'content_hash': '439169bb512cd881059d9e1410616ccd', 'timestamp': '', 'source': 'github', 'line_count': 232, 'max_line_length': 178, 'avg_line_length': 24.823275862068964, 'alnum_prop': 0.5860392429241188, 'repo_name': 'kylescript/password', 'id': '52e195155a25a9b3f3ef1039816b7b89b93ba4ea', 'size': '5949', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'password/fmdb/FMDatabasePool.m', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '5349'}, {'name': 'Objective-C', 'bytes': '318857'}]}
package com.hazelcast.collection.impl.queue; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; import com.hazelcast.spi.impl.eventservice.EventFilter; import java.io.IOException; /** * Provides the filtering functionality for Queue events. */ public class QueueEventFilter implements EventFilter, IdentifiedDataSerializable { private boolean includeValue; public QueueEventFilter() { } public QueueEventFilter(boolean includeValue) { this.includeValue = includeValue; } public boolean isIncludeValue() { return includeValue; } @Override public boolean eval(Object arg) { return false; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeBoolean(includeValue); } @Override public void readData(ObjectDataInput in) throws IOException { includeValue = in.readBoolean(); } @Override public int getFactoryId() { return QueueDataSerializerHook.F_ID; } @Override public int getClassId() { return QueueDataSerializerHook.QUEUE_EVENT_FILTER; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } QueueEventFilter that = (QueueEventFilter) o; if (includeValue != that.includeValue) { return false; } return true; } @Override public int hashCode() { return (includeValue ? 1 : 0); } }
{'content_hash': 'e24934958196a5471d8936b3444777dc', 'timestamp': '', 'source': 'github', 'line_count': 78, 'max_line_length': 82, 'avg_line_length': 21.73076923076923, 'alnum_prop': 0.6471976401179941, 'repo_name': 'emre-aydin/hazelcast', 'id': '4e8d7b59a3c7e639896b61aca6d62ca0a324943c', 'size': '2320', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'hazelcast/src/main/java/com/hazelcast/collection/impl/queue/QueueEventFilter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '1261'}, {'name': 'C', 'bytes': '353'}, {'name': 'Java', 'bytes': '39634758'}, {'name': 'Shell', 'bytes': '29479'}]}
module.exports = { jsdoc3 : require('./jsdoc3'), jsduck5 : require('./jsduck5'), closurecompiler : require('./closurecompiler') };
{'content_hash': 'ed485bbd4f0ccace862271083942fc99', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 50, 'avg_line_length': 28.6, 'alnum_prop': 0.6293706293706294, 'repo_name': 'srednakun/bandNameGenerator', 'id': 'f39340edde1497211638dfc756ff7ab6b2aec356', 'size': '143', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'node_modules/grunt-jscs/node_modules/jscs/node_modules/jscs-jsdoc/lib/tags/index.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '873'}, {'name': 'JavaScript', 'bytes': '5225'}]}
ACCEPTED #### According to International Plant Names Index #### Published in Index sem. hort. petrop. 5:36. 1839 #### Original name null ### Remarks null
{'content_hash': '9fa1774e663f074bf99cb3ccc522477f', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 35, 'avg_line_length': 12.076923076923077, 'alnum_prop': 0.7006369426751592, 'repo_name': 'mdoering/backbone', 'id': 'b4e1ab6a23b9dfd23e7598990e297111095f4023', 'size': '222', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Plantaginaceae/Globularia/Globularia trichosantha/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
#ifndef BOOST_FUSION_CONTAINER_SET_DETAIL_DEREF_IMPL_HPP #define BOOST_FUSION_CONTAINER_SET_DETAIL_DEREF_IMPL_HPP #include <boost/fusion/sequence/intrinsic/at.hpp> #include <boost/type_traits/is_const.hpp> namespace boost { namespace fusion { namespace extension { template <typename> struct deref_impl; template <> struct deref_impl<set_iterator_tag> { template <typename It> struct apply { typedef typename result_of::at< typename mpl::if_< is_const<typename It::seq_type> , typename It::seq_type::storage_type const , typename It::seq_type::storage_type >::type , typename It::index >::type type; static type call(It const& it) { return ::boost::fusion::at<typename It::index>(it.seq->get_data()); } }; }; }}} #endif
{'content_hash': '24997ca1fdac38fd053d1536ab5c56bb', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 83, 'avg_line_length': 25.725, 'alnum_prop': 0.5189504373177842, 'repo_name': 'eSDK/esdk_uc_plugin_lync', 'id': '10a03496876e6cb24b4a4a37eae8e6653f7e25da', 'size': '1388', 'binary': False, 'copies': '181', 'ref': 'refs/heads/master', 'path': 'open_src/client/firebreath/src/3rdParty/boost/boost/fusion/container/set/detail/deref_impl.hpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AppleScript', 'bytes': '1632'}, {'name': 'Batchfile', 'bytes': '16231'}, {'name': 'C', 'bytes': '5949477'}, {'name': 'C#', 'bytes': '558674'}, {'name': 'C++', 'bytes': '52962965'}, {'name': 'CMake', 'bytes': '194512'}, {'name': 'CSS', 'bytes': '12560'}, {'name': 'HTML', 'bytes': '90460'}, {'name': 'JavaScript', 'bytes': '5286'}, {'name': 'Makefile', 'bytes': '2269'}, {'name': 'Objective-C', 'bytes': '160617'}, {'name': 'Objective-C++', 'bytes': '78555'}, {'name': 'Perl', 'bytes': '6080'}, {'name': 'Python', 'bytes': '37535'}, {'name': 'Rebol', 'bytes': '980'}, {'name': 'Shell', 'bytes': '315235'}, {'name': 'XSLT', 'bytes': '6256'}]}
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.service.history; import java.util.*; /** * The standard Java Iterator is uni-directional, allowing the user to explore * the contents of a collection in one way only. This interface defines a * bi-directional iterator, permiting the user to go forwards and backwards in a * collection. * * @author Alexander Pelov */ public interface BidirectionalIterator<T> extends Iterator<T> { /** * Returns true if the iteration has elements preceeding the current one. * (In other words, returns true if <tt>prev</tt> would return an element * rather than throwing an exception.) * * @return true if the iterator has preceeding elements. */ boolean hasPrev(); /** * Returns the previous element in the iteration. * * @return the previous element in the iteration. * * @throws NoSuchElementException * iteration has no more elements. */ T prev() throws NoSuchElementException; }
{'content_hash': 'c47e8aaf9a56b226927afccc8ec5411e', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 80, 'avg_line_length': 29.53846153846154, 'alnum_prop': 0.6875, 'repo_name': 'ibauersachs/jitsi', 'id': '08396fd7428a1b6ee910437231b5f66d2d8825a1', 'size': '1152', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'src/net/java/sip/communicator/service/history/BidirectionalIterator.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '423671'}, {'name': 'C++', 'bytes': '464408'}, {'name': 'CSS', 'bytes': '7555'}, {'name': 'Groff', 'bytes': '2384'}, {'name': 'HTML', 'bytes': '5051'}, {'name': 'Java', 'bytes': '21111446'}, {'name': 'Makefile', 'bytes': '12348'}, {'name': 'Mathematica', 'bytes': '21265'}, {'name': 'Objective-C', 'bytes': '171020'}, {'name': 'Shell', 'bytes': '13717'}, {'name': 'Visual Basic', 'bytes': '11032'}, {'name': 'XSLT', 'bytes': '1814'}]}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="../includes/main.css" type="text/css"> <link rel="shortcut icon" href="../favicon.ico" type="image/x-icon"> <title>Apache CloudStack | The Power Behind Your Cloud</title> </head> <body> <div id="insidetopbg"> <div id="inside_wrapper"> <div class="uppermenu_panel"> <div class="uppermenu_box"></div> </div> <div id="main_master"> <div id="inside_header"> <div class="header_top"> <a class="cloud_logo" href="http://cloudstack.org"></a> <div class="mainemenu_panel"></div> </div> </div> <div id="main_content"> <div class="inside_apileftpanel"> <div class="inside_contentpanel" style="width:930px;"> <div class="api_titlebox"> <div class="api_titlebox_left"> <span> Apache CloudStack v4.4.1 Root Admin API Reference </span> <p></p> <h1>changeServiceForSystemVm</h1> <p>Changes the service offering for a system vm (console proxy or secondary storage). The system vm must be in a "Stopped" state for this command to take effect.</p> </div> <div class="api_titlebox_right"> <a class="api_backbutton" href="../TOC_Root_Admin.html"></a> </div> </div> <div class="api_tablepanel"> <h2>Request parameters</h2> <table class="apitable"> <tr class="hed"> <td style="width:200px;"><strong>Parameter Name</strong></td><td style="width:500px;">Description</td><td style="width:180px;">Required</td> </tr> <tr> <td style="width:200px;"><strong>id</strong></td><td style="width:500px;"><strong>The ID of the system vm</strong></td><td style="width:180px;"><strong>true</strong></td> </tr> <tr> <td style="width:200px;"><strong>serviceofferingid</strong></td><td style="width:500px;"><strong>the service offering ID to apply to the system vm</strong></td><td style="width:180px;"><strong>true</strong></td> </tr> <tr> <td style="width:200px;"><i>details</i></td><td style="width:500px;"><i>name value pairs of custom parameters for cpu, memory and cpunumber. example details[i].name=value</i></td><td style="width:180px;"><i>false</i></td> </tr> </table> </div> <div class="api_tablepanel"> <h2>Response Tags</h2> <table class="apitable"> <tr class="hed"> <td style="width:200px;"><strong>Response Name</strong></td><td style="width:500px;">Description</td> </tr> <tr> <td style="width:200px;"><strong>id</strong></td><td style="width:500px;">the ID of the system VM</td> </tr> <tr> <td style="width:200px;"><strong>activeviewersessions</strong></td><td style="width:500px;">the number of active console sessions for the console proxy system vm</td> </tr> <tr> <td style="width:200px;"><strong>created</strong></td><td style="width:500px;">the date and time the system VM was created</td> </tr> <tr> <td style="width:200px;"><strong>dns1</strong></td><td style="width:500px;">the first DNS for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>dns2</strong></td><td style="width:500px;">the second DNS for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>gateway</strong></td><td style="width:500px;">the gateway for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>hostid</strong></td><td style="width:500px;">the host ID for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>hostname</strong></td><td style="width:500px;">the hostname for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>jobid</strong></td><td style="width:500px;">the job ID associated with the system VM. This is only displayed if the router listed is part of a currently running asynchronous job.</td> </tr> <tr> <td style="width:200px;"><strong>jobstatus</strong></td><td style="width:500px;">the job status associated with the system VM. This is only displayed if the router listed is part of a currently running asynchronous job.</td> </tr> <tr> <td style="width:200px;"><strong>linklocalip</strong></td><td style="width:500px;">the link local IP address for the system vm</td> </tr> <tr> <td style="width:200px;"><strong>linklocalmacaddress</strong></td><td style="width:500px;">the link local MAC address for the system vm</td> </tr> <tr> <td style="width:200px;"><strong>linklocalnetmask</strong></td><td style="width:500px;">the link local netmask for the system vm</td> </tr> <tr> <td style="width:200px;"><strong>name</strong></td><td style="width:500px;">the name of the system VM</td> </tr> <tr> <td style="width:200px;"><strong>networkdomain</strong></td><td style="width:500px;">the network domain for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>podid</strong></td><td style="width:500px;">the Pod ID for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>privateip</strong></td><td style="width:500px;">the private IP address for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>privatemacaddress</strong></td><td style="width:500px;">the private MAC address for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>privatenetmask</strong></td><td style="width:500px;">the private netmask for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>publicip</strong></td><td style="width:500px;">the public IP address for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>publicmacaddress</strong></td><td style="width:500px;">the public MAC address for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>publicnetmask</strong></td><td style="width:500px;">the public netmask for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>state</strong></td><td style="width:500px;">the state of the system VM</td> </tr> <tr> <td style="width:200px;"><strong>systemvmtype</strong></td><td style="width:500px;">the system VM type</td> </tr> <tr> <td style="width:200px;"><strong>templateid</strong></td><td style="width:500px;">the template ID for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>zoneid</strong></td><td style="width:500px;">the Zone ID for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>zonename</strong></td><td style="width:500px;">the Zone name for the system VM</td> </tr> </table> </div> </div> </div> </div> </div> <div id="footer"> <div id="comments_thread"> <script type="text/javascript" src="https://comments.apache.org/show_comments.lua?site=test" async="true"></script> <noscript> <iframe width="930" height="500" src="https://comments.apache.org/iframe.lua?site=test&amp;page=4.2.0/rootadmin"></iframe> </noscript> </div> <div id="footer_mainmaster"> <p>Copyright &copy; 2014 The Apache Software Foundation, Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0.</a> <br> Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo and the Apache feather logo are trademarks of The Apache Software Foundation.</p> </div> </div> </div> </div> </body> </html>
{'content_hash': '0396221c541eb05b24a6ce262a1cea09', 'timestamp': '', 'source': 'github', 'line_count': 166, 'max_line_length': 225, 'avg_line_length': 42.48795180722892, 'alnum_prop': 0.6936055579186162, 'repo_name': 'resmo/cloudstack-www', 'id': '5cb6155c2e0eb051adea1f18861c1c157c748c3a', 'size': '7053', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'source/api/apidocs-4.4/root_admin/changeServiceForSystemVm.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '194113'}, {'name': 'HTML', 'bytes': '72884196'}, {'name': 'Ruby', 'bytes': '5038'}, {'name': 'Shell', 'bytes': '861'}]}
package com.thoughtworks.go.server.service; import com.thoughtworks.go.domain.ArtifactUrlReader; import com.thoughtworks.go.domain.JobIdentifier; import com.thoughtworks.go.domain.Stage; import com.thoughtworks.go.domain.StageIdentifier; import com.thoughtworks.go.domain.exception.IllegalArtifactLocationException; import com.thoughtworks.go.server.dao.StageDao; import com.thoughtworks.go.server.view.artifacts.ArtifactDirectoryChooser; import com.thoughtworks.go.server.view.artifacts.BuildIdArtifactLocator; import com.thoughtworks.go.server.view.artifacts.PathBasedArtifactsLocator; import com.thoughtworks.go.util.*; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipInputStream; import static java.lang.String.format; @Service public class ArtifactsService implements ArtifactUrlReader { private final ArtifactsDirHolder artifactsDirHolder; private final ZipUtil zipUtil; private final JobResolverService jobResolverService; private final StageDao stageDao; private SystemService systemService; public static final Logger LOGGER = LoggerFactory.getLogger(ArtifactsService.class); public static final String LOG_XML_NAME = "log.xml"; private ArtifactDirectoryChooser chooser; @Autowired public ArtifactsService(JobResolverService jobResolverService, StageDao stageDao, ArtifactsDirHolder artifactsDirHolder, ZipUtil zipUtil, SystemService systemService) { this(jobResolverService, stageDao, artifactsDirHolder, zipUtil, systemService, new ArtifactDirectoryChooser()); } protected ArtifactsService(JobResolverService jobResolverService, StageDao stageDao, ArtifactsDirHolder artifactsDirHolder, ZipUtil zipUtil, SystemService systemService, ArtifactDirectoryChooser chooser) { this.artifactsDirHolder = artifactsDirHolder; this.zipUtil = zipUtil; this.jobResolverService = jobResolverService; this.stageDao = stageDao; this.systemService = systemService; //This is a Chain of Responsibility to decide which view should be shown for a particular artifact URL this.chooser = chooser; } public void initialize() { chooser.add(new PathBasedArtifactsLocator(artifactsDirHolder.getArtifactsDir())); chooser.add(new BuildIdArtifactLocator(artifactsDirHolder.getArtifactsDir())); } public boolean saveFile(File dest, InputStream stream, boolean shouldUnzip, int attempt) { String destPath = dest.getAbsolutePath(); try { LOGGER.trace("Saving file [{}]", destPath); if (shouldUnzip) { zipUtil.unzip(new ZipInputStream(stream), dest); } else { systemService.streamToFile(stream, dest); } LOGGER.trace("File [{}] saved.", destPath); return true; } catch (IOException e) { final String message = format("Failed to save the file to: [%s]", destPath); if (attempt < GoConstants.PUBLISH_MAX_RETRIES) { LOGGER.warn(message, e); } else { LOGGER.error(message, e); } return false; } catch (IllegalPathException e) { final String message = format("Failed to save the file to: [%s]", destPath); LOGGER.error(message, e); return false; } } public boolean saveOrAppendFile(File dest, InputStream stream) { String destPath = dest.getAbsolutePath(); try { LOGGER.trace("Appending file [{}]", destPath); systemService.streamToFile(stream, dest); LOGGER.trace("File [{}] appended.", destPath); return true; } catch (IOException e) { LOGGER.error("Failed to save the file to : [{}]", destPath, e); return false; } } public File findArtifact(JobIdentifier identifier, String path) throws IllegalArtifactLocationException { return chooser.findArtifact(identifier, path); } @Override public String findArtifactRoot(JobIdentifier identifier) throws IllegalArtifactLocationException { JobIdentifier id = jobResolverService.actualJobIdentifier(identifier); try { String fullArtifactPath = chooser.findArtifact(id, "").getCanonicalPath(); String artifactRoot = artifactsDirHolder.getArtifactsDir().getCanonicalPath(); String relativePath = fullArtifactPath.replace(artifactRoot, ""); if (relativePath.startsWith(File.separator)) { relativePath = relativePath.replaceFirst("\\" + File.separator, ""); } return relativePath; } catch (IOException e) { throw new IllegalArtifactLocationException("No artifact found.", e); } } @Override public String findArtifactUrl(JobIdentifier jobIdentifier) { JobIdentifier actualId = jobResolverService.actualJobIdentifier(jobIdentifier); return format("/files/%s", actualId.buildLocator()); } public String findArtifactUrl(JobIdentifier jobIdentifier, String path) { return format("%s/%s", findArtifactUrl(jobIdentifier), path); } public File getArtifactLocation(String path) throws IllegalArtifactLocationException { try { File file = new File(artifactsDirHolder.getArtifactsDir(), path); if (!FileUtil.isSubdirectoryOf(artifactsDirHolder.getArtifactsDir(), file)) { throw new IllegalArtifactLocationException("Illegal artifact path " + path); } return file; } catch (Exception e) { throw new IllegalArtifactLocationException("Illegal artifact path " + path); } } public void purgeArtifactsForStage(Stage stage) { StageIdentifier stageIdentifier = stage.getIdentifier(); try { File stageRoot = chooser.findArtifact(stageIdentifier, ""); File cachedStageRoot = chooser.findCachedArtifact(stageIdentifier); deleteFile(cachedStageRoot); boolean didDelete = deleteArtifactsExceptCruiseOutputAndPluggableArtifactMetadata(stageRoot); if (!didDelete) { LOGGER.error("Artifacts for stage '{}' at path '{}' was not deleted", stageIdentifier.entityLocator(), stageRoot.getAbsolutePath()); } } catch (Exception e) { LOGGER.error("Error occurred while clearing artifacts for '{}'. Error: '{}'", stageIdentifier.entityLocator(), e.getMessage(), e); } stageDao.markArtifactsDeletedFor(stage); LOGGER.debug("Marked stage '{}' as artifacts deleted.", stageIdentifier.entityLocator()); } private boolean deleteArtifactsExceptCruiseOutputAndPluggableArtifactMetadata(File stageRoot) throws IOException { File[] jobs = stageRoot.listFiles(); if (jobs == null) { // null if security restricted throw new IOException("Failed to list contents of " + stageRoot); } boolean didDelete = true; for (File jobRoot : jobs) { File[] artifacts = jobRoot.listFiles(); if (artifacts == null) { // null if security restricted throw new IOException("Failed to list contents of " + stageRoot); } for (File artifact : artifacts) { if (artifact.isDirectory() && (artifact.getName().equals(ArtifactLogUtil.CRUISE_OUTPUT_FOLDER) || artifact.getName().equals(ArtifactLogUtil.PLUGGABLE_ARTIFACT_METADATA_FOLDER))) { continue; } didDelete &= deleteFile(artifact); } } return didDelete; } private boolean deleteFile(File file) { return FileUtils.deleteQuietly(file); } }
{'content_hash': 'a7ae0888a912654dfe3b431ddf6fb1bd', 'timestamp': '', 'source': 'github', 'line_count': 188, 'max_line_length': 195, 'avg_line_length': 43.15425531914894, 'alnum_prop': 0.6706520399359054, 'repo_name': 'ibnc/gocd', 'id': '931b554c391d51b0f945594f5da63d536642f6e6', 'size': '8714', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'server/src/main/java/com/thoughtworks/go/server/service/ArtifactsService.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '466'}, {'name': 'CSS', 'bytes': '833927'}, {'name': 'FreeMarker', 'bytes': '9764'}, {'name': 'Groovy', 'bytes': '2043806'}, {'name': 'HTML', 'bytes': '644360'}, {'name': 'Java', 'bytes': '20536854'}, {'name': 'JavaScript', 'bytes': '2679628'}, {'name': 'NSIS', 'bytes': '23526'}, {'name': 'PowerShell', 'bytes': '691'}, {'name': 'Ruby', 'bytes': '1952239'}, {'name': 'Shell', 'bytes': '169149'}, {'name': 'TSQL', 'bytes': '200114'}, {'name': 'TypeScript', 'bytes': '2964749'}, {'name': 'XSLT', 'bytes': '200357'}]}
<!--- category: AudioVideoAndCamera samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=620607 ---> # Spatial audio sample This sample demonstrates how to render spatial audio using HRTF xAPO and XAudio2 API within Universal Applications. Specifically, this sample covers hosting the HRTF xAPO in an XAudio2 graph for rendering sources with different spatial locations, radiation patterns and distance decay behaviors. You can choose one of the following three scenarios: - Omnidirectional source with natural distance decay. - Cardioid source with natural distance decay. - Omnidirectional source with custom distance decay. ### Omnidirectional source with natural distance decay "Play" button starts playback from an omnidirectional source which starts orbiting around the listener's head. The sliders control the radius and height of orbit. ### Cardioid source with natural distance decay. "Play" button starts playback from a source with Cardioid radiation pattern. The sliders control the orientation of the source and the shape of the radiation pattern. ### Omnidirectional source with custom distance decay. "Play" button starts playback from an omnidiretional source. The sliders allow control the location of the source. **Note** The Windows universal samples require Visual Studio 2015 to build and Windows 10 to execute. To obtain information about Windows 10 development, go to the [Windows Dev Center](https://dev.windows.com) To obtain information about Microsoft Visual Studio 2015 and the tools for developing Windows apps, go to [Visual Studio 2015](http://go.microsoft.com/fwlink/?LinkID=532422) ### Remark HRTF xAPO API is present but nonfunctional on Phone devices. ## Reference * [XAudio2 API](https://msdn.microsoft.com/en-us/library/windows/desktop/hh405049(v=vs.85).aspx) * [IXAPOHrtfParameters] (https://msdn.microsoft.com/en-us/library/windows/desktop/mt186608(v=vs.85).aspx) ## System requirements **Client:** Windows 10 **Phone:** Not supported ## Build the sample 1. If you download the samples ZIP, be sure to unzip the entire archive, not just the folder with the sample you want to build. 2. Start Microsoft Visual Studio 2015 and select **File** \> **Open** \> **Project/Solution**. 3. Starting in the folder where you unzipped the samples, go to the Samples subfolder, then the subfolder for this specific sample, then the subfolder for your preferred language (C++, C#, or JavaScript). Double-click the Visual Studio 2015 Solution (.sln) file. 4. Press Ctrl+Shift+B, or select **Build** \> **Build Solution**. ## Run the sample The next steps depend on whether you just want to deploy the sample or you want to both deploy and run it. ### Deploying the sample - Select Build > Deploy Solution. ### Deploying and running the sample - To debug the sample and then run it, press F5 or select Debug > Start Debugging. To run the sample without debugging, press Ctrl+F5 or selectDebug > Start Without Debugging. Spatial sound requires headphones.
{'content_hash': '453fa14471cc6d310b3e7ce5c821206a', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 262, 'avg_line_length': 45.059701492537314, 'alnum_prop': 0.7747598542563763, 'repo_name': 'alexpisquared/Windows-universal-samples', 'id': 'cdf654e8aa8bdebec81a095df5b0e9ea59e60565', 'size': '3019', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'Samples/SpatialSound/README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '2648'}, {'name': 'C', 'bytes': '2825'}, {'name': 'C#', 'bytes': '15946'}, {'name': 'C++', 'bytes': '214184'}, {'name': 'CSS', 'bytes': '486563'}, {'name': 'HLSL', 'bytes': '6845'}, {'name': 'HTML', 'bytes': '7923'}, {'name': 'JavaScript', 'bytes': '4205880'}, {'name': 'Visual Basic', 'bytes': '8199'}]}
package jrds.probe.jdbc; import java.net.MalformedURLException; import java.net.URL; import java.sql.Driver; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jrds.Probe; import jrds.ProbeDesc; import jrds.Util; import jrds.factories.ProbeBean; import jrds.probe.IndexedProbe; import jrds.probe.UrlProbe; import org.apache.log4j.Level; @ProbeBean({"port", "user", "password"}) public abstract class JdbcProbe extends Probe<String, Number> implements UrlProbe, IndexedProbe { static final void registerDriver(String JdbcDriver) { try { Driver jdbcDriver = (Driver) Class.forName (JdbcDriver).newInstance(); DriverManager.registerDriver(jdbcDriver); } catch (Exception e) { throw new RuntimeException("Can't register JDBC driver " + JdbcDriver, e); } } static final void registerDriver(Class<?> JdbcDriver) { try { Driver jdbcDriver = (Driver) JdbcDriver.newInstance(); DriverManager.registerDriver(jdbcDriver); } catch (Exception e) { throw new RuntimeException("Can't register JDBC driver " + JdbcDriver, e); } } private int port; protected final JdbcStarter starter; public JdbcProbe() { super(); starter = setStarter(); } public JdbcProbe(ProbeDesc pd) { super(pd); starter = setStarter(); } public void configure() { registerStarter(starter); } public void configure(int port, String user, String passwd) { this.port = port; starter.setPasswd(passwd); starter.setUser(user); starter.setHost(getHost()); registerStarter(starter); } public void configure(int port, String user, String passwd, String dbName) { this.port = port; starter.setDbName(dbName); starter.setPasswd(passwd); starter.setUser(user); starter.setHost(getHost()); registerStarter(starter); } @Override public String getName() { return "jdbc-" + Util.stringSignature(getUrlAsString()); } abstract JdbcStarter setStarter(); public Map<String, Number> getNewSampleValues() { Map<String, Number> retValue = new HashMap<String, Number>(getPd().getSize()); for(String query: getQueries()) { log(Level.DEBUG, "Getting %s", query); retValue.putAll(select2Map(query)); } return retValue; } public abstract List<String> getQueries(); protected List<Map<String, Object>> parseRsVerticaly(ResultSet rs, boolean numFilter) throws SQLException { ArrayList<Map<String, Object>> values = new ArrayList<Map<String, Object>>(); ResultSetMetaData rsmd = rs.getMetaData(); int colCount = rsmd.getColumnCount(); log(Level.DEBUG, "Columns: %d", colCount); while(rs.next()) { Map<String, Object> row = new HashMap<String, Object>(colCount); String key = rs.getObject(1).toString(); Object oValue = rs.getObject(2).toString(); row.put(key, oValue); values.add(row); } values.trimToSize(); return values; } protected List<Map<String, Object>> parseRsHorizontaly(ResultSet rs, boolean numFilter) throws SQLException { ArrayList<Map<String, Object>> values = new ArrayList<Map<String, Object>>(); ResultSetMetaData rsmd = rs.getMetaData(); int colCount = rsmd.getColumnCount(); while(rs.next()) { Map<String, Object> row = new HashMap<String, Object>(colCount); for (int i = 1; i <= colCount; i++) { String key = rsmd.getColumnLabel(i); Object oValue = rs.getObject(i); if(numFilter && !(oValue instanceof Number)) { oValue = Double.NaN; } row.put(key, oValue); } values.add(row); } values.trimToSize(); return values; } public abstract Map<String, Number> parseRs(ResultSet rs) throws SQLException; /** * Parse all the collumns of a query and return a List of Map * where the column name is the key * @param query * @return a List of Map of values */ public Map<String, Number> select2Map(String query) { Map<String, Number> values = new HashMap<String, Number>(); try { Statement stmt = starter.getStatment(); if(stmt.execute(query)) { do { values = parseRs(stmt.getResultSet()); } while(stmt.getMoreResults()); } else { log(Level.WARN, "Not a select query"); } stmt.close(); } catch (SQLException e) { log(Level.ERROR, e, "SQL Error: " + e); } return values; } public Map<String, Object> select2Map(String query, String keyCol, String valCol) { Map<String, Object> values = new HashMap<String, Object>(); log(Level.DEBUG, "Getting %s", query); Statement stmt; try { stmt = starter.getStatment(); if(stmt.execute(query)) { do { ResultSet rs = stmt.getResultSet(); while(rs.next()) { String key = rs.getString(keyCol); Number value; Object oValue = rs.getObject(valCol); if(oValue instanceof Number) value = (Number) oValue; else value = new Double(Double.NaN); values.put(key, value); } } while(stmt.getMoreResults()); } stmt.close(); } catch (SQLException e) { log(Level.ERROR, e, "SQL Error: %s", e.getLocalizedMessage()); } return values; } /** * @return Returns the port. */ public Integer getPort() { return port; } /** * @param port The port to set. */ public void setPort(Integer port) { this.port = port; } /** * @return Returns the user. */ public String getUser() { return starter.getUser(); } /** * @param user The user to set. */ public void setUser(String user) { starter.setUser(user); } /** * @return Returns the user. */ public String getPassword() { return starter.getPasswd(); } /** * @param password The user to set. */ public void setPassword(String password) { starter.setPasswd(password); } /** * @return Returns the dbName. */ public String getDbName() { return starter.getDbName(); } /** * @param dbName */ public void setDbName(String dbName) { starter.setDbName(dbName); } public String getUrlAsString() { return starter.getUrlAsString(); } @Override public boolean isCollectRunning() { return super.isCollectRunning() && starter.isStarted(); } @Override public String getSourceType() { return "JDBC"; } @Override public long getUptime() { return starter.getUptime(); } public String getIndexName() { return starter.getDbName(); } /* (non-Javadoc) * @see jrds.probe.UrlProbe#getUrl() */ public URL getUrl(){ URL newurl = null; try { newurl = new URL(getUrlAsString()); } catch (MalformedURLException e) { log(Level.ERROR, e, "Invalid jdbc url: " + getUrlAsString()); } return newurl; } }
{'content_hash': '8f916c3140182eafccb015eb39fc96ee', 'timestamp': '', 'source': 'github', 'line_count': 282, 'max_line_length': 113, 'avg_line_length': 28.50354609929078, 'alnum_prop': 0.5641950734013437, 'repo_name': 'qwer233968/Mycat-Web', 'id': '08f46ea7b163c126aab3987136ec3d22bda8820e', 'size': '8038', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'mycat-web-server/src/main/java/jrds/probe/jdbc/JdbcProbe.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '381'}, {'name': 'CSS', 'bytes': '243445'}, {'name': 'HTML', 'bytes': '97209'}, {'name': 'Java', 'bytes': '157678'}, {'name': 'JavaScript', 'bytes': '586933'}, {'name': 'Shell', 'bytes': '381'}]}
def good_guess?(num) if num == 42 return true else return false end end
{'content_hash': '9f34ef6e249e08c90eb67846f53614da', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 20, 'avg_line_length': 12.142857142857142, 'alnum_prop': 0.6235294117647059, 'repo_name': 'tommchenry/phase-0', 'id': '4d3de39ee66c60cf3ae450eef3b8090a6148552a', 'size': '255', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'week-4/flow-control/good-guess/my_solution.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4975'}, {'name': 'HTML', 'bytes': '21022'}, {'name': 'JavaScript', 'bytes': '54023'}, {'name': 'Ruby', 'bytes': '147585'}]}
<?php final class DifferentialRevision extends DifferentialDAO implements PhabricatorTokenReceiverInterface, PhabricatorPolicyInterface, PhabricatorExtendedPolicyInterface, PhabricatorFlaggableInterface, PhrequentTrackableInterface, HarbormasterBuildableInterface, PhabricatorSubscribableInterface, PhabricatorCustomFieldInterface, PhabricatorApplicationTransactionInterface, PhabricatorMentionableInterface, PhabricatorDestructibleInterface, PhabricatorProjectInterface, PhabricatorFulltextInterface { protected $title = ''; protected $originalTitle; protected $status; protected $summary = ''; protected $testPlan = ''; protected $authorPHID; protected $lastReviewerPHID; protected $lineCount = 0; protected $attached = array(); protected $mailKey; protected $branchName; protected $repositoryPHID; protected $viewPolicy = PhabricatorPolicies::POLICY_USER; protected $editPolicy = PhabricatorPolicies::POLICY_USER; private $relationships = self::ATTACHABLE; private $commits = self::ATTACHABLE; private $activeDiff = self::ATTACHABLE; private $diffIDs = self::ATTACHABLE; private $hashes = self::ATTACHABLE; private $repository = self::ATTACHABLE; private $reviewerStatus = self::ATTACHABLE; private $customFields = self::ATTACHABLE; private $drafts = array(); private $flags = array(); const TABLE_COMMIT = 'differential_commit'; const RELATION_REVIEWER = 'revw'; const RELATION_SUBSCRIBED = 'subd'; public static function initializeNewRevision(PhabricatorUser $actor) { $app = id(new PhabricatorApplicationQuery()) ->setViewer($actor) ->withClasses(array('PhabricatorDifferentialApplication')) ->executeOne(); $view_policy = $app->getPolicy( DifferentialDefaultViewCapability::CAPABILITY); return id(new DifferentialRevision()) ->setViewPolicy($view_policy) ->setAuthorPHID($actor->getPHID()) ->attachRelationships(array()) ->attachRepository(null) ->setStatus(ArcanistDifferentialRevisionStatus::NEEDS_REVIEW); } protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_SERIALIZATION => array( 'attached' => self::SERIALIZATION_JSON, 'unsubscribed' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'title' => 'text255', 'originalTitle' => 'text255', 'status' => 'text32', 'summary' => 'text', 'testPlan' => 'text', 'authorPHID' => 'phid?', 'lastReviewerPHID' => 'phid?', 'lineCount' => 'uint32?', 'mailKey' => 'bytes40', 'branchName' => 'text255?', 'repositoryPHID' => 'phid?', ), self::CONFIG_KEY_SCHEMA => array( 'key_phid' => null, 'phid' => array( 'columns' => array('phid'), 'unique' => true, ), 'authorPHID' => array( 'columns' => array('authorPHID', 'status'), ), 'repositoryPHID' => array( 'columns' => array('repositoryPHID'), ), // If you (or a project you are a member of) is reviewing a significant // fraction of the revisions on an install, the result set of open // revisions may be smaller than the result set of revisions where you // are a reviewer. In these cases, this key is better than keys on the // edge table. 'key_status' => array( 'columns' => array('status', 'phid'), ), ), ) + parent::getConfiguration(); } public function getMonogram() { $id = $this->getID(); return "D{$id}"; } public function setTitle($title) { $this->title = $title; if (!$this->getID()) { $this->originalTitle = $title; } return $this; } public function loadIDsByCommitPHIDs($phids) { if (!$phids) { return array(); } $revision_ids = queryfx_all( $this->establishConnection('r'), 'SELECT * FROM %T WHERE commitPHID IN (%Ls)', self::TABLE_COMMIT, $phids); return ipull($revision_ids, 'revisionID', 'commitPHID'); } public function loadCommitPHIDs() { if (!$this->getID()) { return ($this->commits = array()); } $commits = queryfx_all( $this->establishConnection('r'), 'SELECT commitPHID FROM %T WHERE revisionID = %d', self::TABLE_COMMIT, $this->getID()); $commits = ipull($commits, 'commitPHID'); return ($this->commits = $commits); } public function getCommitPHIDs() { return $this->assertAttached($this->commits); } public function getActiveDiff() { // TODO: Because it's currently technically possible to create a revision // without an associated diff, we allow an attached-but-null active diff. // It would be good to get rid of this once we make diff-attaching // transactional. return $this->assertAttached($this->activeDiff); } public function attachActiveDiff($diff) { $this->activeDiff = $diff; return $this; } public function getDiffIDs() { return $this->assertAttached($this->diffIDs); } public function attachDiffIDs(array $ids) { rsort($ids); $this->diffIDs = array_values($ids); return $this; } public function attachCommitPHIDs(array $phids) { $this->commits = array_values($phids); return $this; } public function getAttachedPHIDs($type) { return array_keys(idx($this->attached, $type, array())); } public function setAttachedPHIDs($type, array $phids) { $this->attached[$type] = array_fill_keys($phids, array()); return $this; } public function generatePHID() { return PhabricatorPHID::generateNewPHID( DifferentialRevisionPHIDType::TYPECONST); } public function loadActiveDiff() { return id(new DifferentialDiff())->loadOneWhere( 'revisionID = %d ORDER BY id DESC LIMIT 1', $this->getID()); } public function save() { if (!$this->getMailKey()) { $this->mailKey = Filesystem::readRandomCharacters(40); } return parent::save(); } public function loadRelationships() { if (!$this->getID()) { $this->relationships = array(); return; } $data = array(); $subscriber_phids = PhabricatorEdgeQuery::loadDestinationPHIDs( $this->getPHID(), PhabricatorObjectHasSubscriberEdgeType::EDGECONST); $subscriber_phids = array_reverse($subscriber_phids); foreach ($subscriber_phids as $phid) { $data[] = array( 'relation' => self::RELATION_SUBSCRIBED, 'objectPHID' => $phid, 'reasonPHID' => null, ); } $reviewer_phids = PhabricatorEdgeQuery::loadDestinationPHIDs( $this->getPHID(), DifferentialRevisionHasReviewerEdgeType::EDGECONST); $reviewer_phids = array_reverse($reviewer_phids); foreach ($reviewer_phids as $phid) { $data[] = array( 'relation' => self::RELATION_REVIEWER, 'objectPHID' => $phid, 'reasonPHID' => null, ); } return $this->attachRelationships($data); } public function attachRelationships(array $relationships) { $this->relationships = igroup($relationships, 'relation'); return $this; } public function getReviewers() { return $this->getRelatedPHIDs(self::RELATION_REVIEWER); } public function getCCPHIDs() { return $this->getRelatedPHIDs(self::RELATION_SUBSCRIBED); } private function getRelatedPHIDs($relation) { $this->assertAttached($this->relationships); return ipull($this->getRawRelations($relation), 'objectPHID'); } public function getRawRelations($relation) { return idx($this->relationships, $relation, array()); } public function getPrimaryReviewer() { $reviewers = $this->getReviewers(); $last = $this->lastReviewerPHID; if (!$last || !in_array($last, $reviewers)) { return head($this->getReviewers()); } return $last; } public function getHashes() { return $this->assertAttached($this->hashes); } public function attachHashes(array $hashes) { $this->hashes = $hashes; return $this; } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, ); } public function getPolicy($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: return $this->getViewPolicy(); case PhabricatorPolicyCapability::CAN_EDIT: return $this->getEditPolicy(); } } public function hasAutomaticCapability($capability, PhabricatorUser $user) { // A revision's author (which effectively means "owner" after we added // commandeering) can always view and edit it. $author_phid = $this->getAuthorPHID(); if ($author_phid) { if ($user->getPHID() == $author_phid) { return true; } } return false; } public function describeAutomaticCapability($capability) { $description = array( pht('The owner of a revision can always view and edit it.'), ); switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: $description[] = pht("A revision's reviewers can always view it."); $description[] = pht( 'If a revision belongs to a repository, other users must be able '. 'to view the repository in order to view the revision.'); break; } return $description; } /* -( PhabricatorExtendedPolicyInterface )--------------------------------- */ public function getExtendedPolicy($capability, PhabricatorUser $viewer) { $extended = array(); switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: // NOTE: In Differential, an automatic capability on a revision (being // an author) is sufficient to view it, even if you can not see the // repository the revision belongs to. We can bail out early in this // case. if ($this->hasAutomaticCapability($capability, $viewer)) { break; } $repository_phid = $this->getRepositoryPHID(); $repository = $this->getRepository(); // Try to use the object if we have it, since it will save us some // data fetching later on. In some cases, we might not have it. $repository_ref = nonempty($repository, $repository_phid); if ($repository_ref) { $extended[] = array( $repository_ref, PhabricatorPolicyCapability::CAN_VIEW, ); } break; } return $extended; } /* -( PhabricatorTokenReceiverInterface )---------------------------------- */ public function getUsersToNotifyOfTokenGiven() { return array( $this->getAuthorPHID(), ); } public function getReviewerStatus() { return $this->assertAttached($this->reviewerStatus); } public function attachReviewerStatus(array $reviewers) { assert_instances_of($reviewers, 'DifferentialReviewer'); $this->reviewerStatus = $reviewers; return $this; } public function getRepository() { return $this->assertAttached($this->repository); } public function attachRepository(PhabricatorRepository $repository = null) { $this->repository = $repository; return $this; } public function isClosed() { return DifferentialRevisionStatus::isClosedStatus($this->getStatus()); } public function getFlag(PhabricatorUser $viewer) { return $this->assertAttachedKey($this->flags, $viewer->getPHID()); } public function attachFlag( PhabricatorUser $viewer, PhabricatorFlag $flag = null) { $this->flags[$viewer->getPHID()] = $flag; return $this; } public function getDrafts(PhabricatorUser $viewer) { return $this->assertAttachedKey($this->drafts, $viewer->getPHID()); } public function attachDrafts(PhabricatorUser $viewer, array $drafts) { $this->drafts[$viewer->getPHID()] = $drafts; return $this; } /* -( HarbormasterBuildableInterface )------------------------------------- */ public function getHarbormasterBuildablePHID() { return $this->loadActiveDiff()->getPHID(); } public function getHarbormasterContainerPHID() { return $this->getPHID(); } public function getBuildVariables() { return array(); } public function getAvailableBuildVariables() { return array(); } /* -( PhabricatorSubscribableInterface )----------------------------------- */ public function isAutomaticallySubscribed($phid) { if ($phid == $this->getAuthorPHID()) { return true; } // TODO: This only happens when adding or removing CCs, and is safe from a // policy perspective, but the subscription pathway should have some // opportunity to load this data properly. For now, this is the only case // where implicit subscription is not an intrinsic property of the object. if ($this->reviewerStatus == self::ATTACHABLE) { $reviewers = id(new DifferentialRevisionQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withPHIDs(array($this->getPHID())) ->needReviewerStatus(true) ->executeOne() ->getReviewerStatus(); } else { $reviewers = $this->getReviewerStatus(); } foreach ($reviewers as $reviewer) { if ($reviewer->getReviewerPHID() == $phid) { return true; } } return false; } public function shouldShowSubscribersProperty() { return true; } public function shouldAllowSubscription($phid) { return true; } /* -( PhabricatorCustomFieldInterface )------------------------------------ */ public function getCustomFieldSpecificationForRole($role) { return PhabricatorEnv::getEnvConfig('differential.fields'); } public function getCustomFieldBaseClass() { return 'DifferentialCustomField'; } public function getCustomFields() { return $this->assertAttached($this->customFields); } public function attachCustomFields(PhabricatorCustomFieldAttachment $fields) { $this->customFields = $fields; return $this; } /* -( PhabricatorApplicationTransactionInterface )------------------------- */ public function getApplicationTransactionEditor() { return new DifferentialTransactionEditor(); } public function getApplicationTransactionObject() { return $this; } public function getApplicationTransactionTemplate() { return new DifferentialTransaction(); } public function willRenderTimeline( PhabricatorApplicationTransactionView $timeline, AphrontRequest $request) { $viewer = $request->getViewer(); $render_data = $timeline->getRenderData(); $left = $request->getInt('left', idx($render_data, 'left')); $right = $request->getInt('right', idx($render_data, 'right')); $diffs = id(new DifferentialDiffQuery()) ->setViewer($request->getUser()) ->withIDs(array($left, $right)) ->execute(); $diffs = mpull($diffs, null, 'getID'); $left_diff = $diffs[$left]; $right_diff = $diffs[$right]; $old_ids = $request->getStr('old', idx($render_data, 'old')); $new_ids = $request->getStr('new', idx($render_data, 'new')); $old_ids = array_filter(explode(',', $old_ids)); $new_ids = array_filter(explode(',', $new_ids)); $type_inline = DifferentialTransaction::TYPE_INLINE; $changeset_ids = array_merge($old_ids, $new_ids); $inlines = array(); foreach ($timeline->getTransactions() as $xaction) { if ($xaction->getTransactionType() == $type_inline) { $inlines[] = $xaction->getComment(); $changeset_ids[] = $xaction->getComment()->getChangesetID(); } } if ($changeset_ids) { $changesets = id(new DifferentialChangesetQuery()) ->setViewer($request->getUser()) ->withIDs($changeset_ids) ->execute(); $changesets = mpull($changesets, null, 'getID'); } else { $changesets = array(); } foreach ($inlines as $key => $inline) { $inlines[$key] = DifferentialInlineComment::newFromModernComment( $inline); } $query = id(new DifferentialInlineCommentQuery()) ->needHidden(true) ->setViewer($viewer); // NOTE: This is a bit sketchy: this method adjusts the inlines as a // side effect, which means it will ultimately adjust the transaction // comments and affect timeline rendering. $query->adjustInlinesForChangesets( $inlines, array_select_keys($changesets, $old_ids), array_select_keys($changesets, $new_ids), $this); return $timeline ->setChangesets($changesets) ->setRevision($this) ->setLeftDiff($left_diff) ->setRightDiff($right_diff); } /* -( PhabricatorDestructibleInterface )----------------------------------- */ public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { $this->openTransaction(); $diffs = id(new DifferentialDiffQuery()) ->setViewer($engine->getViewer()) ->withRevisionIDs(array($this->getID())) ->execute(); foreach ($diffs as $diff) { $engine->destroyObject($diff); } $conn_w = $this->establishConnection('w'); queryfx( $conn_w, 'DELETE FROM %T WHERE revisionID = %d', self::TABLE_COMMIT, $this->getID()); // we have to do paths a little differentally as they do not have // an id or phid column for delete() to act on $dummy_path = new DifferentialAffectedPath(); queryfx( $conn_w, 'DELETE FROM %T WHERE revisionID = %d', $dummy_path->getTableName(), $this->getID()); $this->delete(); $this->saveTransaction(); } /* -( PhabricatorFulltextInterface )--------------------------------------- */ public function newFulltextEngine() { return new DifferentialRevisionFulltextEngine(); } }
{'content_hash': 'a6cdedc1b41cc385a1f32349869d109b', 'timestamp': '', 'source': 'github', 'line_count': 642, 'max_line_length': 80, 'avg_line_length': 28.213395638629283, 'alnum_prop': 0.6304311820239606, 'repo_name': 'christopher-johnson/phabricator', 'id': 'e534ad9ca7755d5ecef72ac2a09970e70afccc69', 'size': '18113', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/applications/differential/storage/DifferentialRevision.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '356'}, {'name': 'C', 'bytes': '160255'}, {'name': 'CSS', 'bytes': '323980'}, {'name': 'Cucumber', 'bytes': '10844'}, {'name': 'Groff', 'bytes': '30134'}, {'name': 'JavaScript', 'bytes': '846540'}, {'name': 'Makefile', 'bytes': '9933'}, {'name': 'PHP', 'bytes': '13775256'}, {'name': 'Python', 'bytes': '7385'}, {'name': 'Shell', 'bytes': '30657'}]}
import React, { PropTypes } from 'react'; import map from 'lodash/map'; var Message = ({ mapList }) => { return map(mapList, index => { return <div />; }); }; Message.propTypes = process.env.NODE_ENV !== "production" ? { mapList: PropTypes.array.isRequired } : {}; export default Message;
{'content_hash': '873aad5aee03881e91207b93e8274e1f', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 61, 'avg_line_length': 20.2, 'alnum_prop': 0.6336633663366337, 'repo_name': 'oliviertassinari/babel-plugin-transform-react-remove-prop-types', 'id': '0a182e33b0f3d198693c85c88e0fb70c082b925d', 'size': '303', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/fixtures/stateless-arrow-return-function/expected-wrap-es6.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '28528'}]}
package main import ( "compress/gzip" "crypto/tls" "errors" "flag" "fmt" "github.com/bitly/nsq/nsq" "github.com/bitly/nsq/util" "log" "os" "os/signal" "path" "strings" "syscall" "time" ) var ( datetimeFormat = flag.String("datetime-format", "%Y-%m-%d_%H", "strftime compatible format for <DATETIME> in filename format") filenameFormat = flag.String("filename-format", "<TOPIC>.<HOST><GZIPREV>.<DATETIME>.log", "output filename format (<TOPIC>, <HOST>, <DATETIME>, <GZIPREV> are replaced. <GZIPREV> is a suffix when an existing gzip file already exists)") showVersion = flag.Bool("version", false, "print version string") hostIdentifier = flag.String("host-identifier", "", "value to output in log filename in place of hostname. <SHORT_HOST> and <HOSTNAME> are valid replacement tokens") outputDir = flag.String("output-dir", "/tmp", "directory to write output files to") topic = flag.String("topic", "", "nsq topic") channel = flag.String("channel", "nsq_to_file", "nsq channel") maxInFlight = flag.Int("max-in-flight", 1000, "max number of messages to allow in flight") gzipCompression = flag.Int("gzip-compression", 3, "gzip compression level. 1 BestSpeed, 2 BestCompression, 3 DefaultCompression") gzipEnabled = flag.Bool("gzip", false, "gzip output files.") verbose = flag.Bool("verbose", false, "verbose logging") skipEmptyFiles = flag.Bool("skip-empty-files", false, "Skip writting empty files") nsqdTCPAddrs = util.StringArray{} lookupdHTTPAddrs = util.StringArray{} tlsEnabled = flag.Bool("tls", false, "enable TLS") tlsInsecureSkipVerify = flag.Bool("tls-insecure-skip-verify", false, "disable TLS server certificate validation") ) func init() { flag.Var(&nsqdTCPAddrs, "nsqd-tcp-address", "nsqd TCP address (may be given multiple times)") flag.Var(&lookupdHTTPAddrs, "lookupd-http-address", "lookupd HTTP address (may be given multiple times)") } type FileLogger struct { out *os.File gzipWriter *gzip.Writer lastFilename string logChan chan *Message compressionLevel int gzipEnabled bool filenameFormat string ExitChan chan int } type Message struct { *nsq.Message returnChannel chan *nsq.FinishedMessage } type SyncMsg struct { m *nsq.FinishedMessage returnChannel chan *nsq.FinishedMessage } func (l *FileLogger) HandleMessage(m *nsq.Message, responseChannel chan *nsq.FinishedMessage) { l.logChan <- &Message{m, responseChannel} } func (f *FileLogger) router(r *nsq.Reader, termChan chan os.Signal, hupChan chan os.Signal) { pos := 0 output := make([]*Message, *maxInFlight) sync := false ticker := time.NewTicker(time.Duration(30) * time.Second) closing := false closeFile := false exit := false for { select { case <-r.ExitChan: sync = true closeFile = true exit = true case <-termChan: ticker.Stop() r.Stop() sync = true closing = true case <-hupChan: sync = true closeFile = true case <-ticker.C: if f.needsFileRotate() { if *skipEmptyFiles { closeFile = true } else { f.updateFile() } } sync = true case m := <-f.logChan: if f.updateFile() { sync = true } _, err := f.Write(m.Body) if err != nil { log.Fatalf("ERROR: writing message to disk - %s", err.Error()) } _, err = f.Write([]byte("\n")) if err != nil { log.Fatalf("ERROR: writing newline to disk - %s", err.Error()) } output[pos] = m pos++ if pos == *maxInFlight { sync = true } } if closing || sync || r.IsStarved() { if pos > 0 { log.Printf("syncing %d records to disk", pos) err := f.Sync() if err != nil { log.Fatalf("ERROR: failed syncing messages - %s", err.Error()) } for pos > 0 { pos-- m := output[pos] m.returnChannel <- &nsq.FinishedMessage{m.Id, 0, true} output[pos] = nil } } sync = false } if closeFile { f.Close() closeFile = false } if exit { close(f.ExitChan) break } } } func (f *FileLogger) Close() { if f.out != nil { if f.gzipWriter != nil { f.gzipWriter.Close() } f.out.Close() f.out = nil } } func (f *FileLogger) Write(p []byte) (n int, err error) { if f.gzipWriter != nil { return f.gzipWriter.Write(p) } return f.out.Write(p) } func (f *FileLogger) Sync() error { var err error if f.gzipWriter != nil { f.gzipWriter.Close() err = f.out.Sync() f.gzipWriter, _ = gzip.NewWriterLevel(f.out, f.compressionLevel) } else { err = f.out.Sync() } return err } func (f *FileLogger) calculateCurrentFilename() string { t := time.Now() datetime := strftime(*datetimeFormat, t) filename := strings.Replace(f.filenameFormat, "<DATETIME>", datetime, -1) if !f.gzipEnabled { filename = strings.Replace(filename, "<GZIPREV>", "", -1) } return filename } func (f *FileLogger) needsFileRotate() bool { filename := f.calculateCurrentFilename() return filename != f.lastFilename } func (f *FileLogger) updateFile() bool { filename := f.calculateCurrentFilename() maxGzipRevisions := 1000 if filename != f.lastFilename || f.out == nil { f.Close() os.MkdirAll(*outputDir, 777) var newFile *os.File var err error if f.gzipEnabled { // for gzip files, we never append to an existing file // we try to create different revisions, replacing <GZIPREV> in the filename for gzipRevision := 0; gzipRevision < maxGzipRevisions; gzipRevision += 1 { var revisionSuffix string if gzipRevision > 0 { revisionSuffix = fmt.Sprintf("-%d", gzipRevision) } tempFilename := strings.Replace(filename, "<GZIPREV>", revisionSuffix, -1) fullPath := path.Join(*outputDir, tempFilename) newFile, err = os.OpenFile(fullPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666) if err != nil && os.IsExist(err) { log.Printf("INFO: file already exists: %s", fullPath) continue } if err != nil { log.Fatalf("ERROR: %s Unable to open %s", err, fullPath) } log.Printf("opening %s", fullPath) break } if newFile == nil { log.Fatalf("ERROR: Unable to open a new gzip file after %d tries", maxGzipRevisions) } } else { log.Printf("opening %s/%s", *outputDir, filename) newFile, err = os.OpenFile(path.Join(*outputDir, filename), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { log.Fatal(err) } } f.out = newFile f.lastFilename = filename if f.gzipEnabled { f.gzipWriter, _ = gzip.NewWriterLevel(newFile, f.compressionLevel) } return true } return false } func NewFileLogger(gzipEnabled bool, compressionLevel int, filenameFormat string) (*FileLogger, error) { var speed int switch compressionLevel { case 1: speed = gzip.BestSpeed case 2: speed = gzip.BestCompression case 3: speed = gzip.DefaultCompression } if gzipEnabled && strings.Index(filenameFormat, "<GZIPREV>") == -1 { return nil, errors.New("missing <GZIPREV> in filenameFormat") } hostname, err := os.Hostname() if err != nil { return nil, err } shortHostname := strings.Split(hostname, ".")[0] identifier := shortHostname if len(*hostIdentifier) != 0 { identifier = strings.Replace(*hostIdentifier, "<SHORT_HOST>", shortHostname, -1) identifier = strings.Replace(identifier, "<HOSTNAME>", hostname, -1) } filenameFormat = strings.Replace(filenameFormat, "<TOPIC>", *topic, -1) filenameFormat = strings.Replace(filenameFormat, "<HOST>", identifier, -1) if gzipEnabled && !strings.HasSuffix(filenameFormat, ".gz") { filenameFormat = filenameFormat + ".gz" } f := &FileLogger{ logChan: make(chan *Message, 1), compressionLevel: speed, filenameFormat: filenameFormat, gzipEnabled: gzipEnabled, ExitChan: make(chan int), } return f, nil } func main() { flag.Parse() if *showVersion { fmt.Printf("nsq_to_file v%s\n", util.BINARY_VERSION) return } if *topic == "" || *channel == "" { log.Fatalf("--topic and --channel are required") } if *maxInFlight <= 0 { log.Fatalf("--max-in-flight must be > 0") } if len(nsqdTCPAddrs) == 0 && len(lookupdHTTPAddrs) == 0 { log.Fatalf("--nsqd-tcp-address or --lookupd-http-address required.") } if len(nsqdTCPAddrs) != 0 && len(lookupdHTTPAddrs) != 0 { log.Fatalf("use --nsqd-tcp-address or --lookupd-http-address not both") } if *gzipCompression < 1 || *gzipCompression > 3 { log.Fatalf("invalid --gzip-compresion value (%v). should be 1,2 or 3", *gzipCompression) } hupChan := make(chan os.Signal, 1) termChan := make(chan os.Signal, 1) signal.Notify(hupChan, syscall.SIGHUP) signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM) f, err := NewFileLogger(*gzipEnabled, *gzipCompression, *filenameFormat) if err != nil { log.Fatal(err.Error()) } r, err := nsq.NewReader(*topic, *channel) if err != nil { log.Fatalf(err.Error()) } r.SetMaxInFlight(*maxInFlight) r.VerboseLogging = *verbose if *tlsEnabled { r.TLSv1 = true r.TLSConfig = &tls.Config{ InsecureSkipVerify: *tlsInsecureSkipVerify, } } r.AddAsyncHandler(f) go f.router(r, termChan, hupChan) for _, addrString := range nsqdTCPAddrs { err := r.ConnectToNSQ(addrString) if err != nil { log.Fatalf(err.Error()) } } for _, addrString := range lookupdHTTPAddrs { log.Printf("lookupd addr %s", addrString) err := r.ConnectToLookupd(addrString) if err != nil { log.Fatalf(err.Error()) } } <-f.ExitChan }
{'content_hash': '141e7954808b65042d50154f74af4837', 'timestamp': '', 'source': 'github', 'line_count': 356, 'max_line_length': 237, 'avg_line_length': 26.553370786516854, 'alnum_prop': 0.6562995874325611, 'repo_name': 'blueplus/nsq', 'id': 'f8326557d925fccdb0b934b6dbb69be618cbe93e', 'size': '9531', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'examples/nsq_to_file/nsq_to_file.go', 'mode': '33188', 'license': 'mit', 'language': []}
package org.cagrid.gridgrouper.test.system.steps; import gov.nih.nci.cagrid.gridgrouper.bean.GroupIdentifier; import gov.nih.nci.cagrid.gridgrouper.client.GridGrouperClient; import gov.nih.nci.cagrid.testing.system.haste.Step; public class GrouperAddMembershipRequestStep extends Step { private String endpoint; private String group; private boolean shouldFail = false; public GrouperAddMembershipRequestStep(String group, String endpoint) { this(group, false, endpoint); } public GrouperAddMembershipRequestStep(String group, boolean shouldFail, String endpoint) { super(); this.endpoint = endpoint; this.group = group; this.shouldFail = shouldFail; } @Override public void runStep() throws Exception { GridGrouperClient grouper = new GridGrouperClient(this.endpoint); grouper.setAnonymousPrefered(false); try { grouper.addMembershipRequest(new GroupIdentifier(null, this.group)); if (this.shouldFail) { fail("addMember should fail"); } } catch (Exception e) { if (!this.shouldFail) { throw e; } } } }
{'content_hash': '962ec49bc098a5a2abc8d883fdd0260a', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 92, 'avg_line_length': 25.951219512195124, 'alnum_prop': 0.7546992481203008, 'repo_name': 'NCIP/cagrid-core', 'id': 'd1a15be66baa69dd51135beefe0502419fe13563', 'size': '1553', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'integration-tests/projects/gridgrouperTests/src/org/cagrid/gridgrouper/test/system/steps/GrouperAddMembershipRequestStep.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '124236'}, {'name': 'Java', 'bytes': '17856338'}, {'name': 'JavaScript', 'bytes': '62288'}, {'name': 'Perl', 'bytes': '100792'}, {'name': 'Scala', 'bytes': '405'}, {'name': 'Shell', 'bytes': '3487'}, {'name': 'XSLT', 'bytes': '6524'}]}
package provider import ( "encoding/base64" "encoding/json" "fmt" "net/http" "net/http/httptest" "net/url" "strings" "testing" utilnet "k8s.io/apimachinery/pkg/util/net" "k8s.io/cloud-provider-gcp/pkg/gcpcredential" credentialproviderapi "k8s.io/kubelet/pkg/apis/credentialprovider/v1alpha1" ) const ( dummyToken = "ya26.lots-of-indiscernible-garbage" email = "[email protected]" expectedUsername = "_token" expectedCacheKey = credentialproviderapi.ImagePluginCacheKeyType dummyImage = "k8s.gcr.io/pause" ) func hasURL(url string, response *credentialproviderapi.CredentialProviderResponse) bool { _, ok := response.Auth[url] return ok } func TestContainerRegistry(t *testing.T) { // Taken from from pkg/credentialprovider/gcp/metadata_test.go in kubernetes/kubernetes registryURL := "container.cloud.google.com" token := &gcpcredential.TokenBlob{AccessToken: dummyToken} // Fake value for testing. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defaultPrefix := "/computeMetadata/v1/instance/service-accounts/default/" // Only serve the URL key and the value endpoint switch r.URL.Path { case defaultPrefix + "scopes": w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") fmt.Fprintf(w, `["%s.read_write"]`, gcpcredential.StorageScopePrefix) case defaultPrefix + "email": w.WriteHeader(http.StatusOK) fmt.Fprint(w, email) case defaultPrefix + "token": w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") bytes, err := json.Marshal(token) if err != nil { t.Fatalf("unexpected error: %v", err) } fmt.Fprintln(w, string(bytes)) case "/computeMetadata/v1/instance/service-accounts/": w.WriteHeader(http.StatusOK) fmt.Fprintln(w, "default/\ncustom") default: http.Error(w, "", http.StatusNotFound) } })) defer server.Close() // Make a transport that reroutes all traffic to the example server transport := utilnet.SetTransportDefaults(&http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return url.Parse(server.URL + req.URL.Path) }, }) provider := MakeRegistryProvider(transport) response, err := GetResponse(dummyImage, provider) if err != nil { t.Fatalf("Unexpected error while getting response: %s", err.Error()) } if hasURL(registryURL, response) == false { t.Errorf("URL %s expected in response, not found (response: %s)", registryURL, response.Auth) } if expectedCacheKey != response.CacheKeyType { t.Errorf("Expected %s as cache key (found %s instead)", expectedCacheKey, response.CacheKeyType) } for _, auth := range response.Auth { if expectedUsername != auth.Username { t.Errorf("Expected username %s not found (username: %s)", expectedUsername, auth.Username) } if dummyToken != auth.Password { t.Errorf("Expected password %s not found (password: %s)", dummyToken, auth.Password) } } } func TestConfigProvider(t *testing.T) { // Taken from from pkg/credentialprovider/gcp/metadata_test.go in kubernetes/kubernetes registryURL := "hello.kubernetes.io" email := "[email protected]" username := "foo" password := "bar" // Fake value for testing. auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))) sampleDockerConfig := fmt.Sprintf(`{ "https://%s": { "email": %q, "auth": %q } }`, registryURL, email, auth) const probeEndpoint = "/computeMetadata/v1/" server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Only serve the one metadata key. if probeEndpoint == r.URL.Path { w.WriteHeader(http.StatusOK) } else if strings.HasSuffix(gcpcredential.DockerConfigKey, r.URL.Path) { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") fmt.Fprintln(w, sampleDockerConfig) } else { http.Error(w, "", http.StatusNotFound) } })) defer server.Close() // Make a transport that reroutes all traffic to the example server transport := utilnet.SetTransportDefaults(&http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return url.Parse(server.URL + req.URL.Path) }, }) provider := MakeDockerConfigProvider(transport) response, err := GetResponse(dummyImage, provider) if err != nil { t.Fatalf("Unexpected error while getting response: %s", err.Error()) } if expectedCacheKey != response.CacheKeyType { t.Errorf("Expected %s as cache key (found %s instead)", expectedCacheKey, response.CacheKeyType) } for _, auth := range response.Auth { if username != auth.Username { t.Errorf("Expected username %s not found (username: %s)", username, auth.Username) } if password != auth.Password { t.Errorf("Expected password %s not found (password: %s)", password, auth.Password) } } } func TestConfigURLProvider(t *testing.T) { // Taken from from pkg/credentialprovider/gcp/metadata_test.go in kubernetes/kubernetes registryURL := "hello.kubernetes.io" email := "[email protected]" username := "foo" password := "bar" // Fake value for testing. auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))) sampleDockerConfig := fmt.Sprintf(`{ "https://%s": { "email": %q, "auth": %q } }`, registryURL, email, auth) const probeEndpoint = "/computeMetadata/v1/" const valueEndpoint = "/my/value" server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Only serve the URL key and the value endpoint if probeEndpoint == r.URL.Path { w.WriteHeader(http.StatusOK) } else if valueEndpoint == r.URL.Path { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") fmt.Fprintln(w, sampleDockerConfig) } else if strings.HasSuffix(gcpcredential.DockerConfigURLKey, r.URL.Path) { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/text") fmt.Fprint(w, "http://foo.bar.com"+valueEndpoint) } else { http.Error(w, "", http.StatusNotFound) } })) defer server.Close() // Make a transport that reroutes all traffic to the example server transport := utilnet.SetTransportDefaults(&http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return url.Parse(server.URL + req.URL.Path) }, }) provider := MakeDockerConfigURLProvider(transport) response, err := GetResponse(dummyImage, provider) if err != nil { t.Fatalf("Unexpected error while getting response: %s", err.Error()) } if expectedCacheKey != response.CacheKeyType { t.Errorf("Expected %s as cache key (found %s instead)", expectedCacheKey, response.CacheKeyType) } for _, auth := range response.Auth { if username != auth.Username { t.Errorf("Expected username %s not found (username: %s)", username, auth.Username) } if password != auth.Password { t.Errorf("Expected password %s not found (password: %s)", password, auth.Password) } } }
{'content_hash': '3831638f8d381dfdfd0bbe8ddd47ed8e', 'timestamp': '', 'source': 'github', 'line_count': 198, 'max_line_length': 98, 'avg_line_length': 35.21212121212121, 'alnum_prop': 0.7066838783706254, 'repo_name': 'kubernetes/cloud-provider-gcp', 'id': 'e1029c14940c3aea7b52d41bd8948b7c0ffea636', 'size': '7538', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'cmd/auth-provider-gcp/provider/provider_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '1508'}, {'name': 'Go', 'bytes': '1320328'}, {'name': 'Makefile', 'bytes': '5048'}, {'name': 'PowerShell', 'bytes': '142152'}, {'name': 'Shell', 'bytes': '691339'}, {'name': 'Starlark', 'bytes': '72351'}, {'name': 'sed', 'bytes': '1262'}]}
package org.apache.hadoop.hbase.client; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.DoNotRetryIOException; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.NotServingRegionException; import org.apache.hadoop.hbase.OutOfOrderScannerNextException; import org.apache.hadoop.hbase.UnknownScannerException; import org.apache.hadoop.hbase.client.metrics.ScanMetrics; import org.apache.hadoop.hbase.protobuf.ProtobufUtil; import org.apache.hadoop.hbase.protobuf.generated.MapReduceProtos; import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.DataOutputBuffer; /** * Implements the scanner interface for the HBase client. * If there are multiple regions in a table, this scanner will iterate * through them all. */ @InterfaceAudience.Public @InterfaceStability.Stable public class ClientScanner extends AbstractClientScanner { private final Log LOG = LogFactory.getLog(this.getClass()); private Scan scan; private boolean closed = false; // Current region scanner is against. Gets cleared if current region goes // wonky: e.g. if it splits on us. private HRegionInfo currentRegion = null; private ScannerCallable callable = null; private final LinkedList<Result> cache = new LinkedList<Result>(); private final int caching; private long lastNext; // Keep lastResult returned successfully in case we have to reset scanner. private Result lastResult = null; private ScanMetrics scanMetrics = null; private final long maxScannerResultSize; private final HConnection connection; private final byte[] tableName; private final int scannerTimeout; /** * Create a new ClientScanner for the specified table. An HConnection will be * retrieved using the passed Configuration. * Note that the passed {@link Scan}'s start row maybe changed changed. * * @param conf The {@link Configuration} to use. * @param scan {@link Scan} to use in this scanner * @param tableName The table that we wish to scan * @throws IOException */ public ClientScanner(final Configuration conf, final Scan scan, final byte[] tableName) throws IOException { this(conf, scan, tableName, HConnectionManager.getConnection(conf)); } /** * Create a new ClientScanner for the specified table * Note that the passed {@link Scan}'s start row maybe changed changed. * * @param conf The {@link Configuration} to use. * @param scan {@link Scan} to use in this scanner * @param tableName The table that we wish to scan * @param connection Connection identifying the cluster * @throws IOException */ public ClientScanner(final Configuration conf, final Scan scan, final byte[] tableName, HConnection connection) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Creating scanner over " + Bytes.toString(tableName) + " starting at key '" + Bytes.toStringBinary(scan.getStartRow()) + "'"); } this.scan = scan; this.tableName = tableName; this.lastNext = System.currentTimeMillis(); this.connection = connection; if (scan.getMaxResultSize() > 0) { this.maxScannerResultSize = scan.getMaxResultSize(); } else { this.maxScannerResultSize = conf.getLong( HConstants.HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE_KEY, HConstants.DEFAULT_HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE); } this.scannerTimeout = conf.getInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD, HConstants.DEFAULT_HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD); // check if application wants to collect scan metrics byte[] enableMetrics = scan.getAttribute( Scan.SCAN_ATTRIBUTES_METRICS_ENABLE); if (enableMetrics != null && Bytes.toBoolean(enableMetrics)) { scanMetrics = new ScanMetrics(); } // Use the caching from the Scan. If not set, use the default cache setting for this table. if (this.scan.getCaching() > 0) { this.caching = this.scan.getCaching(); } else { this.caching = conf.getInt( HConstants.HBASE_CLIENT_SCANNER_CACHING, HConstants.DEFAULT_HBASE_CLIENT_SCANNER_CACHING); } // initialize the scanner nextScanner(this.caching, false); } protected HConnection getConnection() { return this.connection; } protected byte[] getTableName() { return this.tableName; } protected Scan getScan() { return scan; } protected long getTimestamp() { return lastNext; } // returns true if the passed region endKey private boolean checkScanStopRow(final byte [] endKey) { if (this.scan.getStopRow().length > 0) { // there is a stop row, check to see if we are past it. byte [] stopRow = scan.getStopRow(); int cmp = Bytes.compareTo(stopRow, 0, stopRow.length, endKey, 0, endKey.length); if (cmp <= 0) { // stopRow <= endKey (endKey is equals to or larger than stopRow) // This is a stop. return true; } } return false; //unlikely. } /* * Gets a scanner for the next region. If this.currentRegion != null, then * we will move to the endrow of this.currentRegion. Else we will get * scanner at the scan.getStartRow(). We will go no further, just tidy * up outstanding scanners, if <code>currentRegion != null</code> and * <code>done</code> is true. * @param nbRows * @param done Server-side says we're done scanning. */ private boolean nextScanner(int nbRows, final boolean done) throws IOException { // Close the previous scanner if it's open if (this.callable != null) { this.callable.setClose(); callable.withRetries(); this.callable = null; } // Where to start the next scanner byte [] localStartKey; // if we're at end of table, close and return false to stop iterating if (this.currentRegion != null) { byte [] endKey = this.currentRegion.getEndKey(); if (endKey == null || Bytes.equals(endKey, HConstants.EMPTY_BYTE_ARRAY) || checkScanStopRow(endKey) || done) { close(); if (LOG.isDebugEnabled()) { LOG.debug("Finished with scanning at " + this.currentRegion); } return false; } localStartKey = endKey; if (LOG.isDebugEnabled()) { LOG.debug("Finished with region " + this.currentRegion); } } else { localStartKey = this.scan.getStartRow(); } if (LOG.isDebugEnabled()) { LOG.debug("Advancing internal scanner to startKey at '" + Bytes.toStringBinary(localStartKey) + "'"); } try { callable = getScannerCallable(localStartKey, nbRows); // Open a scanner on the region server starting at the // beginning of the region callable.withRetries(); this.currentRegion = callable.getHRegionInfo(); if (this.scanMetrics != null) { this.scanMetrics.countOfRegions.incrementAndGet(); } } catch (IOException e) { close(); throw e; } return true; } protected ScannerCallable getScannerCallable(byte [] localStartKey, int nbRows) { scan.setStartRow(localStartKey); ScannerCallable s = new ScannerCallable(getConnection(), getTableName(), scan, this.scanMetrics); s.setCaching(nbRows); return s; } /** * Publish the scan metrics. For now, we use scan.setAttribute to pass the metrics back to the * application or TableInputFormat.Later, we could push it to other systems. We don't use metrics * framework because it doesn't support multi-instances of the same metrics on the same machine; * for scan/map reduce scenarios, we will have multiple scans running at the same time. * * By default, scan metrics are disabled; if the application wants to collect them, this behavior * can be turned on by calling calling: * * scan.setAttribute(SCAN_ATTRIBUTES_METRICS_ENABLE, Bytes.toBytes(Boolean.TRUE)) */ private void writeScanMetrics() throws IOException { if (this.scanMetrics == null) { return; } final DataOutputBuffer d = new DataOutputBuffer(); MapReduceProtos.ScanMetrics pScanMetrics = ProtobufUtil.toScanMetrics(scanMetrics); scan.setAttribute(Scan.SCAN_ATTRIBUTES_METRICS_DATA, pScanMetrics.toByteArray()); } public Result next() throws IOException { // If the scanner is closed and there's nothing left in the cache, next is a no-op. if (cache.size() == 0 && this.closed) { return null; } if (cache.size() == 0) { Result [] values = null; long remainingResultSize = maxScannerResultSize; int countdown = this.caching; // We need to reset it if it's a new callable that was created // with a countdown in nextScanner callable.setCaching(this.caching); // This flag is set when we want to skip the result returned. We do // this when we reset scanner because it split under us. boolean skipFirst = false; boolean retryAfterOutOfOrderException = true; do { try { if (skipFirst) { // Skip only the first row (which was the last row of the last // already-processed batch). callable.setCaching(1); values = callable.withRetries(); callable.setCaching(this.caching); skipFirst = false; } // Server returns a null values if scanning is to stop. Else, // returns an empty array if scanning is to go on and we've just // exhausted current region. values = callable.withRetries(); retryAfterOutOfOrderException = true; } catch (DoNotRetryIOException e) { if (e instanceof UnknownScannerException) { long timeout = lastNext + scannerTimeout; // If we are over the timeout, throw this exception to the client // Else, it's because the region moved and we used the old id // against the new region server; reset the scanner. if (timeout < System.currentTimeMillis()) { long elapsed = System.currentTimeMillis() - lastNext; ScannerTimeoutException ex = new ScannerTimeoutException( elapsed + "ms passed since the last invocation, " + "timeout is currently set to " + scannerTimeout); ex.initCause(e); throw ex; } } else { Throwable cause = e.getCause(); if ((cause == null || (!(cause instanceof NotServingRegionException) && !(cause instanceof RegionServerStoppedException))) && !(e instanceof OutOfOrderScannerNextException)) { throw e; } } // Else, its signal from depths of ScannerCallable that we got an // NSRE on a next and that we need to reset the scanner. if (this.lastResult != null) { this.scan.setStartRow(this.lastResult.getRow()); // Skip first row returned. We already let it out on previous // invocation. skipFirst = true; } if (e instanceof OutOfOrderScannerNextException) { if (retryAfterOutOfOrderException) { retryAfterOutOfOrderException = false; } else { throw new DoNotRetryIOException("Failed after retry" + ", it could be cause by rpc timeout", e); } } // Clear region this.currentRegion = null; callable = null; continue; } long currentTime = System.currentTimeMillis(); if (this.scanMetrics != null ) { this.scanMetrics.sumOfMillisSecBetweenNexts.addAndGet(currentTime-lastNext); } lastNext = currentTime; if (values != null && values.length > 0) { for (Result rs : values) { cache.add(rs); for (KeyValue kv : rs.raw()) { remainingResultSize -= kv.heapSize(); } countdown--; this.lastResult = rs; } } // Values == null means server-side filter has determined we must STOP } while (remainingResultSize > 0 && countdown > 0 && nextScanner(countdown, values == null)); } if (cache.size() > 0) { return cache.poll(); } // if we exhausted this scanner before calling close, write out the scan metrics writeScanMetrics(); return null; } /** * Get <param>nbRows</param> rows. * How many RPCs are made is determined by the {@link Scan#setCaching(int)} * setting (or hbase.client.scanner.caching in hbase-site.xml). * @param nbRows number of rows to return * @return Between zero and <param>nbRows</param> RowResults. Scan is done * if returned array is of zero-length (We never return null). * @throws IOException */ public Result [] next(int nbRows) throws IOException { // Collect values to be returned here ArrayList<Result> resultSets = new ArrayList<Result>(nbRows); for(int i = 0; i < nbRows; i++) { Result next = next(); if (next != null) { resultSets.add(next); } else { break; } } return resultSets.toArray(new Result[resultSets.size()]); } public void close() { if (callable != null) { callable.setClose(); try { callable.withRetries(); } catch (IOException e) { // We used to catch this error, interpret, and rethrow. However, we // have since decided that it's not nice for a scanner's close to // throw exceptions. Chances are it was just an UnknownScanner // exception due to lease time out. } finally { // we want to output the scan metrics even if an error occurred on close try { writeScanMetrics(); } catch (IOException e) { // As above, we still don't want the scanner close() method to throw. } } callable = null; } closed = true; } }
{'content_hash': '25b99a7e38a658edb19120d0465765be', 'timestamp': '', 'source': 'github', 'line_count': 389, 'max_line_length': 101, 'avg_line_length': 39.05141388174807, 'alnum_prop': 0.6232637746033836, 'repo_name': 'daidong/DominoHBase', 'id': '553346b58489746e75e24f83043f7830f0bf136a', 'size': '15997', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'hbase-server/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '4124'}, {'name': 'C++', 'bytes': '733760'}, {'name': 'CSS', 'bytes': '8314'}, {'name': 'Java', 'bytes': '16924338'}, {'name': 'JavaScript', 'bytes': '1347'}, {'name': 'PHP', 'bytes': '413443'}, {'name': 'Perl', 'bytes': '383793'}, {'name': 'Python', 'bytes': '382260'}, {'name': 'Ruby', 'bytes': '369746'}, {'name': 'Shell', 'bytes': '111877'}, {'name': 'XSLT', 'bytes': '4379'}]}
'use strict'; describe('userstory Directive', function () { var userStory, element, StoriesModel, $rootScope; beforeEach(module('Angello.User')); beforeEach(inject(function($q, $compile, _$rootScope_, _StoriesModel_) { $rootScope = _$rootScope_; var directiveMarkup = angular.element('<li userstory></li>'); element = $compile(directiveMarkup)($rootScope); userStory = element.scope().userStory; StoriesModel = _StoriesModel_; spyOn(StoriesModel, 'destroy').and.callFake(function() { var deferred = $q.defer(); deferred.resolve('data'); return deferred.promise; }); spyOn($rootScope,'$broadcast').and.callThrough(); })); it('should delete a story', function() { userStory.deleteStory('0'); expect(StoriesModel.destroy).toHaveBeenCalledWith('0'); $rootScope.$digest(); expect($rootScope.$broadcast).toHaveBeenCalledWith('storyDeleted'); }); });
{'content_hash': '243ed29c7bab291e4b6d97e58b3c94ad', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 76, 'avg_line_length': 27.210526315789473, 'alnum_prop': 0.6005802707930368, 'repo_name': 'angularjs-in-action/angello', 'id': 'beaa0e29f4ba7176f673ee4e5cce67480e80a57a', 'size': '1034', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'client/tests/specs/directives/UserStoryDirective.spec.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '8831'}, {'name': 'HTML', 'bytes': '15232'}, {'name': 'JavaScript', 'bytes': '53454'}]}
require 'active_support/duration' module ActiveSupport #:nodoc: module CoreExtensions #:nodoc: module Time #:nodoc: # Enables the use of time calculations within Time itself module Calculations def self.included(base) #:nodoc: base.extend ClassMethods base.class_eval do alias_method :plus_without_duration, :+ alias_method :+, :plus_with_duration alias_method :minus_without_duration, :- alias_method :-, :minus_with_duration alias_method :minus_without_coercion, :- alias_method :-, :minus_with_coercion alias_method :compare_without_coercion, :<=> alias_method :<=>, :compare_with_coercion end end COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] module ClassMethods # Overriding case equality method so that it returns true for ActiveSupport::TimeWithZone instances def ===(other) other.is_a?(::Time) end # Return the number of days in the given month. # If no year is specified, it will use the current year. def days_in_month(month, year = now.year) return 29 if month == 2 && ::Date.gregorian_leap?(year) COMMON_YEAR_DAYS_IN_MONTH[month] end # Returns a new Time if requested year can be accommodated by Ruby's Time class # (i.e., if year is within either 1970..2038 or 1902..2038, depending on system architecture); # otherwise returns a DateTime def time_with_datetime_fallback(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0, usec=0) ::Time.send(utc_or_local, year, month, day, hour, min, sec, usec) rescue offset = utc_or_local.to_sym == :local ? ::DateTime.local_offset : 0 ::DateTime.civil(year, month, day, hour, min, sec, offset) end # Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:utc</tt>. def utc_time(*args) time_with_datetime_fallback(:utc, *args) end # Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:local</tt>. def local_time(*args) time_with_datetime_fallback(:local, *args) end end # Tells whether the Time object's time lies in the past def past? self < ::Time.current end # Tells whether the Time object's time is today def today? self.to_date == ::Date.current end # Tells whether the Time object's time lies in the future def future? self > ::Time.current end # Seconds since midnight: Time.now.seconds_since_midnight def seconds_since_midnight self.to_i - self.change(:hour => 0).to_i + (self.usec/1.0e+6) end # Returns a new Time where one or more of the elements have been changed according to the +options+ parameter. The time options # (hour, minute, sec, usec) reset cascadingly, so if only the hour is passed, then minute, sec, and usec is set to 0. If the hour and # minute is passed, then sec and usec is set to 0. def change(options) ::Time.send( self.utc? ? :utc_time : :local_time, options[:year] || self.year, options[:month] || self.month, options[:day] || self.day, options[:hour] || self.hour, options[:min] || (options[:hour] ? 0 : self.min), options[:sec] || ((options[:hour] || options[:min]) ? 0 : self.sec), options[:usec] || ((options[:hour] || options[:min] || options[:sec]) ? 0 : self.usec) ) end # Uses Date to provide precise Time calculations for years, months, and days. # The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>, # <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>, # <tt>:minutes</tt>, <tt>:seconds</tt>. def advance(options) unless options[:weeks].nil? options[:weeks], partial_weeks = options[:weeks].divmod(1) options[:days] = (options[:days] || 0) + 7 * partial_weeks end unless options[:days].nil? options[:days], partial_days = options[:days].divmod(1) options[:hours] = (options[:hours] || 0) + 24 * partial_days end d = to_date.advance(options) time_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day) seconds_to_advance = (options[:seconds] || 0) + (options[:minutes] || 0) * 60 + (options[:hours] || 0) * 3600 seconds_to_advance == 0 ? time_advanced_by_date : time_advanced_by_date.since(seconds_to_advance) end # Returns a new Time representing the time a number of seconds ago, this is basically a wrapper around the Numeric extension def ago(seconds) self.since(-seconds) end # Returns a new Time representing the time a number of seconds since the instance time, this is basically a wrapper around # the Numeric extension. def since(seconds) f = seconds.since(self) if ActiveSupport::Duration === seconds f else initial_dst = self.dst? ? 1 : 0 final_dst = f.dst? ? 1 : 0 (seconds.abs >= 86400 && initial_dst != final_dst) ? f + (initial_dst - final_dst).hours : f end rescue self.to_datetime.since(seconds) end alias :in :since # Returns a new Time representing the time a number of specified months ago def months_ago(months) advance(:months => -months) end # Returns a new Time representing the time a number of specified months in the future def months_since(months) advance(:months => months) end # Returns a new Time representing the time a number of specified years ago def years_ago(years) advance(:years => -years) end # Returns a new Time representing the time a number of specified years in the future def years_since(years) advance(:years => years) end # Short-hand for years_ago(1) def last_year years_ago(1) end # Short-hand for years_since(1) def next_year years_since(1) end # Short-hand for months_ago(1) def last_month months_ago(1) end # Short-hand for months_since(1) def next_month months_since(1) end # Returns a new Time representing the "start" of this week (Monday, 0:00) def beginning_of_week days_to_monday = self.wday!=0 ? self.wday-1 : 6 (self - days_to_monday.days).midnight end alias :monday :beginning_of_week alias :at_beginning_of_week :beginning_of_week # Returns a new Time representing the end of this week (Sunday, 23:59:59) def end_of_week days_to_sunday = self.wday!=0 ? 7-self.wday : 0 (self + days_to_sunday.days).end_of_day end alias :at_end_of_week :end_of_week # Returns a new Time representing the start of the given day in next week (default is Monday). def next_week(day = :monday) days_into_week = { :monday => 0, :tuesday => 1, :wednesday => 2, :thursday => 3, :friday => 4, :saturday => 5, :sunday => 6} since(1.week).beginning_of_week.since(days_into_week[day].day).change(:hour => 0) end # Returns a new Time representing the start of the day (0:00) def beginning_of_day #(self - seconds_since_midnight).change(:usec => 0) change(:hour => 0, :min => 0, :sec => 0, :usec => 0) end alias :midnight :beginning_of_day alias :at_midnight :beginning_of_day alias :at_beginning_of_day :beginning_of_day # Returns a new Time representing the end of the day, 23:59:59.999999 (.999999999 in ruby1.9) def end_of_day change(:hour => 23, :min => 59, :sec => 59, :usec => 999999.999) end # Returns a new Time representing the start of the month (1st of the month, 0:00) def beginning_of_month #self - ((self.mday-1).days + self.seconds_since_midnight) change(:day => 1,:hour => 0, :min => 0, :sec => 0, :usec => 0) end alias :at_beginning_of_month :beginning_of_month # Returns a new Time representing the end of the month (end of the last day of the month) def end_of_month #self - ((self.mday-1).days + self.seconds_since_midnight) last_day = ::Time.days_in_month( self.month, self.year ) change(:day => last_day, :hour => 23, :min => 59, :sec => 59, :usec => 999999.999) end alias :at_end_of_month :end_of_month # Returns a new Time representing the start of the quarter (1st of january, april, july, october, 0:00) def beginning_of_quarter beginning_of_month.change(:month => [10, 7, 4, 1].detect { |m| m <= self.month }) end alias :at_beginning_of_quarter :beginning_of_quarter # Returns a new Time representing the end of the quarter (end of the last day of march, june, september, december) def end_of_quarter beginning_of_month.change(:month => [3, 6, 9, 12].detect { |m| m >= self.month }).end_of_month end alias :at_end_of_quarter :end_of_quarter # Returns a new Time representing the start of the year (1st of january, 0:00) def beginning_of_year change(:month => 1,:day => 1,:hour => 0, :min => 0, :sec => 0, :usec => 0) end alias :at_beginning_of_year :beginning_of_year # Returns a new Time representing the end of the year (end of the 31st of december) def end_of_year change(:month => 12, :day => 31, :hour => 23, :min => 59, :sec => 59, :usec => 999999.999) end alias :at_end_of_year :end_of_year # Convenience method which returns a new Time representing the time 1 day ago def yesterday advance(:days => -1) end # Convenience method which returns a new Time representing the time 1 day since the instance time def tomorrow advance(:days => 1) end def plus_with_duration(other) #:nodoc: if ActiveSupport::Duration === other other.since(self) else plus_without_duration(other) end end def minus_with_duration(other) #:nodoc: if ActiveSupport::Duration === other other.until(self) else minus_without_duration(other) end end # Time#- can also be used to determine the number of seconds between two Time instances. # We're layering on additional behavior so that ActiveSupport::TimeWithZone instances # are coerced into values that Time#- will recognize def minus_with_coercion(other) other = other.comparable_time if other.respond_to?(:comparable_time) minus_without_coercion(other) end # Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances # can be chronologically compared with a Time def compare_with_coercion(other) # if other is an ActiveSupport::TimeWithZone, coerce a Time instance from it so we can do <=> comparison other = other.comparable_time if other.respond_to?(:comparable_time) if other.acts_like?(:date) # other is a Date/DateTime, so coerce self #to_datetime and hand off to DateTime#<=> to_datetime.compare_without_coercion(other) else compare_without_coercion(other) end end end end end end
{'content_hash': 'b1c4e752c2f38efab87544330354c006', 'timestamp': '', 'source': 'github', 'line_count': 304, 'max_line_length': 141, 'avg_line_length': 40.06907894736842, 'alnum_prop': 0.5790985961743699, 'repo_name': 'boy-jer/santhathi-appointment', 'id': '380922dd54295318f140aa4f3b0d5b0e743a63fd', 'size': '12181', 'binary': False, 'copies': '42', 'ref': 'refs/heads/master', 'path': 'vendor/rails/activesupport/lib/active_support/core_ext/time/calculations.rb', 'mode': '33261', 'license': 'mit', 'language': []}
/* * HE_Mesh Frederik Vanhoutte - www.wblut.com * * https://github.com/wblut/HE_Mesh * A Processing/Java library for for creating and manipulating polygonal meshes. * * Public Domain: http://creativecommons.org/publicdomain/zero/1.0/ */ package wblut.hemesh; import java.util.ArrayList; import java.util.Collection; import wblut.geom.WB_Coord; import wblut.geom.WB_Plane; import wblut.geom.WB_Point; import wblut.geom.WB_Vector; import wblut.math.WB_ConstantScalarParameter; import wblut.math.WB_ScalarParameter; /** * Creates the Voronoi cell of one point in a collection of points, constrained * by a mesh. * * @author Frederik Vanhoutte (W:Blut) * */ public class HEC_VoronoiCell extends HEC_Creator { /** Points. */ private WB_Coord[] points; /** Number of points. */ private int numberOfPoints; /** Use specific subselection of points. */ private int[] pointsToUse; /** Cell index. */ private int cellIndex; /** Container. */ private HE_Mesh container; /** Treat container as surface?. */ private boolean surface; /** Offset. */ private WB_ScalarParameter offset; /** Faces fully interior to cell. */ public HE_Selection inner; /** Faces part of container. */ public HE_Selection outer; /** The limit points. */ private boolean limitPoints; /** * Instantiates a new HEC_VoronoiCell. * */ public HEC_VoronoiCell() { super(); override = true; offset = WB_ScalarParameter.ZERO; } /** * Set points that define cell centers. * * @param points * array of vertex positions * @return self */ public HEC_VoronoiCell setPoints(final WB_Coord[] points) { this.points = points; return this; } public HEC_VoronoiCell setPoints(final Collection<? extends WB_Coord> points) { this.points = new WB_Coord[points.size()]; int i = 0; for (WB_Coord p : points) { this.points[i++] = p; } return this; } /** * Set points that define cell centers. * * @param points * 2D array of double of vertex positions * @return self */ public HEC_VoronoiCell setPoints(final double[][] points) { final int n = points.length; this.points = new WB_Coord[n]; for (int i = 0; i < n; i++) { this.points[i] = new WB_Point(points[i][0], points[i][1], points[i][2]); } return this; } /** * Set points that define cell centers. * * @param points * 2D array of float of vertex positions * @return self */ public HEC_VoronoiCell setPoints(final float[][] points) { final int n = points.length; this.points = new WB_Point[n]; for (int i = 0; i < n; i++) { this.points[i] = new WB_Point(points[i][0], points[i][1], points[i][2]); } return this; } /** * Sets the points to use. * * @param pointsToUse * the points to use * @return the hE c_ voronoi cell */ public HEC_VoronoiCell setPointsToUse(final int[] pointsToUse) { this.pointsToUse = pointsToUse; return this; } /** * Sets the points to use. * * @param pointsToUse * the points to use * @return the hE c_ voronoi cell */ public HEC_VoronoiCell setPointsToUse(final ArrayList<Integer> pointsToUse) { final int n = pointsToUse.size(); this.pointsToUse = new int[n]; for (int i = 0; i < n; i++) { this.pointsToUse[i] = pointsToUse.get(i); } return this; } /** * Set index of cell to create. * * @param i * index * @return self */ public HEC_VoronoiCell setCellIndex(final int i) { cellIndex = i; return this; } /** * Set voronoi cell offset. * * @param o * offset * @return self */ public HEC_VoronoiCell setOffset(final double o) { offset = new WB_ConstantScalarParameter(o); return this; } /** * Set voronoi cell offset. * * @param o * offset * @return self */ public HEC_VoronoiCell setOffset(final WB_ScalarParameter o) { offset = o; return this; } /** * Set enclosing mesh limiting cells. * * @param container * enclosing mesh * @return self */ public HEC_VoronoiCell setContainer(final HE_Mesh container) { this.container = container; return this; } /** * Limit the points considered to those indices specified in the * pointsToUseArray. * * @param b * true, false * @return self */ public HEC_VoronoiCell setLimitPoints(final boolean b) { limitPoints = b; return this; } /** * Set optional surface mesh mode. * * @param b * true, false * @return self */ public HEC_VoronoiCell setSurface(final boolean b) { surface = b; return this; } /* * (non-Javadoc) * * @see wblut.hemesh.HE_Creator#create() */ @Override public HE_Mesh createBase() { if (container == null) { return new HE_Mesh(); } if (points == null) { return container; } numberOfPoints = points.length; if (cellIndex < 0 || cellIndex >= numberOfPoints) { return new HE_Mesh(); } final HE_Mesh result = container.copy(); result.setInternalLabel(cellIndex); result.setUserLabel(cellIndex); final ArrayList<WB_Plane> cutPlanes = new ArrayList<WB_Plane>(); int id = 0; final WB_Point O = new WB_Point(); WB_Plane P; final int[] labels; if (limitPoints) { labels = new int[pointsToUse.length]; for (final int element : pointsToUse) { if (cellIndex != element) { final WB_Vector N = new WB_Vector(points[cellIndex]); N.subSelf(points[element]); N.normalizeSelf(); O.set(points[cellIndex]); // plane origin=point halfway // between point i and point j O.addSelf(points[element]); O.mulSelf(0.5); O.addSelf(N.mul( offset.evaluate(points[cellIndex].xd(), points[cellIndex].yd(), points[cellIndex].zd()))); P = new WB_Plane(O, N); cutPlanes.add(P); labels[id] = element; id++; } } } else { labels = new int[numberOfPoints - 1]; for (int j = 0; j < numberOfPoints; j++) { if (cellIndex != j) { final WB_Vector N = new WB_Vector(points[cellIndex]); N.subSelf(points[j]); N.normalizeSelf(); O.set(points[cellIndex]); // plane origin=point halfway // between point i and point j O.addSelf(points[j]); O.mulSelf(0.5); O.addSelf(N.mul( offset.evaluate(points[cellIndex].xd(), points[cellIndex].yd(), points[cellIndex].zd()))); P = new WB_Plane(O, N); cutPlanes.add(P); labels[id] = j; id++; } } } final HEM_MultiSlice msm = new HEM_MultiSlice(); msm.setPlanes(cutPlanes).setCenter(new WB_Point(points[cellIndex])).setCap(!surface).setLabels(labels); try { msm.applySelf(result); } catch (Exception e) { return new HE_Mesh(); } inner = HE_Selection.getSelection(result); for (int i = 0; i < labels.length; i++) { final HE_Selection sel = result.selectFacesWithInternalLabel(labels[i]); if (sel.getNumberOfFaces() > 0) { final HE_FaceIterator fitr = sel.fItr(); while (fitr.hasNext()) { inner.add(fitr.next()); } } } outer = msm.origFaces; return result; } }
{'content_hash': '8fc80cd57d330859c865b750a0808040', 'timestamp': '', 'source': 'github', 'line_count': 309, 'max_line_length': 105, 'avg_line_length': 22.802588996763753, 'alnum_prop': 0.6308543854669316, 'repo_name': 'DweebsUnited/CodeMonkey', 'id': 'c072ffdf63d066a760500bed6cb901e5a8450191', 'size': '7046', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'java/CodeMonkey/HEMesh/wblut/hemesh/HEC_VoronoiCell.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '718'}, {'name': 'C++', 'bytes': '2748240'}, {'name': 'CMake', 'bytes': '11221'}, {'name': 'CSS', 'bytes': '896'}, {'name': 'GLSL', 'bytes': '1116'}, {'name': 'HTML', 'bytes': '887'}, {'name': 'Java', 'bytes': '132732'}, {'name': 'Makefile', 'bytes': '23824'}, {'name': 'Meson', 'bytes': '246'}, {'name': 'Objective-C', 'bytes': '810'}, {'name': 'Processing', 'bytes': '205574'}, {'name': 'Python', 'bytes': '65902'}, {'name': 'Shell', 'bytes': '6253'}]}
#ifndef __VERSION_H__ #define __VERSION_H__ #include <zxing/common/Counted.h> #include <zxing/qrcode/ErrorCorrectionLevel.h> #include <zxing/ReaderException.h> #include <zxing/common/BitMatrix.h> #include <zxing/common/Counted.h> #include <vector> namespace zxing { namespace qrcode { class ECB { private: int count_; int dataCodewords_; public: ECB(int count, int dataCodewords); int getCount(); int getDataCodewords(); }; class ECBlocks { private: int ecCodewordsPerBloc_; std::vector<ECB*> ecBlocks_; public: ECBlocks(int ecCodewordsPerBloc, ECB *ecBlocks); ECBlocks(int ecCodewordsPerBloc, ECB *ecBlocks1, ECB *ecBlocks2); int getECCodewordsPerBloc(); int getTotalECCodewords(); std::vector<ECB*>& getECBlocks(); ~ECBlocks(); }; class Version : public Counted { private: int versionNumber_; std::vector<int> &alignmentPatternCenters_; std::vector<ECBlocks*> ecBlocks_; int totalCodewords_; Version(int versionNumber, std::vector<int> *alignmentPatternCenters, ECBlocks *ecBlocks1, ECBlocks *ecBlocks2, ECBlocks *ecBlocks3, ECBlocks *ecBlocks4); public: static unsigned int VERSION_DECODE_INFO[]; static int N_VERSION_DECODE_INFOS; static std::vector<Ref<Version> > VERSIONS; ~Version(); int getVersionNumber() const; std::vector<int> &getAlignmentPatternCenters(); int getTotalCodewords(); int getDimensionForVersion(); ECBlocks &getECBlocksForLevel(const ErrorCorrectionLevel &ecLevel) const; static Ref<Version> getProvisionalVersionForDimension(int dimension); static Ref<Version> getVersionForNumber(int versionNumber); static Ref<Version> decodeVersionInformation(unsigned int versionBits); Ref<BitMatrix> buildFunctionPattern(); static int buildVersions(); }; } } #endif // __VERSION_H__
{'content_hash': '452015491b0d104208ac90d2503c1c11', 'timestamp': '', 'source': 'github', 'line_count': 69, 'max_line_length': 113, 'avg_line_length': 25.840579710144926, 'alnum_prop': 0.7442512619181155, 'repo_name': 'tauplatform/tau', 'id': '0af4416c433f7710d7d2a5770c37c991c5b60a6d', 'size': '2429', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'lib/commonAPI/barcode/ext/platform/qt/src/qzxing/zxing/zxing/qrcode/Version.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '6291'}, {'name': 'Batchfile', 'bytes': '117803'}, {'name': 'C', 'bytes': '58276168'}, {'name': 'C#', 'bytes': '695670'}, {'name': 'C++', 'bytes': '17458941'}, {'name': 'COBOL', 'bytes': '187'}, {'name': 'CSS', 'bytes': '641054'}, {'name': 'GAP', 'bytes': '76344'}, {'name': 'HTML', 'bytes': '1756465'}, {'name': 'Java', 'bytes': '6450324'}, {'name': 'JavaScript', 'bytes': '1670149'}, {'name': 'Makefile', 'bytes': '330343'}, {'name': 'Matlab', 'bytes': '123'}, {'name': 'NSIS', 'bytes': '85403'}, {'name': 'Objective-C', 'bytes': '4133620'}, {'name': 'Objective-C++', 'bytes': '417934'}, {'name': 'Perl', 'bytes': '1710'}, {'name': 'QMake', 'bytes': '79603'}, {'name': 'Rebol', 'bytes': '130'}, {'name': 'Roff', 'bytes': '328967'}, {'name': 'Ruby', 'bytes': '17284489'}, {'name': 'Shell', 'bytes': '33635'}, {'name': 'XSLT', 'bytes': '4315'}, {'name': 'Yacc', 'bytes': '257479'}]}
namespace fusion = boost::fusion; namespace hana = boost::hana; struct Fish { std::string name; }; struct Cat { std::string name; }; struct Dog { std::string name; }; int main() { fusion::list<Fish, Cat, Dog> animals{{"Nemo"}, {"Garfield"}, {"Snoopy"}}; hana::front(animals).name = "Moby Dick"; auto names = hana::transform(animals, [](auto a) { return a.name; }); BOOST_HANA_RUNTIME_CHECK(hana::equal( names, fusion::make_list("Moby Dick", "Garfield", "Snoopy") )); }
{'content_hash': '6df05b384486dfb46c479a14903feaf5', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 77, 'avg_line_length': 24.857142857142858, 'alnum_prop': 0.5957854406130269, 'repo_name': 'hsu1994/Terminator', 'id': 'fa0dda372f668a7e96a20760dc5621614517e06b', 'size': '1003', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'Server/RelyON/boost_1_61_0/libs/hana/example/ext/boost/fusion/list.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '223360'}, {'name': 'Batchfile', 'bytes': '43670'}, {'name': 'C', 'bytes': '3717232'}, {'name': 'C#', 'bytes': '12172138'}, {'name': 'C++', 'bytes': '188465965'}, {'name': 'CMake', 'bytes': '119765'}, {'name': 'CSS', 'bytes': '430770'}, {'name': 'Cuda', 'bytes': '52444'}, {'name': 'DIGITAL Command Language', 'bytes': '6246'}, {'name': 'FORTRAN', 'bytes': '1856'}, {'name': 'GLSL', 'bytes': '143058'}, {'name': 'Groff', 'bytes': '5189'}, {'name': 'HTML', 'bytes': '234253948'}, {'name': 'IDL', 'bytes': '14'}, {'name': 'JavaScript', 'bytes': '694216'}, {'name': 'Lex', 'bytes': '1231'}, {'name': 'M4', 'bytes': '29689'}, {'name': 'Makefile', 'bytes': '1459789'}, {'name': 'Max', 'bytes': '36857'}, {'name': 'Objective-C', 'bytes': '15456'}, {'name': 'Objective-C++', 'bytes': '630'}, {'name': 'PHP', 'bytes': '59030'}, {'name': 'Perl', 'bytes': '38649'}, {'name': 'Perl6', 'bytes': '2053'}, {'name': 'Protocol Buffer', 'bytes': '409987'}, {'name': 'Python', 'bytes': '1764372'}, {'name': 'QML', 'bytes': '593'}, {'name': 'QMake', 'bytes': '16692'}, {'name': 'Rebol', 'bytes': '354'}, {'name': 'Ruby', 'bytes': '5532'}, {'name': 'Shell', 'bytes': '362208'}, {'name': 'Smalltalk', 'bytes': '2796'}, {'name': 'Tcl', 'bytes': '1172'}, {'name': 'TeX', 'bytes': '32117'}, {'name': 'XSLT', 'bytes': '265714'}, {'name': 'Yacc', 'bytes': '19623'}]}
package email.client.gui; import java.awt.Dimension; import java.awt.Toolkit; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.WindowConstants; public class FrameTemplate extends JFrame { private PanelTemplate panel; public FrameTemplate() { panel = new PanelTemplate(); add(panel); normalSetting(); setVisible(true); } private void normalSetting() { try { // 设置Nimbus皮肤 UIManager .setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel"); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // 表示运行环境非JRE7 e.printStackTrace(); } SwingUtilities.updateComponentTreeUI(this); // 点击红叉关闭窗口的行为 setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // 设置窗体位置大小为:水平垂直居中,大小为1/4 Toolkit kit = Toolkit.getDefaultToolkit(); Dimension screenSize = kit.getScreenSize(); setBounds(screenSize.width / 4, screenSize.height / 4, screenSize.width / 2, screenSize.height / 2); } }
{'content_hash': '24b1830c7fd756da2208d72196abb88b', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 67, 'avg_line_length': 24.52173913043478, 'alnum_prop': 0.7526595744680851, 'repo_name': 'baijinping/EmailClient', 'id': '72d6361241ab12b77e0b624f6224abc2a96fb71b', 'size': '1212', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'EmailClient/src/email/client/gui/FrameTemplate.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '159353'}]}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"> <title>FLAC: FLAC/_decoder.h: decoder interfaces</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.4.2 --> <div class="qindex"><a class="qindex" href="index.html">Main&nbsp;Page</a> | <a class="qindex" href="modules.html">Modules</a> | <a class="qindex" href="hierarchy.html">Class&nbsp;Hierarchy</a> | <a class="qindex" href="classes.html">Alphabetical&nbsp;List</a> | <a class="qindex" href="annotated.html">Class&nbsp;List</a> | <a class="qindex" href="dirs.html">Directories</a> | <a class="qindex" href="files.html">File&nbsp;List</a> | <a class="qindex" href="functions.html">Class&nbsp;Members</a> | <a class="qindex" href="globals.html">File&nbsp;Members</a></div> <h1>FLAC/_decoder.h: decoder interfaces<br> <small> [<a class="el" href="group__flac.html">FLAC C API</a>]</small> </h1><hr><a name="_details"></a><h2>Detailed Description</h2> This module describes the decoder layers provided by libFLAC. <p> The stream decoder can be used to decode complete streams either from the client via callbacks, or directly from a file, depending on how it is initialized. When decoding via callbacks, the client provides callbacks for reading FLAC data and writing decoded samples, and handling metadata and errors. If the client also supplies seek-related callback, the decoder function for sample-accurate seeking within the FLAC input is also available. When decoding from a file, the client needs only supply a filename or open <code>FILE*</code> and write/metadata/error callbacks; the rest of the callbacks are supplied internally. For more info see the <a class="el" href="group__flac__stream__decoder.html">stream decoder </a> module. <p> <table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> <tr><td colspan="2"><br><h2>Modules</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__flac__stream__decoder.html">FLAC/stream_decoder.h: stream decoder interface</a></td></tr> </table> <hr size="1"> <div class="copyright"> <!-- @@@ oh so hacky --> <table> <tr> <td align="left"> Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007 Josh Coalson </td> <td width="1%" align="right"> <a href="http://sourceforge.net"><img src="http://sflogo.sourceforge.net/sflogo.php?group_id=13478&amp;type=1" width="88" height="31" border="0" alt="SourceForge.net Logo" /></a> </td> </tr> </table> </div> <!-- Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007 Josh Coalson --> <!-- Permission is granted to copy, distribute and/or modify this document --> <!-- under the terms of the GNU Free Documentation License, Version 1.1 --> <!-- or any later version published by the Free Software Foundation; --> <!-- with no invariant sections. --> <!-- A copy of the license can be found at http://www.gnu.org/copyleft/fdl.html --> </body> </html>
{'content_hash': 'b70d52c8a28ff9aa421a3caabc22407a', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 728, 'avg_line_length': 70.3409090909091, 'alnum_prop': 0.7033925686591276, 'repo_name': 'ring-lang/ring', 'id': '0b93ceccf0c5d933182517c769d496d91eecbbbf', 'size': '3095', 'binary': False, 'copies': '111', 'ref': 'refs/heads/master', 'path': 'extensions/android/ringlibsdl/project/jni/flac-1.2.1/doc/html/api/group__flac__decoder.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ada', 'bytes': '89080'}, {'name': 'Assembly', 'bytes': '296081'}, {'name': 'Awk', 'bytes': '46636'}, {'name': 'Batchfile', 'bytes': '101663'}, {'name': 'C', 'bytes': '71469704'}, {'name': 'C#', 'bytes': '80097'}, {'name': 'C++', 'bytes': '20961776'}, {'name': 'CLIPS', 'bytes': '5291'}, {'name': 'CMake', 'bytes': '67747'}, {'name': 'CSS', 'bytes': '82643'}, {'name': 'DIGITAL Command Language', 'bytes': '110604'}, {'name': 'Emacs Lisp', 'bytes': '7096'}, {'name': 'Java', 'bytes': '60236'}, {'name': 'JavaScript', 'bytes': '77844'}, {'name': 'Less', 'bytes': '246'}, {'name': 'M4', 'bytes': '493435'}, {'name': 'Makefile', 'bytes': '3116661'}, {'name': 'Module Management System', 'bytes': '17479'}, {'name': 'Objective-C', 'bytes': '376958'}, {'name': 'Pascal', 'bytes': '72283'}, {'name': 'Perl', 'bytes': '85778'}, {'name': 'Python', 'bytes': '263263'}, {'name': 'QML', 'bytes': '1152'}, {'name': 'QMake', 'bytes': '36639'}, {'name': 'Rebol', 'bytes': '6496'}, {'name': 'Ring', 'bytes': '45850703'}, {'name': 'Roff', 'bytes': '677912'}, {'name': 'SAS', 'bytes': '16030'}, {'name': 'SWIG', 'bytes': '13206'}, {'name': 'Shell', 'bytes': '5483160'}, {'name': 'Smalltalk', 'bytes': '5908'}, {'name': 'StringTemplate', 'bytes': '4184'}, {'name': 'TeX', 'bytes': '352002'}, {'name': 'WebAssembly', 'bytes': '13987'}, {'name': 'sed', 'bytes': '236'}]}
/** * soga.js v0.1.4 * (c) 2017-2019 musicode * Released under the MIT License. */ function createResponse (xhr, headers) { function response() { return { ok: xhr.status >= 200 && xhr.status < 300, statusText: xhr.statusText || 'OK', status: xhr.status || 200, url: xhr.responseURL || headers['x-request-url'] || '', headers: { get(name) { return headers[name.toLowerCase()]; }, has(name) { return name.toLowerCase() in headers; } }, body: xhr.response || xhr.responseText, text() { return xhr.responseText; }, json() { return JSON.parse(xhr.responseText); }, blob() { return new Blob([xhr.response]); }, clone: response, }; } return response; } function parseResponse (xhr) { const headers = {}; const rawHeaders = xhr.getAllResponseHeaders() || ''; rawHeaders.replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm, function (match, key, value) { headers[key.toLowerCase()] = value; return match; }); return createResponse(xhr, headers); } function setRequestHeaders (xhr, headers) { for (let key in headers) { xhr.setRequestHeader(key, headers[key]); } } function fetch(url, options = {}) { return new Promise(function (resolve, reject) { const xhr = new XMLHttpRequest(); xhr.open(options.method || 'get', url, true); xhr.onload = function () { const response = parseResponse(xhr); resolve(response()); }; xhr.onerror = reject; /** * The credentials indicates whether the user agent should send cookies * from the other domain in the case of cross-origin requests. * * omit: Never send or receive cookies * * include: Always send user credentials (cookies, basic http auth, etc..), even for cross-origin calls * * same-origin: Send user credentials (cookies, basic http auth, etc..) if the URL is on the same origin as the calling script. * This is the default value. */ if (options.credentials === 'include') { xhr.withCredentials = true; } else if (options.credentials === 'omit') { xhr.withCredentials = false; } setRequestHeaders(xhr, options.headers); xhr.send(options.body || null); }); } const blobSlice = File.prototype.slice || File.prototype['webkitSlice'] || File.prototype['mozSlice']; class AjaxUploader { static support() { const xhr = new XMLHttpRequest(); return 'upload' in xhr && 'onprogress' in xhr.upload; } constructor(file, hooks) { const instance = this; instance.file = file; instance.hooks = hooks; // 碰到过传了几个分片之后,file.size 变成 0 的情况 // 因此先存一下最初的 fileSize instance.fileSize = file.size || 0; const xhr = instance.xhr = new XMLHttpRequest(); xhr.onloadstart = function () { if (hooks.onStart) { hooks.onStart(); } }; xhr.onloadend = function () { if (hooks.onEnd) { hooks.onEnd(); } }; xhr.onload = function () { const { fileSize, chunkInfo } = instance; if (chunkInfo) { if (chunkInfo.uploaded < fileSize) { chunkInfo.uploaded += chunkInfo.uploading; if (hooks.onChunkSuccess) { hooks.onChunkSuccess({ chunkIndex: chunkInfo.options.chunkIndex }); } // 还有分片没上传完则继续上传下一个 if (chunkInfo.uploaded < fileSize) { chunkInfo.options.chunkIndex++; instance.uploadChunk(chunkInfo.options); return; } } } if (hooks.onSuccess) { const response = parseResponse(xhr); hooks.onSuccess(response()); } }; xhr.onerror = function () { if (hooks.onError) { hooks.onError(); } }; xhr.onabort = function () { if (hooks.onAbort) { hooks.onAbort(); } }; // 下载文件触发的是 xhr.onprogress // 上传文件触发的是 xhr.upload.onprogress xhr.upload.onprogress = function (event) { const { fileSize, chunkInfo } = instance; let uploaded; if (chunkInfo) { // 当前正在上传的分片 size const chunkTotal = chunkInfo.uploading; // 不能比当前正在上传的 size 还大 const chunkUploaded = Math.min(chunkTotal, event.loaded); if (hooks.onChunkProgress) { hooks.onChunkProgress({ chunkIndex: chunkInfo.options.chunkIndex, uploaded: chunkUploaded, total: chunkTotal, // 怕浏览器有 bug 导致 chunkTotal 为 0 percent: chunkTotal > 0 ? chunkUploaded / chunkTotal : 0 }); } // 加上之前上传成功的分片 size uploaded = chunkInfo.uploaded + chunkUploaded; } else { // 不能比文件 size 还大 uploaded = Math.min(fileSize, event.loaded); } if (hooks.onProgress) { hooks.onProgress({ uploaded, total: fileSize, // 怕浏览器有 bug 导致 fileSize 为 0 percent: fileSize > 0 ? uploaded / fileSize : 0 }); } }; } /** * 上传整个文件 */ upload(options) { const { xhr, file } = this; xhr.open('post', options.action, true); if (options.credentials === 'include') { xhr.withCredentials = true; } else if (options.credentials === 'omit') { xhr.withCredentials = false; } const formData = new FormData(); for (let key in options.data) { formData.append(key, options.data[key]); } formData.append(options.fileName, file); setRequestHeaders(xhr, options.headers); xhr.send(formData); } /** * 上传文件分片 */ uploadChunk(options) { let { xhr, file, fileSize, chunkInfo } = this; if (!chunkInfo) { chunkInfo = this.chunkInfo = { uploaded: 0, uploading: 0, options, }; } else if (chunkInfo.options !== options) { chunkInfo.options = options; } // 默认从第一个分片开始上传,断点续传可以传入指定的分片 const chunkIndex = options.chunkIndex || 0; // 默认一个分片为 4M const chunkSize = options.chunkSize || (4 * 1024 * 1024); const start = chunkSize * chunkIndex; const end = Math.min(fileSize, chunkSize * (chunkIndex + 1)); chunkInfo.uploading = end - start; xhr.open('post', options.action, true); // xhr.setRequestHeader 必须在 open() 方法之后,send() 方法之前调用,否则会报错 // xhr.setRequestHeader 设置相同的请求头不会覆盖,而是追加,如 key: value1, value2 // 这里改成覆盖 const headers = { Range: `bytes ${start}-${end}/${fileSize}` }; for (let key in options.headers) { headers[key] = options.headers[key]; } setRequestHeaders(xhr, headers); xhr.send(blobSlice.call(file, start, end)); } /** * 取消上传 */ abort() { this.xhr.abort(); } /** * 销毁 */ destroy() { this.abort(); } } class FlashUploader { constructor(options, hooks = {}) { const movieName = createMovieName(); const swf = createSWF(movieName, options.swfUrl, createFlashVars(movieName, options.accept || '', options.multiple || false)); const { el } = options; if (el.parentNode) { el.parentNode.replaceChild(swf, el); } else { throw new Error('el.parentNode is not found.'); } this.swf = swf; this.movieName = movieName; this.hooks = hooks; this.debug = !!options.debug; FlashUploader.instances[movieName] = this; } /** * 获得要上传的文件 */ getFiles() { return this.swf['getFiles'](); } /** * 上传 */ upload(index, options) { this.swf['upload'](index, options.action, options.fileName, options.data, options.headers); } /** * 取消上传 */ abort(index) { this.swf['abort'](index); } /** * 启用鼠标点击打开文件选择窗口 */ enable() { this.swf['enable'](); } /** * 禁用鼠标点击打开文件选择窗口 */ disable() { this.swf['disable'](); } /** * 销毁对象 */ destroy() { const files = this.getFiles(); for (let i = 0, len = files.length; i < len; i++) { this.abort(files[i].index); } this.swf['destroy'](); FlashUploader.instances[this.movieName] = null; // 清除 IE 引用 window[this.movieName] = null; } onReady() { // swf 文件初始化成功 const { onReady } = this.hooks; if (onReady) { onReady(); } } onFileChange() { // 用户选择文件 const { onFileChange } = this.hooks; if (onFileChange) { onFileChange(); } } onStart(data) { const { onStart } = this.hooks; if (onStart) { onStart(data.file); } } onEnd(data) { const { onEnd } = this.hooks; if (onEnd) { onEnd(data.file); } } onError(data) { const { onError } = this.hooks; if (onError) { onError(data.file, data.code, data.detail); } } onAbort(data) { const { onAbort } = this.hooks; if (onAbort) { onAbort(data.file); } } onProgress(data) { const { onProgress } = this.hooks; if (onProgress) { const { file, uploaded, total } = data; onProgress(file, { uploaded, total, percent: total > 0 ? uploaded / total : 0 }); } } onSuccess(data) { const { onSuccess } = this.hooks; if (onSuccess) { onSuccess(data.file, data.responseText); } } onDebug(data) { if (this.debug) { console.log(data.text); } } } FlashUploader.instances = {}; /** * 文件状态 - 等待上传 */ FlashUploader.STATUS_WAITING = 0; /** * 文件状态 - 正在上传 */ FlashUploader.STATUS_UPLOADING = 1; /** * 文件状态 - 上传成功 */ FlashUploader.STATUS_UPLOAD_SUCCESS = 2; /** * 文件状态 - 上传失败 */ FlashUploader.STATUS_UPLOAD_ERROR = 3; /** * 文件状态 - 上传中止 */ FlashUploader.STATUS_UPLOAD_ABORT = 4; /** * 错误码 - 上传出现沙箱安全错误 */ FlashUploader.ERROR_SECURITY = 0; /** * 错误码 - 上传 IO 错误 */ FlashUploader.ERROR_IO = 1; /** * 项目名称 AS 会用 projectName.instances[movieName] 找出当前实例 */ const projectName = 'Soga_Flash_Uploader'; /** * 暴露给全局的对象,这样 AS 才能调到 */ window[projectName] = FlashUploader; /** * guid 初始值 */ let guid = 0; /** * 创建新的唯一的影片剪辑名称 */ function createMovieName() { return projectName + (guid++); } /** * 创建 swf 元素 * * 无需兼容 IE67 用现有方法即可 * * 如果想兼容 IE67,有两种方法: * * 1. 把 wmode 改成 opaque * 2. 用 swfobject 或别的库重写此方法 * * 这里不兼容 IE67 是因为要判断浏览器实在太蛋疼了。。。 */ function createSWF(id, swfUrl, flashVars) { const div = document.createElement('div'); // 不加 ID 在 IE 下没法运行 div.innerHTML = '<object id="' + id + '" class="' + projectName.toLowerCase() + '" type="application/x-shockwave-flash" data="' + swfUrl + '">' + '<param name="movie" value="' + swfUrl + '" />' + '<param name="allowscriptaccess" value="always" />' + '<param name="wmode" value="transparent" />' + '<param name="flashvars" value="' + flashVars + '" />' + '</object>'; return div.children[0]; } /** * 拼装给 swf 用的参数 */ function createFlashVars(movieName, accept, multiple) { const result = [ 'projectName=' + projectName, 'movieName=' + movieName, 'accept=' + encodeURIComponent(accept), 'multiple=' + (multiple ? 'true' : 'false') ]; return result.join('&amp;'); } export { AjaxUploader, FlashUploader, fetch }; //# sourceMappingURL=soga.esm.js.map
{'content_hash': '4fe63229a91b562cf3996159ac31b593', 'timestamp': '', 'source': 'github', 'line_count': 453, 'max_line_length': 135, 'avg_line_length': 28.24503311258278, 'alnum_prop': 0.5007424775302852, 'repo_name': 'cdnjs/cdnjs', 'id': 'e6b19b95dfe6a48bf30f4103b464414744e549d1', 'size': '13701', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ajax/libs/soga/0.1.4/soga.esm.js', 'mode': '33188', 'license': 'mit', 'language': []}
require 'net/http' require 'json' require_relative 'specials' require_relative 'transaction' include Enumerable class Networking BASE_BCI = 'https://blockchain.info/' BASE_BLOCKR = 'https://btc.blockr.io/api/v1/' BASE_BLOCKR_TEST = 'https://tbtc.blockr.io/api/v1/' def initilize @t = Transaction.new end def make_request(*args) uri = URI(*args) res = Net::HTTP.get_response(uri) return res.body end def parse_addr_args(*args) # Valid input formats: blockr_unspent([addr1, addr2, addr3]) # blockr_unspent(addr1, addr2, addr3) # blockr_unspent([addr1, addr2, addr3], network) # blockr_unspent(addr1, addr2, addr3, network) # Where network is 'btc' or 'testnet' network = 'btc' addr_args = args if (args.size > 1) && (['btc', 'testnet'].include? args[-1]) network = args[-1] addr_args = args[0..-2] end return network, addr_args end # Gets the unspent outputs of one or more addresses def bci_unspent(*args) network, addrs = parse_addr_args(*args) unspent = [] addrs.each do |a| data = make_request(BASE_BCI + 'unspent?active='+a) next if data == 'No free outputs to spend' hash = JSON.parse data hash["unspent_outputs"].each do |output| h = Specials.new.change_endianness(output['tx_hash']) unspent << {output: h.to_s + ":" + output["tx_output_n"].to_s, value: output["value"]} end end return unspent end def blockr_unspent(*args) # Valid input formats: blockr_unspent([addr1, addr2, addr3]) # blockr_unspent(addr1, addr2, addr3) # blockr_unspent([addr1, addr2, addr3], network) # blockr_unspent(addr1, addr2, addr3, network) # Where network is 'btc' or 'testnet' network, addr_args = parse_addr_args(*args) switch = network == "testnet" ? BASE_BLOCKR_TEST : BASE_BLOCKR blockr_url = switch + "address/unspent/" result = make_request(blockr_url + addr_args.join(',')) data = (JSON.parse result)['data'] unspent = [] if data.include? "unspent" data = [data] end data.each do |dat| dat['unspent'].each do |u| unspent << {output: u['tx'].to_s + ":" + u['n'].to_s, value: u['amount'].sub!(".", "").to_i} end end return unspent end def unspent(*args, site) return bci_unspent(*args) if site == "bci" return blockr_unspent(*args) end # Gets the transaction output history of a given set of addresses, # including whether or not they have been spent # Valid input formats: history([addr1, addr2,addr3]) # history(addr1, addr2, addr3) def history(*addrs) transactions = [] addrs.each do |addr| offset = 0 while 1 result = make_request(BASE_BCI + "address/#{addr}?format=json&offset=#{offset}") data = JSON.parse result transactions.concat(data["txs"]) if data["txs"].size < 50 break end offset += 50 puts "Fetching more transactions ... #{offset} \n" end end outs = {} transactions.each do |tx| tx["out"].each do |out| if addrs.include?(out["addr"]) key = tx["tx_index"].to_s + ":" + out["n"].to_s outs[key] = { address: out["addr"], value: out["value"], output: tx["hash"].to_s + ":" + out["n"].to_s, block_height: tx["block_height"] || "None" } end end end transactions.each_with_index do |tx, index| tx["inputs"].each do |inp| if addrs.include?(inp["prev_out"]["addr"]) key = inp["prev_out"]["tx_index"].to_s + ":" + inp["prev_out"]["n"].to_s if outs[key] outs[key]["spend"] = tx["hash"] + ":" + index.to_s end end end end return outs end # Pushes a transaction to the network using https://blockchain.info/pushtx def bci_pushtx(tx) tx = @t.serialize tx unless tx.respond_to? :each_char return make_request(BASE_BCI + 'pushtx', 'tx=#{tx}') end def blockr_pushtx(tx, network="btc") switch = network == "testnet" ? BASE_BLOCKR_TEST : BASE_BLOCKR blockr_url = switch + "address/unspent/" tx = @t.serialize tx unless tx.respond_to? :each_char return make_request(blockr_url, '{"hex:#{tx}"}') end def pushtx(*args, site) return bci_pushtx(*args) if site == "bci" return blockr_pushtx(*args) end def last_block(network="btc") if network == "testnet" data = make_request(BASE_BLOCKR_TEST + 'block/info/last') jsonobj = JSON.parse data return jsonobj["data"]["nb"] end data = make_request(BASE_BCI + 'latestblock') jsonobj = JSON.parse data return jsonobj["height"] end # Gets a specific transaction def bci_fetchtx(txhash) return make_request(BASE_BCI + 'rawtx/'+txhash+'?format=hex') end def blockr_fetchtx(txhash, network='btc') switch = network == "testnet" ? BASE_BLOCKR_TEST : BASE_BLOCKR blockr_url = switch + "tx/raw/" jsondata = JSON.parse(make_request(blockr_url+txhash)) return jsondata['data']['tx']['hex'] end def fetchtx(*args, site) return bci_fetchtx(*args) if site == "bci" return blockr_fetchtx(*args) end def get_block_at_height(height) result = make_request(BASE_BCI + "block-height/#{height}?format=json") raise "Block at this height not found" if result =~ /Unknown Error/ result = JSON.parse result result["blocks"].each{|block| block if block["main_chain"] == true} end def get_block_header_data(height) block = get_block_at_height(height.to_s) return { version: block[0]['ver'], hash: block[0]['hash'], prevblock: block[0]['prev_block'], timestamp: block[0]['time'], merkle_root: block[0]['mrkl_root'], bits: block[0]['bits'], nonce: block[0]['nonce'] } end def blockr_get_block_header_data(height, network='btc') switch = network == "testnet" ? BASE_BLOCKR_TEST : BASE_BLOCKR blockr_url = switch + "address/unspent/" result = JSON.parse make_request(blockr_url) block = result['data'] return { version: block['ver'], hash: block['hash'], prevblock: block['prev_block'], timestamp: block['time'], merkle_root: block['mrkl_root'], bits: block['bits'].to_i(16), nonce: block['nonce'] } end def get_txs_in_block(height) block = get_block_at_height(height) hash = [] block[0]['tx'].each {|t| hash << t['hash']} return hash end end
{'content_hash': '7d4d3663279bdce0ae0ac48c898471ab', 'timestamp': '', 'source': 'github', 'line_count': 252, 'max_line_length': 96, 'avg_line_length': 25.63888888888889, 'alnum_prop': 0.6057885776195635, 'repo_name': 'Vidreven/rubitcointools', 'id': 'd36e9172bf967df72255508030b2618c2c703f35', 'size': '6461', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/networking.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '148615'}]}
package org.apache.cassandra.db; import java.net.InetAddress; import java.nio.ByteBuffer; import java.util.UUID; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.junit.Test; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.cql3.CQLTester; import org.apache.cassandra.cql3.UntypedResultSet; import org.apache.cassandra.db.marshal.BytesType; import org.apache.cassandra.db.marshal.Int32Type; import org.apache.cassandra.db.marshal.UTF8Type; import org.apache.cassandra.db.marshal.UUIDType; import org.apache.cassandra.utils.UUIDGen; import static org.junit.Assert.assertEquals; public class SystemKeyspaceMigrator40Test extends CQLTester { @Test public void testMigratePeers() throws Throwable { String insert = String.format("INSERT INTO %s (" + "peer, " + "data_center, " + "host_id, " + "preferred_ip, " + "rack, " + "release_version, " + "rpc_address, " + "schema_version, " + "tokens) " + " values ( ?, ?, ? , ? , ?, ?, ?, ?, ?)", SystemKeyspaceMigrator40.legacyPeersName); UUID hostId = UUIDGen.getTimeUUID(); UUID schemaVersion = UUIDGen.getTimeUUID(); execute(insert, InetAddress.getByName("127.0.0.1"), "dcFoo", hostId, InetAddress.getByName("127.0.0.2"), "rackFoo", "4.0", InetAddress.getByName("127.0.0.3"), schemaVersion, ImmutableSet.of("foobar")); SystemKeyspaceMigrator40.migrate(); int rowCount = 0; for (UntypedResultSet.Row row : execute(String.format("SELECT * FROM %s", SystemKeyspaceMigrator40.peersName))) { rowCount++; assertEquals(InetAddress.getByName("127.0.0.1"), row.getInetAddress("peer")); assertEquals(DatabaseDescriptor.getStoragePort(), row.getInt("peer_port")); assertEquals("dcFoo", row.getString("data_center")); assertEquals(hostId, row.getUUID("host_id")); assertEquals(InetAddress.getByName("127.0.0.2"), row.getInetAddress("preferred_ip")); assertEquals(DatabaseDescriptor.getStoragePort(), row.getInt("preferred_port")); assertEquals("rackFoo", row.getString("rack")); assertEquals("4.0", row.getString("release_version")); assertEquals(InetAddress.getByName("127.0.0.3"), row.getInetAddress("native_address")); assertEquals(DatabaseDescriptor.getNativeTransportPort(), row.getInt("native_port")); assertEquals(schemaVersion, row.getUUID("schema_version")); assertEquals(ImmutableSet.of("foobar"), row.getSet("tokens", UTF8Type.instance)); } assertEquals(1, rowCount); //Test nulls/missing don't prevent the row from propagating execute(String.format("TRUNCATE %s", SystemKeyspaceMigrator40.legacyPeersName)); execute(String.format("TRUNCATE %s", SystemKeyspaceMigrator40.peersName)); execute(String.format("INSERT INTO %s (peer) VALUES (?)", SystemKeyspaceMigrator40.legacyPeersName), InetAddress.getByName("127.0.0.1")); SystemKeyspaceMigrator40.migrate(); rowCount = 0; for (UntypedResultSet.Row row : execute(String.format("SELECT * FROM %s", SystemKeyspaceMigrator40.peersName))) { rowCount++; } assertEquals(1, rowCount); } @Test public void testMigratePeerEvents() throws Throwable { String insert = String.format("INSERT INTO %s (" + "peer, " + "hints_dropped) " + " values ( ?, ? )", SystemKeyspaceMigrator40.legacyPeerEventsName); UUID uuid = UUIDGen.getTimeUUID(); execute(insert, InetAddress.getByName("127.0.0.1"), ImmutableMap.of(uuid, 42)); SystemKeyspaceMigrator40.migrate(); int rowCount = 0; for (UntypedResultSet.Row row : execute(String.format("SELECT * FROM %s", SystemKeyspaceMigrator40.peerEventsName))) { rowCount++; assertEquals(InetAddress.getByName("127.0.0.1"), row.getInetAddress("peer")); assertEquals(DatabaseDescriptor.getStoragePort(), row.getInt("peer_port")); assertEquals(ImmutableMap.of(uuid, 42), row.getMap("hints_dropped", UUIDType.instance, Int32Type.instance)); } assertEquals(1, rowCount); //Test nulls/missing don't prevent the row from propagating execute(String.format("TRUNCATE %s", SystemKeyspaceMigrator40.legacyPeerEventsName)); execute(String.format("TRUNCATE %s", SystemKeyspaceMigrator40.peerEventsName)); execute(String.format("INSERT INTO %s (peer) VALUES (?)", SystemKeyspaceMigrator40.legacyPeerEventsName), InetAddress.getByName("127.0.0.1")); SystemKeyspaceMigrator40.migrate(); rowCount = 0; for (UntypedResultSet.Row row : execute(String.format("SELECT * FROM %s", SystemKeyspaceMigrator40.peerEventsName))) { rowCount++; } assertEquals(1, rowCount); } @Test public void testMigrateTransferredRanges() throws Throwable { String insert = String.format("INSERT INTO %s (" + "operation, " + "peer, " + "keyspace_name, " + "ranges) " + " values ( ?, ?, ?, ? )", SystemKeyspaceMigrator40.legacyTransferredRangesName); execute(insert, "foo", InetAddress.getByName("127.0.0.1"), "bar", ImmutableSet.of(ByteBuffer.wrap(new byte[] { 42 }))); SystemKeyspaceMigrator40.migrate(); int rowCount = 0; for (UntypedResultSet.Row row : execute(String.format("SELECT * FROM %s", SystemKeyspaceMigrator40.transferredRangesName))) { rowCount++; assertEquals("foo", row.getString("operation")); assertEquals(InetAddress.getByName("127.0.0.1"), row.getInetAddress("peer")); assertEquals(DatabaseDescriptor.getStoragePort(), row.getInt("peer_port")); assertEquals("bar", row.getString("keyspace_name")); assertEquals(ImmutableSet.of(ByteBuffer.wrap(new byte[] { 42 })), row.getSet("ranges", BytesType.instance)); } assertEquals(1, rowCount); //Test nulls/missing don't prevent the row from propagating execute(String.format("TRUNCATE %s", SystemKeyspaceMigrator40.legacyTransferredRangesName)); execute(String.format("TRUNCATE %s", SystemKeyspaceMigrator40.transferredRangesName)); execute(String.format("INSERT INTO %s (operation, peer, keyspace_name) VALUES (?, ?, ?)", SystemKeyspaceMigrator40.legacyTransferredRangesName), "foo", InetAddress.getByName("127.0.0.1"), "bar"); SystemKeyspaceMigrator40.migrate(); rowCount = 0; for (UntypedResultSet.Row row : execute(String.format("SELECT * FROM %s", SystemKeyspaceMigrator40.transferredRangesName))) { rowCount++; } assertEquals(1, rowCount); } }
{'content_hash': '3ce7b462bf45c4f28fab5777e77c8410', 'timestamp': '', 'source': 'github', 'line_count': 176, 'max_line_length': 152, 'avg_line_length': 45.0, 'alnum_prop': 0.5757575757575758, 'repo_name': 'mkjellman/cassandra', 'id': '1c051f50d0e49503788839bf1f0af3597cb4f0be', 'size': '8725', 'binary': False, 'copies': '5', 'ref': 'refs/heads/trunk', 'path': 'test/unit/org/apache/cassandra/db/SystemKeyspaceMigrator40Test.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '801'}, {'name': 'Batchfile', 'bytes': '37481'}, {'name': 'GAP', 'bytes': '86323'}, {'name': 'HTML', 'bytes': '264240'}, {'name': 'Java', 'bytes': '19402920'}, {'name': 'Lex', 'bytes': '10151'}, {'name': 'PowerShell', 'bytes': '39138'}, {'name': 'Python', 'bytes': '514138'}, {'name': 'Shell', 'bytes': '81919'}]}
package com.izforge.izpack.core.resource; import com.izforge.izpack.api.exception.ResourceException; import com.izforge.izpack.api.exception.ResourceNotFoundException; import com.izforge.izpack.api.resource.Locales; import java.io.InputStream; import java.net.URL; import java.util.List; import java.util.Locale; /** * With this ResourceManager you are able to get resources from the jar file. * <p/> * All resources are loaded language dependent as it's done in java.util.ResourceBundle. To set a * language dependent resource just append '_' and the locale to the end of the Resourcename<br> * <br> * Example: * <li>InfoPanel.info - for default value</li> * <li>InfoPanel.info_deu - for german value</li> * <li>InfoPanel.info_eng - for english value</li> <br> * <p/> * * @author Marcus Stursberg * @author Tim Anderson */ public class ResourceManager extends AbstractResources { /** * The locales. */ private Locales locales; /** * The base path where to find the resources: resourceBasePathDefaultConstant = "/res/" */ public final static String RESOURCE_BASEPATH_DEFAULT = "/resources/"; /** * Internally used resourceBasePath = "/resources/" */ private String resourceBasePath = "/resources/"; /** * Constructs a <tt>ResourceManager</tt>. */ public ResourceManager() { this(Thread.currentThread().getContextClassLoader()); } /** * Constructs a <tt>ResourceManager</tt>. * * @param loader the class loader to use to load resources */ public ResourceManager(ClassLoader loader) { super(loader); } public static String getInstallLoggingConfigurationResourceName() { return RESOURCE_BASEPATH_DEFAULT + DEFAULT_INSTALL_LOGGING_CONFIGURATION_RES; } /** * Registers the supported locales. * * @param locales the locales. May be {@code null} */ public void setLocales(Locales locales) { this.locales = locales; } /** * Returns an InputStream contains the given Resource The Resource is loaded language dependen * by the informations from <code>this.locale</code> If there is no Resource for the current * language found, the default Resource is given. * * @param resource The resource to load * @return an InputStream contains the requested resource * @throws ResourceNotFoundException thrown if there is no resource found */ @Override public InputStream getInputStream(String resource) { resource = getLanguageResourceString(resource); return super.getInputStream(resource); } /** * Returns the URL to a resource. * * @param name the resource name * @return the URL to the resource * @throws ResourceNotFoundException if the resource cannot be found */ @Override public URL getURL(String name) { return getResource(getLanguageResourceString(name)); } /** * Returns the locale's ISO3 language code. * * @return the current language code, or {@code null} if no locale is set */ public String getLocale() { if (locales != null) { Locale locale = locales.getLocale(); return (locale != null) ? locale.getISO3Language() : null; } return null; } public String getResourceBasePath() { return resourceBasePath; } public void setResourceBasePath(String resourceBasePath) { this.resourceBasePath = resourceBasePath; } /** * Returns an ArrayList of the available langpacks ISO3 codes. * * @return The available langpacks list. * @throws ResourceNotFoundException if the langpacks resource cannot be found * @throws ResourceException if the langpacks resource cannot be retrieved * @deprecated use {@link com.izforge.izpack.api.resource.Locales#getLocales()} */ @SuppressWarnings("unchecked") @Deprecated public List<String> getAvailableLangPacks() { return (List<String>) getObject("langpacks.info"); } /** * Resolves relative resource names. * <p/> * This implementation prefixes relative resource names with {@link #getResourceBasePath()}. * * @param name the resource name * @return the absolute resource name */ @Override protected String resolveName(String name) { name = (name.charAt(0) == '/') ? name : getResourceBasePath() + name; return super.resolveName(name); } /** * This method is used to get the language dependent path of the given resource. If there is a * resource for the current language the path of the language dependent resource is returned. If * there's no resource for the current lanugage the default path is returned. * * @param resource the resource to load * @return the language dependent path of the given resource * @throws ResourceNotFoundException If the resource is not found */ private String getLanguageResourceString(String resource) { Locale locale = (locales != null) ? locales.getLocale() : null; String country = null; String language = null; if (locale != null) { country = LocaleHelper.getISO3Country(locale); language = LocaleHelper.getISO3Language(locale); } // use lowercase country code for backwards compatibility String resourcePath = (country != null) ? resource + "_" + country.toLowerCase() : null; if (resourcePath != null && getResource(resourcePath) != null) { return resourcePath; } resourcePath = (language != null) ? resource + "_" + language : null; if (resourcePath != null && getResource(resourcePath) != null) { return resourcePath; } if (getResource(resource) != null) { return resource; } if (resourcePath != null) { throw new ResourceNotFoundException("Cannot find named resource: '" + resource + "' AND '" + resourcePath + "'"); } throw new ResourceNotFoundException("Cannot find named resource: '" + resource + "'"); } }
{'content_hash': '7ef50d3d76d96348e79f48ad71b423f0', 'timestamp': '', 'source': 'github', 'line_count': 207, 'max_line_length': 100, 'avg_line_length': 30.82125603864734, 'alnum_prop': 0.6363636363636364, 'repo_name': 'izpack/izpack', 'id': '3dda8854ec8ebec5550567a60a16ab70aeb702bb', 'size': '7136', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'izpack-core/src/main/java/com/izforge/izpack/core/resource/ResourceManager.java', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '4963'}, {'name': 'C', 'bytes': '7579'}, {'name': 'C++', 'bytes': '122183'}, {'name': 'CSS', 'bytes': '6106'}, {'name': 'Groovy', 'bytes': '2560'}, {'name': 'HTML', 'bytes': '4828'}, {'name': 'Java', 'bytes': '6142189'}, {'name': 'JavaScript', 'bytes': '2150'}, {'name': 'Makefile', 'bytes': '149'}, {'name': 'Python', 'bytes': '21668'}, {'name': 'Shell', 'bytes': '47731'}, {'name': 'TeX', 'bytes': '35053'}]}
@interface CDTURLSessionTaskTests : CloudantSyncTests @end @implementation CDTURLSessionTaskTests - (void)testTaskCorrectlyProxiesCalls { NSURLSessionDataTask *task = [[NSURLSessionDataTask alloc] init]; id mockedTask = OCMPartialMock(task); OCMStub([mockedTask state]).andReturn(NSURLSessionTaskStateSuspended); OCMStub([(NSURLSessionDataTask *)mockedTask resume]).andDo(nil); OCMStub([mockedTask cancel]).andDo(nil); NSThread *thread = [[NSThread alloc] init]; CDTURLSession *session = [[CDTURLSession alloc] initWithCallbackThread:thread requestInterceptors:nil sessionConfigDelegate:nil]; id mockedSession = OCMPartialMock(session); OCMStub([mockedSession createDataTaskWithRequest:[OCMArg any] associatedWithTask:[OCMArg any]]) .andReturn(mockedTask); OCMStub([mockedSession disassociateTask:[OCMArg any]]).andDo(nil); NSURLRequest *r = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost"]]; CDTURLSessionTask *cdtTask = [[CDTURLSessionTask alloc] initWithSession:mockedSession request:r interceptors:nil]; //call void methods methods [cdtTask resume]; [cdtTask cancel]; //verify that object state is as expected XCTAssertEqual(NSURLSessionTaskStateSuspended, [cdtTask state]); //verify mock methods called OCMVerify([(NSURLSessionDataTask *)mockedTask resume]); OCMVerify([mockedTask cancel]); OCMVerify([mockedTask state]); } @end
{'content_hash': '61109e36e85949b988f2de6f757cd407', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 99, 'avg_line_length': 37.57142857142857, 'alnum_prop': 0.6983523447401775, 'repo_name': 'cloudant/CDTDatastore', 'id': '994ea4ec094f34ec05ea717767f19d2d1b9a4f77', 'size': '2425', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'CDTDatastoreTests/CDTURLSessionTaskTests.m', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '4925'}, {'name': 'Objective-C', 'bytes': '2265430'}, {'name': 'Ruby', 'bytes': '12504'}, {'name': 'Shell', 'bytes': '343'}, {'name': 'Swift', 'bytes': '1773'}]}
using Prism.Regions; using System.Composition; namespace Prism.SysComposition.Regions { /// <summary> /// Exports the SysCompRegionNavigationJournal using the Managed Extensibility Framework (MEF). /// </summary> /// <remarks> /// This allows the SysCompBootstrapper to provide this class as a default implementation. /// If another implementation is found, this export will not be used. /// </remarks> [Export(typeof(IRegionNavigationJournal))] public class SysCompRegionNavigationJournal : RegionNavigationJournal { } }
{'content_hash': 'de4020c23b88581070907330233950f8', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 99, 'avg_line_length': 33.588235294117645, 'alnum_prop': 0.7162872154115587, 'repo_name': 'dbeavon/PrismComposition', 'id': 'ed6bab440bd0b22d977b7219e054071dba16cf89', 'size': '571', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Source/Wpf/Prism.SysComposition.Wpf/Regions/SysCompRegionNavigationJournal.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '66839'}, {'name': 'Smalltalk', 'bytes': '45'}]}
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>io_service::strand::dispatch</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../io_service__strand.html" title="io_service::strand"> <link rel="prev" href="../io_service__strand.html" title="io_service::strand"> <link rel="next" href="get_io_service.html" title="io_service::strand::get_io_service"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../io_service__strand.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../io_service__strand.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="get_io_service.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="boost_asio.reference.io_service__strand.dispatch"></a><a class="link" href="dispatch.html" title="io_service::strand::dispatch">io_service::strand::dispatch</a> </h4></div></div></div> <p> <a class="indexterm" name="idp85309896"></a> Request the strand to invoke the given handler. </p> <pre class="programlisting"><span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="../CompletionHandler.html" title="Completion handler requirements">CompletionHandler</a><span class="special">&gt;</span> <a class="link" href="../asynchronous_operations.html#boost_asio.reference.asynchronous_operations.return_type_of_an_initiating_function"><span class="emphasis"><em>void-or-deduced</em></span></a> <span class="identifier">dispatch</span><span class="special">(</span> <span class="identifier">CompletionHandler</span> <span class="identifier">handler</span><span class="special">);</span> </pre> <p> This function is used to ask the strand to execute the given handler. </p> <p> The strand object guarantees that handlers posted or dispatched through the strand will not be executed concurrently. The handler may be executed inside this function if the guarantee can be met. If this function is called from within a handler that was posted or dispatched through the same strand, then the new handler will be executed immediately. </p> <p> The strand's guarantee is in addition to the guarantee provided by the underlying <a class="link" href="../io_service.html" title="io_service"><code class="computeroutput"><span class="identifier">io_service</span></code></a>. The <a class="link" href="../io_service.html" title="io_service"><code class="computeroutput"><span class="identifier">io_service</span></code></a> guarantees that the handler will only be called in a thread in which the io_service's run member function is currently being invoked. </p> <h6> <a name="boost_asio.reference.io_service__strand.dispatch.h0"></a> <span class="phrase"><a name="boost_asio.reference.io_service__strand.dispatch.parameters"></a></span><a class="link" href="dispatch.html#boost_asio.reference.io_service__strand.dispatch.parameters">Parameters</a> </h6> <div class="variablelist"> <p class="title"><b></b></p> <dl class="variablelist"> <dt><span class="term">handler</span></dt> <dd> <p> The handler to be called. The strand will make a copy of the handler object as required. The function signature of the handler must be: </p> <pre class="programlisting"><span class="keyword">void</span> <span class="identifier">handler</span><span class="special">();</span> </pre> <p> </p> </dd> </dl> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2013 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../io_service__strand.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../io_service__strand.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="get_io_service.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{'content_hash': '5e3c837b85aeec2c304d4e86357ce369', 'timestamp': '', 'source': 'github', 'line_count': 88, 'max_line_length': 451, 'avg_line_length': 64.44318181818181, 'alnum_prop': 0.650326221125022, 'repo_name': 'yxcoin/yxcoin', 'id': 'df6f79827c12f27a909d1976b09f345661e134f1', 'size': '5671', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/boost_1_55_0/doc/html/boost_asio/reference/io_service__strand/dispatch.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '222528'}, {'name': 'Batchfile', 'bytes': '26447'}, {'name': 'C', 'bytes': '2572612'}, {'name': 'C#', 'bytes': '40804'}, {'name': 'C++', 'bytes': '151033085'}, {'name': 'CMake', 'bytes': '1741'}, {'name': 'CSS', 'bytes': '270134'}, {'name': 'Cuda', 'bytes': '26749'}, {'name': 'Fortran', 'bytes': '1387'}, {'name': 'HTML', 'bytes': '151665458'}, {'name': 'IDL', 'bytes': '14'}, {'name': 'JavaScript', 'bytes': '132031'}, {'name': 'Lex', 'bytes': '1231'}, {'name': 'M4', 'bytes': '29689'}, {'name': 'Makefile', 'bytes': '1094300'}, {'name': 'Max', 'bytes': '36857'}, {'name': 'NSIS', 'bytes': '6041'}, {'name': 'Objective-C', 'bytes': '11848'}, {'name': 'Objective-C++', 'bytes': '3755'}, {'name': 'PHP', 'bytes': '59030'}, {'name': 'Perl', 'bytes': '28121'}, {'name': 'Perl6', 'bytes': '2053'}, {'name': 'Python', 'bytes': '1720604'}, {'name': 'QML', 'bytes': '593'}, {'name': 'QMake', 'bytes': '24083'}, {'name': 'Rebol', 'bytes': '354'}, {'name': 'Roff', 'bytes': '8039'}, {'name': 'Shell', 'bytes': '350488'}, {'name': 'Tcl', 'bytes': '1172'}, {'name': 'TeX', 'bytes': '13404'}, {'name': 'XSLT', 'bytes': '687839'}, {'name': 'Yacc', 'bytes': '18910'}]}
/* * A simple HTTP library. * * Usage example: * * // Returns NULL if an error was encountered. * struct http_request *request = http_request_parse(fd); * * ... * * http_start_response(fd, 200); * http_send_header(fd, "Content-type", http_get_mime_type("index.html")); * http_send_header(fd, "Server", "httpserver/1.0"); * http_end_headers(fd); * http_send_string(fd, "<html><body><a href='/'>Home</a></body></html>"); * * close(fd); */ #ifndef LIBHTTP_H #define LIBHTTP_H /* * Functions for parsing an HTTP request. */ struct http_request { char *method; char *path; }; struct http_request *http_request_parse(int fd); /* * Functions for sending an HTTP response. */ void http_start_response(int fd, int status_code); void http_send_header(int fd, char *key, char *value); void http_end_headers(int fd); void http_send_string(int fd, char *data); void http_send_data(int fd, char *data, size_t size); /* * Helper function: gets the Content-Type based on a file name. */ char *http_get_mime_type(char *file_name); #endif
{'content_hash': '1bf78769fbd6b59593e340dafd758710', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 78, 'avg_line_length': 23.19148936170213, 'alnum_prop': 0.6403669724770642, 'repo_name': 'Quexint/Assignment-Driven-Learning', 'id': 'e6d4036c5e0cd354f9d6f50a87afd0f859bf9a9c', 'size': '1090', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'OCW/[UCB]CS162_Operating_Systems_and_System_Programming/Homeworks/hw2/libhttp.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '59411'}, {'name': 'C++', 'bytes': '1201623'}, {'name': 'Cool', 'bytes': '77973'}, {'name': 'HTML', 'bytes': '4530'}, {'name': 'Java', 'bytes': '1226154'}, {'name': 'Jupyter Notebook', 'bytes': '90842'}, {'name': 'Lex', 'bytes': '6552'}, {'name': 'Makefile', 'bytes': '33883'}, {'name': 'Perl', 'bytes': '380153'}, {'name': 'Python', 'bytes': '101809'}, {'name': 'Ruby', 'bytes': '3013'}, {'name': 'Shell', 'bytes': '9885'}, {'name': 'Swift', 'bytes': '12873'}, {'name': 'Yacc', 'bytes': '10922'}]}
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{'content_hash': '041b73186908206dabdfa81d3cfe83d7', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': 'd12625cfe80eccc539643885b27b64fe4ca4abb4', 'size': '176', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Escalloniales/Escalloniaceae/Escallonia/Escallonia carmelita/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
module SharedUser extend ActiveSupport::Concern included do devise :database_authenticatable, :confirmable, :lockable, :recoverable, :registerable, :rememberable, :timeoutable, :trackable, :validatable, :omniauthable attr_accessor :other_key # They need to be included after Devise is called. extend ExtendMethods end def raw_confirmation_token @raw_confirmation_token end module ExtendMethods def new_with_session(params, session) super.tap do |user| if data = session["devise.facebook_data"] user.email = data["email"] user.confirmed_at = Time.now end end end end end
{'content_hash': 'ea9f9d0987bfcd1e559dab0ab2d20a52', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 76, 'avg_line_length': 23.689655172413794, 'alnum_prop': 0.660844250363901, 'repo_name': 'suhongrui/gitlab', 'id': '511c23cad18f1393e86e29f6a9b6636d584e4092', 'size': '687', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'vendor/bundle/ruby/2.1.0/gems/devise-3.2.4/test/rails_app/lib/shared_user.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '113763'}, {'name': 'CoffeeScript', 'bytes': '109865'}, {'name': 'Cucumber', 'bytes': '113031'}, {'name': 'HTML', 'bytes': '372689'}, {'name': 'JavaScript', 'bytes': '29449'}, {'name': 'Ruby', 'bytes': '1841958'}, {'name': 'Shell', 'bytes': '12768'}]}
package main /* * Imports for messuring execution time of requests */ import ( "time" ) /* * Imports for reading the config, logging and command line argument parsing. */ import ( "flag" "fmt" "log" "os" "passivetotal-service/config" "path/filepath" "strings" ) /* * Imports for serving on a socket and handling of incoming request. */ import ( "encoding/json" "github.com/julienschmidt/httprouter" "io/ioutil" "net/http" ) /* * Imports relevant for service execution */ import ( "passivetotal-service/passivetotal" "sync" ) // global variables var ( cfg *Config infoLogger *log.Logger metadata Metadata = Metadata{ Name: "PassiveTotal", Version: "1.0", Description: "./README.md", Copyright: "Copyright 2016 Holmes Group LLC", License: "./LICENSE", } ) // config structs type Metadata struct { Name string Version string Description string Copyright string License string } type Settings struct { Port string } type PassivetotalSettings struct { APIUser string APIKey string RequestTimeout int } type Config struct { Setting Settings Passivetotal PassivetotalSettings } // main logic func main() { var configPath string // setup logging infoLogger = log.New(os.Stdout, "", log.Ltime|log.Lshortfile) // load config flag.StringVar(&configPath, "config", "", "Path to the configuration file") flag.Parse() if configPath == "" { configPath, _ = filepath.Abs(filepath.Dir(os.Args[0])) configPath = filepath.Join(configPath, "service.conf") } cfg = &Config{} config.Parse(cfg, configPath) // read metadata-files if data, err := ioutil.ReadFile(metadata.Description); err == nil { metadata.Description = strings.Replace(string(data), "\n", "<br>", -1) } if data, err := ioutil.ReadFile(metadata.License); err == nil { metadata.License = strings.Replace(string(data), "\n", "<br>", -1) } // setup http handlers router := httprouter.New() router.GET("/analyze/", handlerAnalyze) router.GET("/", handlerInfo) infoLogger.Printf("Binding to %s\n", cfg.Setting.Port) infoLogger.Fatal(http.ListenAndServe(cfg.Setting.Port, router)) } func handlerInfo(f_response http.ResponseWriter, r *http.Request, ps httprouter.Params) { result := fmt.Sprintf(` <p>%s - %s</p> <hr> <p>%s</p> <hr> <p>%s</p> `, metadata.Name, metadata.Version, metadata.Description, metadata.License) fmt.Fprint(f_response, result) } func handlerAnalyze(f_response http.ResponseWriter, request *http.Request, params httprouter.Params) { infoLogger.Println("Serving request:", request) startTime := time.Now() // Get settings and do PT queries. // Marshal result right away, after testing if there was an error. result, status := doPassiveTotalLookup(request, params) var resultJSON []byte if result != nil { resultJSON, _ = json.Marshal(result) } else { resultJSON = []byte("{}") } // Send back a response of type text/json f_response.Header().Set("Content-Type", "text/json; charset=utf-8") f_response.WriteHeader(status) f_response.Write(resultJSON) elapsedTime := time.Since(startTime) infoLogger.Printf("Done in %s.\n", elapsedTime) } func doPassiveTotalLookup(r *http.Request, p httprouter.Params) (interface{}, int) { // Generic result object, returned in case of an error instead of the query // object: var errResult struct { Error string `json:"error"` } obj := r.URL.Query().Get("obj") if obj == "" { errResult.Error = "Missing argument 'obj'" return errResult, 400 } // Create a settings object to use with the query, parse parameters passed // via the request body into it (all options can be overriden): aqs := &passivetotal.ApiQuerySettings{ Object: obj, Username: cfg.Passivetotal.APIUser, ApiKey: cfg.Passivetotal.APIKey, Timeout: cfg.Passivetotal.RequestTimeout, } if r.Body != nil { if bytes, err := ioutil.ReadAll(r.Body); err != nil { msg := "Unexpected error reading the request body: " + err.Error() infoLogger.Println(msg) errResult.Error = msg return errResult, 400 } else if len(bytes) > 0 { if err = json.Unmarshal(bytes, aqs); err != nil { msg := "Unexpected error parsing request settings: " + err.Error() infoLogger.Println(msg) errResult.Error = msg return errResult, 400 } } } // Create a new query object based on the settings, also check for errors // during query creation. Only errors possible are due to invalid input // (either filtered or unknown type). query, err := passivetotal.NewApiQuery(aqs) if err != nil { infoLogger.Println("Dropping query due to: " + err.Error()) errResult.Error = err.Error() return errResult, 422 // Status Code: Unprocessable Entity } wg := &sync.WaitGroup{} wg.Add(9) go func(wg *sync.WaitGroup) { defer wg.Done() query.DoPassiveDnsQuery() }(wg) go func(wg *sync.WaitGroup) { defer wg.Done() query.DoWhoisQuery() }(wg) go func(wg *sync.WaitGroup) { defer wg.Done() query.DoWhoisEmailSearch() }(wg) // TODO: ssl query only accepts a certificate hash (sha1), need a per-request option to make this useful // go func(wg *sync.WaitGroup) { // defer wg.Done() // query.DoSslQuery() // }(wg) // TODO: same as for DoSslQuery above, additionally IP seems to not work unlike specified in the API documentation // go func(wg *sync.WaitGroup) { // defer wg.Done() // query.DoSslHistoryQuery() // }(wg) go func(wg *sync.WaitGroup) { defer wg.Done() query.DoSubdomainQuery() }(wg) go func(wg *sync.WaitGroup) { defer wg.Done() query.DoEnrichmentQuery() }(wg) go func(wg *sync.WaitGroup) { defer wg.Done() query.DoTrackerQuery() }(wg) go func(wg *sync.WaitGroup) { defer wg.Done() query.DoComponentQuery() }(wg) go func(wg *sync.WaitGroup) { defer wg.Done() query.DoOsintQuery() }(wg) go func(wg *sync.WaitGroup) { defer wg.Done() query.DoMalwareQuery() }(wg) wg.Wait() // By default assume success, unless the length of errors is not 0. // In that case check if it is a known error (user has reached his paid // quota / user credentials invalid), or if it is an unknown error, in which // case we should return 500 as there should be no error condition that is // unknown (other than maybe a 500 by the PassiveTotal servers, in which // case we should have a 500 too, to indicate the severity of the error). if len(query.Errors) != 0 { status := 200 if query.QuotaReached { errResult.Error = "Quota Reached" status = 402 } else if query.InvalidAuthentication { errResult.Error = "Invalid Authentication" status = 401 } else if query.ConnectionError { errResult.Error = "PassiveTotal API Unreachable" status = 502 } else { errResult.Error = "Unexpected Error" status = 500 } return errResult, status } // Everything is fine. return query, 200 }
{'content_hash': '5c43173b6e68dda966616298be5db4a0', 'timestamp': '', 'source': 'github', 'line_count': 286, 'max_line_length': 115, 'avg_line_length': 24.216783216783217, 'alnum_prop': 0.6796130522668207, 'repo_name': 'HolmesProcessing/Holmes-Totem', 'id': 'ca4d851f947c211d85b0813f4879798828ba5a04', 'size': '6926', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/main/scala/org/holmesprocessing/totem/services/passivetotal/src/passivetotal-service/main.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '12938'}, {'name': 'Go', 'bytes': '108211'}, {'name': 'Python', 'bytes': '105006'}, {'name': 'Scala', 'bytes': '98949'}, {'name': 'Shell', 'bytes': '1905'}, {'name': 'YARA', 'bytes': '6110160'}]}
<!DOCTYPE html> <html> <head> <title>jQuery MiniColors</title> <meta content="A tiny color picker built on jQuery" name="description"> <meta charset="utf-8"> <meta content="initial-scale=1.0" name="viewport"> <link href="jquery.minicolors.css" rel="stylesheet"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="jquery.minicolors.js"></script> <style> HTML, BODY { padding: 0; margin: 0; } BODY { font: 14px sans-serif; color: #666; line-height: 1.7; background: #F8F8F8; padding: 0 20px; padding-bottom: 32px; } H1, H2, H3 { font-family: Georgia, serif; font-weight: normal; color: black; overflow: hidden; text-overflow: ellipsis; } H1, H2, H3, P { margin: 20px 0; } H3 { color: gray; } A { color: #08C; } A:hover { color: #0BE; } PRE, CODE { background: #F8F8F8; padding: 2px; } PRE { overflow: hidden; text-overflow: ellipsis; padding: 10px; margin: 30px 0; } DL { border: solid 1px #EEE; padding: 20px; } .alert { background: #FFFCCC; color: black; padding: 1px 10px; margin: 30px 0; } #main { max-width: 800px; background: white; border: solid 1px #DDD; box-shadow: 0 0 30px rgba(0, 0, 0, .05); padding: 30px; margin: 20px auto; } .example { background: #F8F8F8; padding: 10px; margin: 30px 0; } #console { position: fixed; left: 0; right: 0; bottom: 0; height: 32px; font-family: monospace; line-height: 32px; text-align: center; background: black; color: white; z-index: 100; -moz-transition: all .5s; -ms-transition: all .5s; -webkit-transition: all .5s; transition: all .5s; opacity: 0; } #console.busy { opacity: .85; } </style> <script> $(document).ready( function() { var consoleTimeout; $('.minicolors').each( function() { // // Dear reader, it's actually much easier than this to initialize // miniColors. For example: // // $(selector).minicolors(); // // The way I've done it below is just to make it easier for me // when developing the plugin. It keeps me sane, but it may not // have the same effect on you! // $(this).minicolors({ control: $(this).attr('data-control') || 'hue', defaultValue: $(this).attr('data-default-value') || '', inline: $(this).hasClass('inline'), letterCase: $(this).hasClass('uppercase') ? 'uppercase' : 'lowercase', opacity: $(this).hasClass('opacity'), position: $(this).attr('data-position') || 'default', styles: $(this).attr('data-style') || '', swatchPosition: $(this).attr('data-swatch-position') || 'left', textfield: !$(this).hasClass('no-textfield'), theme: $(this).attr('data-theme') || 'default', change: function(hex, opacity) { // Generate text to show in console text = hex ? hex : 'transparent'; if( opacity ) text += ', ' + opacity; text += ' / ' + $(this).minicolors('rgbaString'); // Show text in console; disappear after a few seconds $('#console').text(text).addClass('busy'); clearTimeout(consoleTimeout); consoleTimeout = setTimeout( function() { $('#console').removeClass('busy'); }, 3000); } }); }); }); </script> </head> <body> <div id="main"> <h1>jQuery MiniColors 2.0 beta</h1> <p>A project by Cory LaViska of <a href="http://www.abeautifulsite.net/">A Beautiful Site</a>.</p> <p>MiniColors is a tiny color picker built on jQuery. It's easy to use and works well on touch-enabled devices. Completely re-written for 2.0.</p> <div class="alert"> <p>The MiniColors API was completely overhauled in 2.0. You will need to change your code if you are upgrading from a previous version!</p> </div> <h2>Demo</h2> <h3>Standard Controls</h3> <p>Hue <input class="minicolors" data-default-value="#fc0" type="text" value="#3b98bd"> Saturation <input class="minicolors" data-control="saturation" type="text" value="#50c900"> Brightness <input class= "minicolors" data-control="brightness" type="text" value="#7745ff"> Wheel <input class="minicolors" data-control="wheel" type="text" value="#ffb987"></p> <h3>Inline Controls</h3> <p><input class="minicolors inline" type="text" value="#3b98bd"> <input class="minicolors inline" data-control= "saturation" type="text" value="#50c900"> <input class="minicolors inline" data-control="brightness" type= "text" value="#7745ff"> <input class="minicolors inline" data-control="wheel" type="text" value="#ffb987"></p> <h2 id="download">Download</h2> <p>You can <a href="https://github.com/claviska/jquery-miniColors">download the source</a> on GitHub. Help contribute to this project by posting bug reports, feature requests, and code improvements!</p> <h2 id="usage">Usage</h2> <pre> $('INPUT.minicolors').minicolors(<em>settings</em>); </pre> <h2 id="settings">Settings</h2> <p>All available settings are shown below with default values:</p> <pre> { animationSpeed: 100, animationEasing: 'swing', change: null, control: 'hue', defaultValue: '', hide: null, hideSpeed: 100, inline: false, letterCase: 'lowercase', opacity: false, position: 'default', show: null, showSpeed: 100, swatchPosition: 'left', textfield: true, theme: 'default' } </pre> <dl> <dt><code>animationSpeed</code></dt> <dd> <p>The animation speed of the sliders when the user taps or clicks a new color. Set to <code>0</code> for no animation.</p> </dd> <dt><code>animationEasing</code></dt> <dd> <p>The easing to use when animating the sliders.</p> </dd> <dt><code>control</code></dt> <dd> <p>Determines the type of control. Valid options are <code>hue</code>, <code>brightness</code>, <code>saturation</code>, and <code>wheel</code>.</p> </dd> <dt><code>defaultValue</code></dt> <dd> <p>To force a default color, set this to a valid hex string. When the user clears the control, it will revert to this color.</p> <div class="example"> Default value: #ffcc00 <input class="minicolors" data-default-value="#ffcc00" type="text" value= "#ffb987"> </div> </dd> <dt><code>hideSpeed</code> &amp; <code>showSpeed</code></dt> <dd> <p>The speed at which to hide and show the color picker.</p> </dd> <dt><code>inline</code></dt> <dd> <p>Set to <code>true</code> to force the color picker to appear inline.</p> </dd> <dt><code>letterCase</code></dt> <dd> <p>Determines the letter case of the hex code value. Valid options are <code>uppercase</code> or <code>lowercase</code>.</p> <div class="example"> Uppercase <input class="minicolors uppercase" type="text" value="#abc"> Lowercase <input class= "minicolors lowercase" type="text" value="#abc"> </div> </dd> <dt><code>opacity</code></dt> <dd> <p>Set to <code>true</code> to enable the opacity slider. (Use the input element's <code>data-opacity</code> attribute to set a preset value.)</p> <div class="example"> <input class="minicolors opacity" type="text" value="#ffb987"> </div> </dd> <dt><code>position</code></dt> <dd> <p>Sets the position of the dropdown. Valid options are <code>default</code>, <code>top</code>, <code>left</code>, and <code>top left</code>.</p> <div class="example"> <code>default</code> <input class="minicolors" data-position="default" type="text" value="#3b98bd"> <code>top</code> <input class="minicolors" data-position="top" type="text" value="#50c900"> <code>left</code> <input class="minicolors" data-position="left" type="text" value="#7745ff"> <code>top left</code> <input class="minicolors" data-position="top left" type="text" value= "#ffb987"> </div> </dd> <dt><code>swatchPosition</code></dt> <dd> <p>Determines which side of the textfield the color swatch will appear. Valid options are <code>left</code> and <code>right</code>.</p> <div class="example"> <code>left</code> <input class="minicolors" data-swatch-position="left" type="text" value= "#3b98bd"> <code>right</code> <input class="minicolors" data-swatch-position="right" type="text" value="#50c900"> </div> </dd> <dt><code>textfield</code></dt> <dd> <p>Whether or not to show the textfield. Set to <code>false</code> for a swatch-only control:</p> <div class="example"> <input class="minicolors no-textfield" type="text" value="#3b98bd"> </div> </dd> <dt><code>theme</code></dt> <dd> <p>A string containing the name of the custom theme to be applied. In your CSS, prefix your selectors like this:</p> <pre> .minicolors-theme-yourThemeName { ... } </pre> <p>Then set your theme like this:</p> <pre> $(<em>selector</em>).minicolors({ theme: 'yourThemeName' }); </pre> <p>Here are a few examples:</p> <div class="example"> Default theme (<code>default</code>)<br> <input class="minicolors" type="text" value="#7ad674"><br> <br> Bootstrap theme (<code>bootstrap</code>)<br> <input class="minicolors opacity" data-theme="bootstrap" type="text" value= "#2eb2e6"><br> <br> No theme (<code>none</code>)<br> <input class="minicolors" data-theme="none" type="text" value="#d96464"> </div> <h3>A note about writing themes</h3> <p>When writing a theme, please make sure it supports both swatch positions (<code>swatchPosition</code>) and all panel positions (<code>position</code>). If you've written a theme and would like to have it included with MiniColors, feel free to <a href= "https://github.com/claviska/jquery-miniColors/">submit it to the project</a> on GitHub.</p> </dd> </dl> <h2 id="methods">Methods</h2> <p>Use this syntax for calling methods:</p> <pre> $(<em>selector</em>).minicolors('method', <em>[data]</em>); </pre> <dl> <dt><code>create</code></dt> <dd> <p>Initializes the control for all items matching your selector. This is the default method, so <code>data</code> may be passed in as the only argument.</p> <p>To set a preset color value, populate the <code>value</code> attribute of the original input element.</p> </dd> <dt><code>destroy</code></dt> <dd> <p>Returns the <em>input</em> element to its original, uninitialized state.</p> </dd> <dt><code>opacity</code></dt> <dd> <p>Gets or sets a control's opacity level. To use this method as a setter, pass data in as a value between 0 and 1. (You can also obtain this value by checking the input element's <code>data-opacity</code> attribute.)</p> <p>To set a preset opacity value, populate the <code>data-opacity</code> attribute of the original input element.</p> </dd> <dt><code>rgbObject</code></dt> <dd> <p>Returns an object containing red, green, blue, and alpha properties that correspond to the control's current value. Example:</p> <pre> { r: 0, g: 82, b: 148, a: 0.75 } </pre> </dd> <dt><code>rgbString</code> &amp; <code>rgbaString</code></dt> <dd> <p>Returns an RGB or RGBA string suitable for use in your CSS. If opacity is enabled on the specified control, an RGBA string will be returned. Otherwise an RGB string will be returned. Examples:</p> <pre> rgb(0, 82, 148) rgba(0, 82, 148, .75) </pre> </dd> <dt><code>settings</code></dt> <dd> <p>Gets or sets a control's settings. If new settings are passed in, the control will destroy and re-initialize itself with any new settings overriding the old ones.</p> </dd> <dt><code>value</code></dt> <dd> <p>Gets or sets a control's color value. To use this method as a setter, pass <code>data</code> in as a hex value. (You can also obtain this value by checking the input element's <code>value</code> attribute.)</p> </dd> </dl> <h2 id="events">Events</h2> <dl> <dt><code>change</code></dt> <dd> <p>Fires when the value of the color picker changes. The <code>this</code> keyword will reference the original input element. <strong>Warning:</strong> This event will fire a lot if the user drags the color picker around.</p> <pre> $(<em>selector</em>).minicolors({ change: function(hex, opacity) { console.log(hex + ' - ' + opacity); } }); </pre> </dd> <dt><code>hide</code></dt> <dd> <p>Fires when the color picker is hidden. The <code>this</code> keyword will reference the original input element.</p> <pre> $(<em>selector</em>).minicolors({ hide: function() { console.log('Hide event triggered!'); } }); </pre> </dd> <dt><code>show</code></dt> <dd> <p>Fires when the color picker is shown. The <code>this</code> keyword will reference the original input element.</p> <pre> $(<em>selector</em>).minicolors({ show: function() { console.log('Show event triggered!'); } }); </pre> </dd> </dl> </div> <div id="console"></div> </body> </html>
{'content_hash': '6270bc283efcf29d328427d4da7ecfcf', 'timestamp': '', 'source': 'github', 'line_count': 499, 'max_line_length': 119, 'avg_line_length': 33.723446893787575, 'alnum_prop': 0.49340385072498216, 'repo_name': 'henyouqian/local_httpd', 'id': '0f70b4fe2df98a8a9870612fd1473a0fd8512511', 'size': '16828', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'samples/app_resource/www/jquery/jquery-miniColors/index.html', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '21550'}]}
using namespace ::v8::internal; static void yield() { UNIMPLEMENTED(); } static const int kLockCounterLimit = 50; static int busy_lock_counter = 0; static void LoopIncrement(Mutex* mutex, int rem) { while (true) { int count = 0; int last_count = -1; do { CHECK_EQ(0, mutex->Lock()); count = busy_lock_counter; CHECK_EQ(0, mutex->Unlock()); yield(); } while (count % 2 == rem && count < kLockCounterLimit); if (count >= kLockCounterLimit) break; CHECK_EQ(0, mutex->Lock()); CHECK_EQ(count, busy_lock_counter); CHECK(last_count == -1 || count == last_count + 1); busy_lock_counter++; last_count = count; CHECK_EQ(0, mutex->Unlock()); yield(); } } static void* RunTestBusyLock(void* arg) { LoopIncrement(static_cast<Mutex*>(arg), 0); return 0; } // Runs two threads that repeatedly acquire the lock and conditionally // increment a variable. TEST(BusyLock) { pthread_t other; Mutex* mutex = OS::CreateMutex(); int thread_created = pthread_create(&other, NULL, &RunTestBusyLock, mutex); CHECK_EQ(0, thread_created); LoopIncrement(mutex, 1); pthread_join(other, NULL); delete mutex; } TEST(VirtualMemory) { VirtualMemory* vm = new VirtualMemory(1 * MB); CHECK(vm->IsReserved()); void* block_addr = vm->address(); size_t block_size = 4 * KB; CHECK(vm->Commit(block_addr, block_size, false)); // Check whether we can write to memory. int* addr = static_cast<int*>(block_addr); addr[KB-1] = 2; CHECK(vm->Uncommit(block_addr, block_size)); delete vm; }
{'content_hash': 'e57d374b47b85f82344835a1e1a2d3a8', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 70, 'avg_line_length': 25.149253731343283, 'alnum_prop': 0.599406528189911, 'repo_name': 'Noah-Huppert/Website-2013', 'id': '3afbd90aeca85ed8646100b29b4d7c60fb4e51de', 'size': '3474', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'vhosts/www.noahhuppert.com/htdocs/trex/deps/v8/test/cctest/test-platform-nullos.cc', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Awk', 'bytes': '4270'}, {'name': 'C', 'bytes': '14473262'}, {'name': 'C++', 'bytes': '36950074'}, {'name': 'CSS', 'bytes': '1287710'}, {'name': 'Clean', 'bytes': '6801'}, {'name': 'Component Pascal', 'bytes': '1754'}, {'name': 'JavaScript', 'bytes': '3308483'}, {'name': 'Max', 'bytes': '296'}, {'name': 'Objective-C', 'bytes': '21478'}, {'name': 'PHP', 'bytes': '7546280'}, {'name': 'Perl', 'bytes': '431706'}, {'name': 'Python', 'bytes': '576430'}, {'name': 'Shell', 'bytes': '41084'}, {'name': 'VCL', 'bytes': '4153'}, {'name': 'Visual Basic', 'bytes': '11668'}, {'name': 'XSLT', 'bytes': '1737070'}]}
package com.goncalossilva.googlemapseverywhere.model; public final class MarkerOptions { private LatLng mPosition; public MarkerOptions() { } public MarkerOptions position(LatLng position) { mPosition = position; return this; } public LatLng getPosition() { return mPosition; } }
{'content_hash': '6107316dd994f47be630af4a5490e201', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 53, 'avg_line_length': 18.72222222222222, 'alnum_prop': 0.6646884272997032, 'repo_name': 'goncalossilva/GoogleMapsEverywhere', 'id': '52489b2cae24974ab4187fe74e534a23cfc1638c', 'size': '337', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'GoogleMapsEverywhere/src/main/java/com/goncalossilva/googlemapseverywhere/model/MarkerOptions.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '891'}, {'name': 'Java', 'bytes': '38093'}]}
package org.apache.drill.exec.expr.fn.impl.conv; import org.apache.drill.exec.expr.DrillSimpleFunc; import org.apache.drill.exec.expr.annotations.FunctionTemplate; import org.apache.drill.exec.expr.annotations.FunctionTemplate.FunctionScope; import org.apache.drill.exec.expr.annotations.FunctionTemplate.NullHandling; import org.apache.drill.exec.expr.annotations.Output; import org.apache.drill.exec.expr.annotations.Param; import org.apache.drill.exec.expr.annotations.Workspace; import org.apache.drill.exec.expr.holders.Float8Holder; import org.apache.drill.exec.expr.holders.VarBinaryHolder; @FunctionTemplate(names = {"convert_fromDOUBLE_OB", "convert_fromDOUBLE_OBD"}, scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL) public class OrderedBytesDoubleConvertFrom implements DrillSimpleFunc { @Param VarBinaryHolder in; @Output Float8Holder out; @Workspace byte[] bytes; @Workspace org.apache.hadoop.hbase.util.PositionedByteRange br; @Override public void setup() { bytes = new byte[9]; br = new org.apache.hadoop.hbase.util.SimplePositionedMutableByteRange(); } @Override public void eval() { org.apache.drill.exec.util.ByteBufUtil.checkBufferLength(in.buffer, in.start, in.end, 9); in.buffer.getBytes(in.start, bytes, 0, 9); br.set(bytes); out.value = org.apache.hadoop.hbase.util.OrderedBytes.decodeFloat64(br); } }
{'content_hash': 'edbbd6309bff80af398b647fbffa52c8', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 93, 'avg_line_length': 38.75, 'alnum_prop': 0.7784946236559139, 'repo_name': 'parthchandra/incubator-drill', 'id': '14764f18ba72a73245eddba3c67f1323f5b6f47f', 'size': '2196', 'binary': False, 'copies': '20', 'ref': 'refs/heads/master', 'path': 'contrib/storage-hbase/src/main/java/org/apache/drill/exec/expr/fn/impl/conv/OrderedBytesDoubleConvertFrom.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '6006'}, {'name': 'C', 'bytes': '31411'}, {'name': 'C++', 'bytes': '257521'}, {'name': 'CMake', 'bytes': '13503'}, {'name': 'FreeMarker', 'bytes': '55163'}, {'name': 'GAP', 'bytes': '16176'}, {'name': 'Java', 'bytes': '13218561'}, {'name': 'JavaScript', 'bytes': '55772'}, {'name': 'PLSQL', 'bytes': '6665'}, {'name': 'Protocol Buffer', 'bytes': '19818'}, {'name': 'Shell', 'bytes': '42289'}]}
'use strict'; var q = require('q'), os = require('os'), fs = require('fs'), _ = require('lodash'), path = require('path'), steps = require('../steps'), db = require('../utils/mongo'), output = require('../utils/output'), logger = require('../utils/logger'), inquirer = require('inquirer'), guid = require('../utils/guid'); module.exports = function(){ var questions = [{ type: 'list', name: 'start', message: 'Do you want to continue?', choices: ['Yes', 'No'] }], validate = require('../validate'); logger.statement('Automated Grasshopper setup. A fresh Grasshopper application will be created in this directory.\n' + 'To ensure that this process goes smoothly please review the prerequisites: https://github.com/Solid-Interactive/grasshopper-cli '); inquirer.prompt(questions, function( answers ) { var appName = process.cwd().substr((process.cwd().lastIndexOf(path.sep) + 1), (process.cwd().length - process.cwd().lastIndexOf(path.sep))), appId = appName.toLowerCase().replace(/ /g,''), config = { project: { home: process.cwd(), name: appName, main: 'app/' + appId + '.js', installExpress: true }, admin: { buildDirectory : path.join('app', 'public', 'admin'), apiEndpoint : '', base : '/admin/' }, crypto: { secret: guid() }, assets: { default : 'local', tmpdir : path.join(process.cwd(), 'tmp'), engines: { local : { path : path.join(process.cwd(), 'app', 'public', 'assets'), urlbase : 'http://locahost:3000' } } }, logger: { adapters: [{ type: 'console', application: appName, machine: os.hostname() }] }, identities: {}, db: db.buildConfig('mongodb://localhost/' + appId) }; if(process.platform === 'win32'){ config.admin.buildDirectory = config.admin.buildDirectory.replace(/\\/g,'\\\\'); config.assets.tmpdir = config.assets.tmpdir.replace(/\\/g,'\\\\'); } if(answers.start === 'Yes'){ writePackageJson(config) .then(writeAdminConfig) .then(validate.hasPackageFile) .then(steps.scaffolding) .then(steps.npms) .then(writeConfig) .then(installAdmin) .then(db.createSampleData) .then(function(results){ output.setupCompleted(); }) .then(startApp) .catch(function(err){ logger.error(''); logger.error('Setup failed!'); logger.error('Reason: ' + err.message); }); } else { logger.notice(''); logger.notice('Quit without installing.'); } }); }; function writePackageJson(config){ var tpl = _.template( fs.readFileSync(path.join(__dirname, '../../templates/package.tpl'), 'utf-8')), output = tpl(config), deferred = q.defer(); fs.writeFile(path.join(config.project.home, 'package.json'), output, 'utf-8', function(err){ if(err){ throw err; } deferred.resolve(config); }); return deferred.promise; } function writeConfig(config){ var tpl = _.template( fs.readFileSync(path.join(__dirname, '../../templates/core.tpl'), 'utf-8')), output = tpl(config), deferred = q.defer(); fs.writeFile(path.join(config.project.home, 'grasshopper-config.json'), output, 'utf-8', function(err){ if(err){ throw err; } deferred.resolve(config); }); return deferred.promise; } function writeAdminConfig(config){ var tpl = _.template( fs.readFileSync(path.join(__dirname, '../../templates/admin.tpl'), 'utf-8')), output = tpl(config), deferred = q.defer(); fs.writeFile(path.join(config.project.home, 'gha.json'), output, 'utf-8', function(err){ if(err){ throw err; } deferred.resolve(config); }); return deferred.promise; } function installAdmin(config){ var exec = require('child_process').exec, cmd = path.join(config.project.home, './node_modules/.bin/grasshopper build'), child = exec(cmd, function(err, stdout, stderr){ if(err) { console.log('exec error: ' + err); } }), progress = output.progress({label: 'Building grasshopper-admin. Please wait, this can take a few minutes.'}), deferred = q.defer(); logger.trace(''); logger.trace('RUNNING: ' + cmd); progress.start(); child.on('error', function(err){ deferred.reject(err); }); child.on('close', function(code){ if(code === 0){ progress.complete(); deferred.resolve(config); } else { deferred.reject(new Error(code)); } }); return deferred.promise; } function startApp(){ var exec = require('child_process').exec, cmd = 'node app', child = exec(cmd), deferred = q.defer(); logger.trace(''); logger.trace('RUNNING: ' + cmd); logger.trace('Browse to your site at: http://localhost:3000'); logger.trace('Get to the admin at: http://localhost:3000/admin\n' + 'Credentials are: admin / TestPassword (remember to change)'); child.on('error', function(err){ deferred.reject(err); }); child.on('close', function(code){ if(code === 0){ deferred.resolve(); } else { deferred.reject(new Error(code)); } }); child.stdout.pipe(process.stdout); child.stderr.pipe(process.stderr); return deferred.promise; }
{'content_hash': '12c928545aa84233b6d7b196ac129205', 'timestamp': '', 'source': 'github', 'line_count': 207, 'max_line_length': 148, 'avg_line_length': 31.207729468599034, 'alnum_prop': 0.4934984520123839, 'repo_name': 'Solid-Interactive/grasshopper-cli', 'id': 'f2992fb030315117039794e1b539656fc6b221ac', 'size': '6460', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/commands/fly.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '758'}, {'name': 'HTML', 'bytes': '552'}, {'name': 'JavaScript', 'bytes': '57655'}, {'name': 'Smarty', 'bytes': '1150'}]}
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Concepts</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../index.html" title="Chapter&#160;1.&#160;Boost.Numeric.Odeint"> <link rel="up" href="../index.html" title="Chapter&#160;1.&#160;Boost.Numeric.Odeint"> <link rel="prev" href="odeint_in_detail/binding_member_functions.html" title="Binding member functions"> <link rel="next" href="concepts/system.html" title="System"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../logo.jpg"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="odeint_in_detail/binding_member_functions.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="concepts/system.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h2 class="title" style="clear: both"> <a name="boost_numeric_odeint.concepts"></a><a class="link" href="concepts.html" title="Concepts">Concepts</a> </h2></div></div></div> <div class="toc"><dl class="toc"> <dt><span class="section"><a href="concepts/system.html">System</a></span></dt> <dt><span class="section"><a href="concepts/second_order_system.html">Second Order System</a></span></dt> <dt><span class="section"><a href="concepts/symplectic_system.html">Symplectic System</a></span></dt> <dt><span class="section"><a href="concepts/simple_symplectic_system.html">Simple Symplectic System</a></span></dt> <dt><span class="section"><a href="concepts/implicit_system.html">Implicit System</a></span></dt> <dt><span class="section"><a href="concepts/stepper.html">Stepper</a></span></dt> <dt><span class="section"><a href="concepts/error_stepper.html">Error Stepper</a></span></dt> <dt><span class="section"><a href="concepts/controlled_stepper.html">Controlled Stepper</a></span></dt> <dt><span class="section"><a href="concepts/dense_output_stepper.html">Dense Output Stepper</a></span></dt> <dt><span class="section"><a href="concepts/state_algebra_operations.html">State Algebra Operations</a></span></dt> <dt><span class="section"><a href="concepts/state_wrapper.html">State Wrapper</a></span></dt> </dl></div> <a name="odeint.concepts"></a> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2009-2012 Karsten Ahnert and Mario Mulansky<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="odeint_in_detail/binding_member_functions.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="concepts/system.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{'content_hash': '91958133d01b0efcdd043f9b1c190afd', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 460, 'avg_line_length': 64.70769230769231, 'alnum_prop': 0.6440798858773181, 'repo_name': 'ycsoft/FatCat-Server', 'id': 'be7772ffe0d0bcf115419a54f84bd8f15c9ffa1e', 'size': '4206', 'binary': False, 'copies': '19', 'ref': 'refs/heads/master', 'path': 'LIBS/boost_1_58_0/libs/numeric/odeint/doc/html/boost_numeric_odeint/concepts.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '195345'}, {'name': 'Batchfile', 'bytes': '32367'}, {'name': 'C', 'bytes': '9529739'}, {'name': 'C#', 'bytes': '41850'}, {'name': 'C++', 'bytes': '175536080'}, {'name': 'CMake', 'bytes': '14812'}, {'name': 'CSS', 'bytes': '282447'}, {'name': 'Cuda', 'bytes': '26521'}, {'name': 'FORTRAN', 'bytes': '1856'}, {'name': 'Groff', 'bytes': '6163'}, {'name': 'HTML', 'bytes': '148956564'}, {'name': 'JavaScript', 'bytes': '174868'}, {'name': 'Lex', 'bytes': '1290'}, {'name': 'Makefile', 'bytes': '1045258'}, {'name': 'Max', 'bytes': '37424'}, {'name': 'Objective-C', 'bytes': '34644'}, {'name': 'Objective-C++', 'bytes': '246'}, {'name': 'PHP', 'bytes': '60249'}, {'name': 'Perl', 'bytes': '37297'}, {'name': 'Perl6', 'bytes': '2130'}, {'name': 'Python', 'bytes': '1717781'}, {'name': 'QML', 'bytes': '613'}, {'name': 'QMake', 'bytes': '9450'}, {'name': 'Rebol', 'bytes': '372'}, {'name': 'Shell', 'bytes': '372652'}, {'name': 'Tcl', 'bytes': '1205'}, {'name': 'TeX', 'bytes': '13819'}, {'name': 'XSLT', 'bytes': '564356'}, {'name': 'Yacc', 'bytes': '19612'}]}