repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
S-ido/XChange
xchange-coindeal/src/main/java/org/knowm/xchange/coindeal/service/CoindealMarketDataServiceRaw.java
package org.knowm.xchange.coindeal.service; import java.io.IOException; import org.knowm.xchange.Exchange; import org.knowm.xchange.coindeal.Coindeal; import org.knowm.xchange.coindeal.CoindealAdapters; import org.knowm.xchange.coindeal.CoindealErrorAdapter; import org.knowm.xchange.coindeal.dto.CoindealException; import org.knowm.xchange.coindeal.dto.marketdata.CoindealOrderBook; import org.knowm.xchange.currency.CurrencyPair; import si.mazi.rescu.RestProxyFactory; public class CoindealMarketDataServiceRaw extends CoindealBaseService { private final Coindeal coindeal; public CoindealMarketDataServiceRaw(Exchange exchange) { super(exchange); this.coindeal = RestProxyFactory.createProxy( Coindeal.class, exchange.getExchangeSpecification().getSslUri(), getClientConfig()); } public CoindealOrderBook getCoindealOrderbook(CurrencyPair currencyPair) throws IOException { try { return coindeal.getOrderBook(CoindealAdapters.adaptCurrencyPairToString(currencyPair)); } catch (CoindealException e) { throw CoindealErrorAdapter.adapt(e); } } }
eirik1502/sol_champ
sol_engine/src/main/java/sol_engine/utils/reflection_utils/ClassUtils.java
package sol_engine.utils.reflection_utils; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; public class ClassUtils { @SuppressWarnings("unchecked") public static <T> T instantiateNoargs(Class<T> clazz) { try { Constructor<?>[] constructors = clazz.getConstructors(); boolean hasNoArgConstructor = Arrays.stream(constructors) .anyMatch(constructor -> constructor.getParameterCount() == 0); if (hasNoArgConstructor) { return clazz.getConstructor().newInstance(); } // handle potential vararg constructor (this is not registered as no-arg, in kotlin at least) Constructor<?> singleArrayArgConstructor = Arrays.stream(constructors) .filter(constructor -> constructor.getParameterCount() == 1) .filter(constructor -> constructor.getParameterTypes()[0].isArray()) .findFirst().orElse(null); if (singleArrayArgConstructor != null) { Class<?> arrayType = singleArrayArgConstructor.getParameterTypes()[0]; Object emptyArray = Array.newInstance(arrayType.getComponentType(), 0); return (T) singleArrayArgConstructor.newInstance(emptyArray); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } System.err.println("Failed to instanciate class: " + clazz.getSimpleName()); return null; } public static <T> T instanciateNoargOf(String classPath, Class<T> of) { Class<? extends T> classOf = toClassOf(classPath, of); if (classOf == null) return null; return instantiateNoargs(classOf); } public static Object instantiateNoargs(String classPath) { Class<?> genericClass = toClass(classPath); if (genericClass == null) return null; return instantiateNoargs(genericClass); } public static Class<?> toClass(String classPath) { try { return Class.forName(classPath); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } public static <T> Class<? extends T> toClassOf(String classPath, Class<T> as) { try { return toClass(classPath).asSubclass(as); } catch (ClassCastException | NullPointerException e) { e.printStackTrace(); return null; } } }
cheesama/nlflow
nlu_flow/preprocessor/spell_corrector.py
import os, sys
abisfadone/storyteller-ui
src/lib/components/TextInput.js
<filename>src/lib/components/TextInput.js import clsx from 'clsx'; import React from 'react'; const TextInput = (props) => ( <div > <div className={`textinput__container textinput__container__${props.size}`}> <input disabled={props.disabled} className={ clsx( 'textinput', `textinput${props.type}`, `${(props.error && 'textinput-error') || (props.success && 'textinput-success')}`, `textinput__${props.size}`, { textinput__icon__text: props.children } ) } id={props.id} type={props.type} name={props.name} value={props.value} onChange={(e) => props.onChangeHandler(e)} /> <label className={ clsx('label', { label__active: props.value }, { label__icon: props.children }, { label__success: props.success }, { label__error: props.error })} htmlFor={props.id}>{props.name} </label> {props.children && <div onClick={props.handleSearch} className='textinput__icon'>{props.children}</div>} </div> <div className='textinput__message'> {props.caption && <p className={'textinput__caption'}>{props.caption}</p>} {props.success && <p className={'textinput__message-success'}>{props.successMessage}</p>} {props.error && <p className={'textinput__message-error'}>{props.errorMessage}</p>} </div> </div> ); export default TextInput;
patil215/v8
fuzzer_output/interesting/sample_1554115038545.js
function main() { const v4 = [13.37,13.37,13.37,"Z6HVy*PuQW"]; const v6 = [1337,1337]; const v7 = []; const v8 = {charAt:13.37,isFinite:1337,b:Map,toPrimitive:v6}; const v9 = {getUint32:"Z6HVy*PuQW"}; let v10 = 2147483647; let v23 = "undefined"; const v29 = [-536870912]; const v31 = [1337]; const v32 = [v31]; const v37 = [13.37,13.37,13.37,13.37]; const v39 = [1337]; const v40 = [v39]; const v41 = {max:Function,setPrototypeOf:10}; const v42 = {exec:v39}; let v43 = "undefined"; const v48 = [13.37,13.37,13.37,13.37]; const v50 = [1337]; const v52 = [Error]; const v53 = {max:Function,setPrototypeOf:10}; const v54 = {exec:v50}; let v55 = "undefined"; const v59 = Function && 13.37; const v67 = [Function]; const v69 = "undefined" >> "undefined"; const v70 = v67.__proto__; const v78 = [13.37,13.37,13.37,13.37]; const v80 = [1337]; const v81 = [v80]; const v82 = {max:Function,setPrototypeOf:10}; const v83 = {exec:v80}; let v85 = v59; let v86 = "undefined"; const v91 = [13.37,13.37,13.37,13.37]; const v93 = [1337]; const v94 = [v93]; const v95 = {max:Function,setPrototypeOf:10}; v86 = Function; for (const v96 in v59) { const v97 = v78[9]; } Function.length = 2; Function[10] = "undefined"; Function.length = 2; Function[10] = "undefined"; const v174 = [13.37,13.37,13.37,13.37]; const v176 = [1337]; const v177 = [3547325953,"object",v176,"object"]; const v178 = {localeCompare:v176}; const v179 = {NEGATIVE_INFINITY:v178,trunc:Math,concat:Math,call:v177,freeze:v176,split:13.37,codePointAt:Math,imul:v176,delete:13.37}; let v180 = Math; for (let v188 = 0; v188 < 5; v188++) { const v189 = 0 & v188; } const v190 = [13.37,13.37,13.37,13.37]; const v192 = [1337,1337,1337]; const v193 = [Atomics,"function",v192,13.37]; const v194 = {toLowerCase:-65535,getPrototypeOf:13.37,flags:-65535,leftContext:Atomics,setUint8:"function"}; const v195 = {getPrototypeOf:v193,max:v194,flatMap:v194,asyncIterator:v190,leftContext:v193,pow:v192,input:v194,search:v194,toLowerCase:v193}; let v196 = v190; const v198 = [65535]; function v199(v200,v201,v202,v203) { let v205 = 0; const v208 = {max:Function,setPrototypeOf:10}; const v210 = [1337]; const v211 = [v210]; const v212 = 1337 | v210; const v214 = Symbol.iterator; const v215 = v211[v214]; const v220 = [1337]; function v223(v224,v225,v226,v227,v228) { const v230 = [13.37,13.37,13.37,13.37]; const v235 = new Int8Array(40654); delete Function[40654]; const v236 = [1337]; const v237 = [v236]; function v238(v239,v240,v241,v242) { 'use strict' let v243 = Function; v243 = v237; return v230; } for (let v248 = 0; v248 < 100; v248++) { const v249 = v238(13.37,v230,13.37,1337,v237); } const v250 = []; const v252 = [13.37,13.37,13.37,13.37]; let v254 = 0; const v255 = v254 + 1; for (let v259 = 0; v259 < 5; v259++) { const v261 = [13.37,13.37,13.37,13.37]; } return v220; } function v262(v263,v264,v265,v266,v267) { const v268 = v223(v264,v266,9007199254740991,9007199254740991); return v205; } for (let v273 = 0; v273 < 100; v273++) { const v274 = v262("undefined",1337,13.37,Math); } return v198; } const v280 = [1337]; for (let v284 = 0; v284 < 100; v284++) { const v285 = v199(10,Function,1337,v280,Function); } v192.defineProperties = Function; const v286 = v199(1337,Atomics,v195,v179); const v295 = [1337]; for (const v296 in v295) { } const v314 = [13.37,13.37,13.37,13.37]; const v316 = [1337]; const v317 = [Function]; const v318 = {max:Function,setPrototypeOf:10}; const v319 = {exec:v316}; let v320 = "undefined"; for (let v324 = 0; v324 < 5; v324++) { const v326 = [Function]; const v327 = [v318]; Function[-3085604502] = 10; for (const v333 in Function) { const v334 = 0 > v333; } } with (v29) { let v376 = -2147483649; v376 = v376; v23 = v32; } let v393 = 0; } %NeverOptimizeFunction(main); main();
JoneXia/mate_tools
petkit_share_lib/src/com/petkit/android/widget/InterceptViewPager.java
package com.petkit.android.widget; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.ViewParent; /** * * 自定义Viewpager,有两个功能: * 1,可禁止翻页,enable为true时开启 * 2,完美解决双层嵌套,不支持三层及以上的嵌套 * * @author Jone * */ public class InterceptViewPager extends ViewPager { private boolean enabled; public InterceptViewPager(Context context, AttributeSet attrs) { super(context, attrs); this.enabled = true; } @Override public boolean onTouchEvent(MotionEvent event) { if (this.enabled) { return super.onTouchEvent(event); } return false; } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (this.enabled) { ViewParent viewParent = getParent(); while(viewParent != null){ if(viewParent instanceof ViewPager){ break; }else{ viewParent = viewParent.getParent(); } } if(viewParent != null){ if (event.getAction() == MotionEvent.ACTION_DOWN) { viewParent.requestDisallowInterceptTouchEvent(true); } if (event.getAction() == MotionEvent.ACTION_MOVE) { viewParent.requestDisallowInterceptTouchEvent(true); } if (event.getAction() == MotionEvent.ACTION_UP) { viewParent.requestDisallowInterceptTouchEvent(false); } } return super.onInterceptTouchEvent(event); } return false; } public void setPagingEnabled(boolean enabled) { this.enabled = enabled; } }
szymek22/AxonFramework
core/src/main/java/org/axonframework/eventsourcing/eventstore/EventStorageEngine.java
/* * Copyright (c) 2010-2017. Axon Framework * * 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.axonframework.eventsourcing.eventstore; import org.axonframework.eventhandling.EventMessage; import org.axonframework.eventhandling.TrackedEventMessage; import org.axonframework.eventsourcing.DomainEventMessage; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import static java.util.Arrays.asList; /** * Provides a mechanism to append as well as retrieve events from an underlying storage like a database. An event * storage engine can also be used to store and fetch aggregate snapshot events. * * @author <NAME> */ public interface EventStorageEngine { /** * Append one or more events to the event storage. Events will be appended in the order that they are offered in. * <p> * Note that all events should have a unique event identifier. When storing {@link DomainEventMessage domain events} * events should also have a unique combination of aggregate id and sequence number. * <p> * By default this method creates a list of the offered events and then invokes {@link #appendEvents(List)}. * * @param events Events to append to the event storage */ default void appendEvents(EventMessage<?>... events) { appendEvents(asList(events)); } /** * Append a list of events to the event storage. Events will be appended in the order that they are offered in. * <p> * Note that all events should have a unique event identifier. When storing {@link DomainEventMessage domain events} * events should also have a unique combination of aggregate id and sequence number. * * @param events Events to append to the event storage */ void appendEvents(List<? extends EventMessage<?>> events); /** * Store an event that contains a snapshot of an aggregate. If the event storage already contains a snapshot for the * same aggregate, then it will be replaced with the given snapshot. * * @param snapshot The snapshot event of the aggregate that is to be stored */ void storeSnapshot(DomainEventMessage<?> snapshot); /** * Open an event stream containing all events stored since given tracking token. The returned stream is comprised of * events from aggregates as well as other application events. Pass a {@code trackingToken} of {@code null} to open * a stream containing all available events. * <p> * If the value of the given {@code mayBlock} is {@code true} the returned stream is allowed to block while waiting * for new event messages if the end of the stream is reached. * * @param trackingToken Object describing the global index of the last processed event or {@code null} to create a * stream of all events in the store * @param mayBlock If {@code true} the storage engine may optionally choose to block to wait for new event * messages if the end of the stream is reached. * @return A stream containing all tracked event messages stored since the given tracking token */ Stream<? extends TrackedEventMessage<?>> readEvents(TrackingToken trackingToken, boolean mayBlock); /** * Get a {@link DomainEventStream} containing all events published by the aggregate with given {@code * aggregateIdentifier}. By default calling this method is shorthand for an invocation of * {@link #readEvents(String, long)} with a sequence number of 0. * <p> * The returned stream is finite, i.e. it should not block to wait for further events if the end of the event stream * of the aggregate is reached. * * @param aggregateIdentifier The identifier of the aggregate to return an event stream for * @return A non-blocking DomainEventStream of the given aggregate */ default DomainEventStream readEvents(String aggregateIdentifier) { return readEvents(aggregateIdentifier, 0L); } /** * Get a {@link DomainEventStream} containing all events published by the aggregate with given {@code * aggregateIdentifier} starting with the first event having a sequence number that is equal or larger than the * given {@code firstSequenceNumber}. * <p> * The returned stream is finite, i.e. it should not block to wait for further * events if the end of the event stream of the aggregate is reached. * * @param aggregateIdentifier The identifier of the aggregate * @param firstSequenceNumber The expected sequence number of the first event in the returned stream * @return A non-blocking DomainEventStream of the given aggregate */ DomainEventStream readEvents(String aggregateIdentifier, long firstSequenceNumber); /** * Try to load a snapshot event of the aggregate with given {@code aggregateIdentifier}. If the storage engine has * no snapshot event of the aggregate, an empty Optional is returned. * * @param aggregateIdentifier The identifier of the aggregate * @return An optional with a snapshot of the aggregate */ Optional<DomainEventMessage<?>> readSnapshot(String aggregateIdentifier); /** * Returns the last known sequence number for the given {@code aggregateIdentifier}. * <p> * While it's recommended to use the sequence numbers from the {@link DomainEventStream}, there are cases where * knowing the sequence number is required, without having read the actual events. In such case, this method is a * viable alternative. * * @param aggregateIdentifier The identifier to find the last sequence number for * @return an optional with the highest sequence number, or an empty optional if the aggregate identifier wasn't * found */ default Optional<Long> lastSequenceNumberFor(String aggregateIdentifier) { return readEvents(aggregateIdentifier).asStream().map(DomainEventMessage::getSequenceNumber).max(Long::compareTo); } }
1and1/camunda-bpm-platform
webapps/camunda-webapp/webapp/src/main/webapp/assets/vendor/camunda-common/directives/requestAware.js
ngDefine('camunda.common.directives', [ 'angular', 'jquery' ], function(module, angular, $) { var requestAwareDirective = [ function() { return { require: 'form', link: function(scope, element, attrs, ngForm) { function setFormValidity(valid) { ngForm.$setValidity("request", valid); } function setFormFieldsEnabled(enabled) { var inputs = $(":input", element); if (!enabled) { inputs.attr("disabled", "disabled"); } else { inputs.removeAttr("disabled"); } } function setFormEnabled(enabled) { setFormFieldsEnabled(enabled); setFormValidity(enabled); } ngForm.$load = { start: function() { scope.$broadcast('formLoadStarted'); }, finish: function() { scope.$broadcast('formLoadFinished'); } }; scope.$on('formLoadStarted', function() { setFormEnabled(false); }); scope.$on('formLoadFinished', function() { setFormEnabled(true); }); if (attrs.requestAware != 'manual') { scope.$on('requestStarted', function() { ngForm.$load.start(); }); scope.$on('requestFinished', function() { ngForm.$load.finish(); }); } } }; }]; module.directive('requestAware', requestAwareDirective); });
django-doctor/lite-frontend
ui_tests/exporter/pages/mod_clearances/ExhibitionClearanceGood.py
<filename>ui_tests/exporter/pages/mod_clearances/ExhibitionClearanceGood.py from ui_tests.exporter.pages.BasePage import BasePage class ExhibitionClearanceGoodPage(BasePage): GOOD_TYPE_PARTIAL_ID = "item_type-" def click_good_type(self, type): self.driver.find_element_by_id(self.GOOD_TYPE_PARTIAL_ID + type).click()
ffinfo/cromwell
engine/src/test/scala/cromwell/util/docker/DockerHashSpec.scala
package cromwell.util.docker import org.scalatest.prop.TableDrivenPropertyChecks._ import org.scalatest.prop.Tables.Table import org.scalatest.{FlatSpec, Matchers} class DockerHashSpec extends FlatSpec with Matchers { behavior of "DockerHash" it should "parse valid digests" in { val digests = Table( ("digest", "hashType", "hashLength"), ("12345678", "unknown", 8), (":12345678", "", 8), ("type:12345678", "type", 8), ("type:11112222333344445555666677778888", "type", 32), ("type:1111222233334444555566667777888899990000aaaabbbbccccddddeeeeffff", "type", 64)) forAll(digests) { (digest, hashType, hashLength) => val dockerHash = DockerHash.fromDigest(digest).get dockerHash.hashType should be(hashType) dockerHash.hashString should have length hashLength } } it should "not parse invalid hash strings" in { val invalidHashStrings = Table( ("hashString", "exceptionMessage"), ("", "unexpected hash length: 0"), ("1", "hexBinary needs to be even-length: 1, unexpected hash length: 1"), ("hashhash", "contains illegal character for hexBinary: hashhash"), ("123456", "unexpected hash length: 6"), ("1234567890", "unexpected hash length: 10")) forAll(invalidHashStrings) { (hashString, exceptionMessage) => val exception = DockerHash.fromHash("type", hashString).failed.get exception shouldBe an[IllegalArgumentException] exception.getMessage should be(s"hashString '$hashString' is not valid: $exceptionMessage") } } it should "create hash digests" in { DockerHash("type", "12345678").digest should be("type:12345678") } it should "not rehash an empty hash" in { val emptyHash = Vector.empty[DockerHash] val exception = DockerHash.fromSeq("collection", emptyHash).failed.get exception shouldBe an[IllegalArgumentException] exception.getMessage should be("docker hashes is empty") } it should "rehash a sequence of hashes" in { val hash1 = DockerHash.fromHash("single", "12345678") val hash2 = DockerHash.fromHash("single", "87654321") val hashes = Vector(hash1, hash2) val rehash = DockerHash.fromTries("collection", hashes).get rehash.hashType should be("collection-single-md5") rehash.hashString should be("461595e4bdb090ce41e7818287954d86") } it should "not rehash a sequence of different hash types" in { val hash1 = DockerHash.fromHash("hash1", "12345678") val hash2 = DockerHash.fromHash("hash2", "12345678") val hashes = Vector(hash1, hash2) val exception = DockerHash.fromTries("collection", hashes).failed.get exception shouldBe an[IllegalArgumentException] exception.getMessage should be("found more than one docker hash type: Vector(hash1, hash2)") } }
bparazin/skyportal
static/js/plotjs/foldphase.js
/* eslint-disable */ if (numphases.active == 1) { /* two phases */ p.x_range.end = 2.01; } else { p.x_range.end = 1.01; } const period = parseFloat(textinput.value); for (let i = 0; i < n_labels; i++) { const folda = eval(`folda${i}`).data_source; const foldaerr = eval(`foldaerr${i}`).data_source; const foldb = eval(`foldb${i}`).data_source; const foldberr = eval(`foldberr${i}`).data_source; const mjd = folda.data.mjd; for (let m = 0; m < mjd.length; m++) { folda.data.mjd_folda[m] = (mjd[m] % period) / period; foldaerr.data.xs[m] = [folda.data.mjd_folda[m], folda.data.mjd_folda[m]]; foldb.data.mjd_foldb[m] = folda.data.mjd_folda[m] + 1; foldberr.data.xs[m] = [foldb.data.mjd_foldb[m], foldb.data.mjd_foldb[m]]; } folda.change.emit(); foldaerr.change.emit(); foldb.change.emit(); foldberr.change.emit(); }
manveru/ver
lib/ver/vendor/levenshtein.rb
module VER # Levenshtein distance algorithm implementation for Ruby, with UTF-8 support. # # The Levenshtein distance is a measure of how similar two strings s and t # are, calculated as the number of deletions/insertions/substitutions needed # to transform s into t. The greater the distance, the more the strings # differ. # # The Levenshtein distance is also sometimes referred to as the # easier-to-pronounce-and-spell 'edit distance'. # # The original author is <NAME> (<EMAIL>) # Modified by <NAME> (<EMAIL>) # # The original implementation is part of the 'english' gem, distributed under # the Ruby license. module Levenshtein module_function # Calculate the Levenshtein distance between two strings +str1+ and +str2+. # +str1+ and +str2+ will be encoded as UTF8. # # Be aware that this algorithm doesn't perform normalization. # If there is a possibility of different normalized forms being used, # normalization should be performed beforehand. def distance(str1, str2) s = str1.encode(Encoding::UTF_8).unpack('U*') t = str2.encode(Encoding::UTF_8).unpack('U*') n = s.length m = t.length return m if n == 0 return n if m == 0 d = (0..m).to_a x = nil (0...n).each do |i| e = i + 1 (0...m).each do |j| cost = s[i] == t[j] ? 0 : 1 x = [ d[j + 1] + 1, # insertion e + 1, # deletion d[j] + cost # substitution ].min d[j] = e e = x end d[m] = x end x end end end
pyracanda/runtime
src/coreclr/pal/tests/palsuite/c_runtime/_wcsnicmp/test1/test1.cpp
<gh_stars>1000+ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================================ ** ** Source: test1.c ** ** Purpose: Take two wide strings and compare them, giving different lengths. ** Comparing str1 and str2 with str2 length, should return <0 ** Comparing str2 and str1 with str2 length, should return >0 ** Comparing str1 and str2 with str1 lenght, should return 0 ** Bring in str3, which has a capital, but this function is doing a lower ** case compare. Just ensure that two strings which differ only by capitals ** return 0. ** ** **==========================================================================*/ #include <palsuite.h> /* * Notes: uses wcslen */ PALTEST(c_runtime__wcsnicmp_test1_paltest_wcsnicmp_test1, "c_runtime/_wcsnicmp/test1/paltest_wcsnicmp_test1") { WCHAR str1[] = {'f','o','o',0}; WCHAR str2[] = {'f','o','o','x',0}; WCHAR str3[] = {'f','O','o',0}; WCHAR str4[] = {'A','B','C','D','E',0}; WCHAR str5[] = {'A','B','C','D',']',0}; WCHAR str6[] = {'a','b','c','d','e',0}; WCHAR str7[] = {'a','b','c','d',']',0}; char cstr1[] = "foo"; char cstr2[] = "foox"; char cstr3[] = "fOo"; char cstr4[] = "ABCDE"; char cstr5[] = "ABCD]"; char cstr6[] = "abcde"; char cstr7[] = "abcd]"; /* * Initialize the PAL and return FAIL if this fails */ if (0 != (PAL_Initialize(argc, argv))) { return FAIL; } if (_wcsnicmp(str1, str2, wcslen(str2)) >= 0) { Fail ("ERROR: wcsnicmp(\"%s\", \"%s\", %d) returned >= 0\n", cstr1, cstr2, wcslen(str2)); } if (_wcsnicmp(str2, str1, wcslen(str2)) <= 0) { Fail ("ERROR: wcsnicmp(\"%s\", \"%s\", %d) returned <= 0\n", cstr2, cstr1, wcslen(str2)); } if (_wcsnicmp(str1, str2, wcslen(str1)) != 0) { Fail ("ERROR: wcsnicmp(\"%s\", \"%s\", %d) returned != 0\n", cstr1, cstr2, wcslen(str1)); } if (_wcsnicmp(str1, str3, wcslen(str1)) != 0) { Fail ("ERROR: wcsnicmp(\"%s\", \"%s\", %d) returned != 0\n", cstr1, cstr3, wcslen(str1)); } /* new testing */ /* str4 should be greater than str5 */ if (_wcsnicmp(str4, str5, wcslen(str4)) <= 0) { Fail ("ERROR: _wcsnicmp(\"%s\", \"%s\", %d) returned >= 0\n", cstr4, cstr5, wcslen(str4)); } /* str6 should be greater than str7 */ if (_wcsnicmp(str6, str7, wcslen(str6)) <= 0) { Fail ("ERROR: _wcsnicmp(\"%s\", \"%s\", %d) returned <= 0\n", cstr6, cstr7, wcslen(str6)); } PAL_Terminate(); return PASS; }
mgusmano/ext-elements
packages/ext-elements-all/dist/ext-sparklinebox.component.js
import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose"; import Ext_sparkline_Box from './Ext/sparkline/Box.js'; import HTMLParsedElement from './HTMLParsedElement.js'; var ExtSparklinebox = /*#__PURE__*/ function (_Ext_sparkline_Box) { _inheritsLoose(ExtSparklinebox, _Ext_sparkline_Box); function ExtSparklinebox() { var _this; _this = _Ext_sparkline_Box.call(this, [], []) || this; _this.xtype = 'sparklinebox'; return _this; } return ExtSparklinebox; }(Ext_sparkline_Box); export { ExtSparklinebox as default }; window.customElements.define('ext-sparklinebox', HTMLParsedElement.withParsedCallback(ExtSparklinebox));
tony56a/prop-unlimiter
docs/search/namespaces_2.js
<reponame>tony56a/prop-unlimiter var searchData= [ ['manager',['Manager',['../namespace_prop_unlimiter_1_1_manager.html',1,'PropUnlimiter']]], ['patches',['Patches',['../namespace_prop_unlimiter_1_1_patches.html',1,'PropUnlimiter']]], ['propunlimiter',['PropUnlimiter',['../namespace_prop_unlimiter.html',1,'']]], ['utils',['Utils',['../namespace_prop_unlimiter_1_1_utils.html',1,'PropUnlimiter']]] ];
konsserto/konsserto
dist/node_modules/konsserto/lib/src/Konsserto/Component/Form/FormField.js
<filename>dist/node_modules/konsserto/lib/src/Konsserto/Component/Form/FormField.js<gh_stars>1-10 /* * This file is part of the Konsserto package. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ var FormField, formWidgets, forms, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; forms = use('ks-forms'); formWidgets = forms.widgets; FormField = (function() { function FormField(name, formName, type, options, predata) { this.name = name; this.formName = formName; this.type = type; this.options = options; if (predata == null) { predata = {}; } this.addDefault = __bind(this.addDefault, this); this.submit = false; this.csrf = false; if (predata[this.name] != null) { this.options['value'] = predata[this.name]; } if (type === 'submit') { this.setSubmit(); } if (this.name === '_csrf') { this.setCsrf(); } this.setHTMLfields(); } FormField.prototype.setSubmit = function() { this.submit = true; this.options['widget'] = formWidgets.submit(this.options); return this.options['value'] = this.name; }; FormField.prototype.setCsrf = function() { this.csrf = true; return this.getFullname = function() { return this.name; }; }; FormField.prototype.handleSubmit = function() { var value; if (this.isSubmit()) { value = this.getCompiled()['value']; if (value !== '' && value !== void 0 && value !== null) { this.isClicked = (function(_this) { return function() { return true; }; })(this); } else { this.isClicked = (function(_this) { return function() { return false; }; })(this); } return this.getCompiled()['value'] = this.name; } }; FormField.prototype.isSubmit = function() { return this.submit; }; FormField.prototype.isCsrf = function() { return this.csrf; }; FormField.prototype.getId = function() { return this.formName + '_' + this.name; }; FormField.prototype.getFullname = function() { return this.formName + '[' + this.name + ']'; }; FormField.prototype.getShortname = function() { var m; m = this.name.match('\\[(.+)\\]'); if ((m != null) && m.length >= 2) { return m[1]; } return ''; }; FormField.prototype.setHTMLfields = function() { this.addDefault(this.options, 'id', this.getId()); this.addDefault(this.options, 'fullname', this.getFullname()); return this.addDefault(this.options, 'shortname', this.name); }; FormField.prototype.addDefault = function(object, field, value) { return object[field] != null ? object[field] : object[field] = value; }; FormField.prototype.getName = function() { return this.name; }; FormField.prototype.getType = function() { return this.type; }; FormField.prototype.getOptions = function() { return this.options; }; FormField.prototype.setCompiled = function(compiled) { this.compiled = compiled; return this; }; FormField.prototype.getCompiled = function() { return this.compiled; }; FormField.prototype.isClicked = function() { if (!this.isSubmit()) { throw new Error('You can\'t call isClicked on a non submit field'); } }; FormField.prototype.getData = function() { return this.compiled.data; }; return FormField; })(); module.exports = FormField;
navikt/fp-felles
felles/sikkerhet/src/test/java/no/nav/vedtak/sikkerhet/jaspic/TokenLocatorTest.java
package no.nav.vedtak.sikkerhet.jaspic; import static no.nav.vedtak.sikkerhet.Constants.ID_TOKEN_COOKIE_NAME; import static no.nav.vedtak.sikkerhet.Constants.REFRESH_TOKEN_COOKIE_NAME; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class TokenLocatorTest { @Mock private HttpServletRequest requestContext; private TokenLocator tokenLocator = new TokenLocator(); @Test void skal_finne_token_i_authorization_header() { when(requestContext.getHeader("Authorization")).thenReturn("Bearer eyJhbGciOiJS..."); assertThat(tokenLocator.getToken(requestContext).get().token()).isEqualTo("<KEY>..."); assertThat(tokenLocator.getToken(requestContext).get().fromCookie()).isFalse(); } @Test void skal_ikke_finne_token_når_token_ikke_finnes_i_authorization_header() { when(requestContext.getHeader("Authorization")).thenReturn(""); assertThat(tokenLocator.getToken(requestContext)).isNotPresent(); when(requestContext.getHeader("Authorization")).thenReturn(null); assertThat(tokenLocator.getToken(requestContext)).isNotPresent(); } @Test void skal_finne_id_token_i_cookie() { when(requestContext.getCookies()).thenReturn(new Cookie[] { new Cookie(ID_TOKEN_COOKIE_NAME, "eyJhbGciOiJS...") }); assertThat(tokenLocator.getToken(requestContext).get().token()).isEqualTo("<KEY>..."); assertThat(tokenLocator.getToken(requestContext).get().fromCookie()).isTrue(); } @Test void skal_ikke_finne_id_token_i_cookie_som_har_feil_navn() { when(requestContext.getCookies()).thenReturn(new Cookie[] { new Cookie("tull", "eyJhbGciOiJS...") }); assertThat(tokenLocator.getToken(requestContext)).isNotPresent(); } @Test void skal_finne_refresh_token_i_cookie() { when(requestContext.getCookies()).thenReturn(new Cookie[] { new Cookie(REFRESH_TOKEN_COOKIE_NAME, "123fas1-1234-a1r2") }); assertThat(tokenLocator.getRefreshToken(requestContext).get()).isEqualTo("123fas1-1234-a1r2"); } @Test void skal_ikke_finne_refreshtoken_i_cookie_som_har_feil_navn() { when(requestContext.getCookies()).thenReturn(new Cookie[] { new Cookie("tull", "123fas1-1234-a1r2") }); assertThat(tokenLocator.getRefreshToken(requestContext)).isNotPresent(); } }
ekibun/BangumiTinygrailPlugin
src/screens/user/zone/bangumi-list.js
/* * @Author: czy0729 * @Date: 2019-05-06 00:28:36 * @Last Modified by: czy0729 * @Last Modified time: 2021-01-30 22:51:05 */ import React from 'react' import { Loading, ListView, Flex, Touchable, Text, Iconfont, Heatmap } from '@components' import { SectionHeader, ItemBangumiList } from '@screens/_' import { _ } from '@stores' import { obc } from '@utils/decorators' import { keyExtractor } from '@utils/app' import { t } from '@utils/fetch' import { H_BG } from './store' const event = { id: '空间.跳转' } export default @obc class List extends React.Component { renderSectionHeader = ({ section: { title, count } }) => { const { $ } = this.context const { expand } = $.state return ( <Touchable style={this.styles.section} onPress={() => $.toggleSection(title)} > <SectionHeader style={this.styles.sectionHeader} type='title' size={15} right={ <Iconfont name={expand[title] ? 'down' : 'up'} color={_.colorIcon} size={16} /> } > {title}{' '} <Text type='sub' size={12} bold lineHeight={15}> {count}{' '} </Text> </SectionHeader> {title === '在看' && <Heatmap id='空间.展开分组' />} </Touchable> ) } ListFooterComponent = ($, navigation) => ( <Touchable style={[_.mt.md, _.mb.md]} onPress={() => { t('空间.跳转', { to: 'User' }) $.toUser(navigation) }} > <Text align='center'>查看TA的所有收藏</Text> <Heatmap id='空间.跳转' data={{ to: 'User', alias: '所有收藏' }} /> </Touchable> ) render() { const { $, navigation } = this.context if (!$.userCollections._loaded) { return <Loading /> } const { expand } = $.state const sections = [] $.userCollections.list.forEach(item => { sections.push({ title: item.status, count: item.count, data: [ { list: item.list } ] }) }) return ( <ListView contentContainerStyle={this.styles.contentContainerStyle} keyExtractor={keyExtractor} sections={sections} renderSectionHeader={this.renderSectionHeader} renderItem={({ item, section: { title } }) => { if (!expand[title]) { return null } return ( <Flex wrap='wrap' align='start'> {item.list .filter((item, index) => index < 15) .map(item => ( <ItemBangumiList key={item.id} navigation={navigation} subjectId={item.id} images={item.images} name={item.name_cn || item.name} event={event} /> ))} {title.includes('在看') && ( <Heatmap id='空间.跳转' data={{ to: 'Subject', alias: '条目' }} /> )} </Flex> ) }} animated showFooter={false} ListFooterComponent={() => this.ListFooterComponent($, navigation)} {...this.props} /> ) } get styles() { return memoStyles() } } const memoStyles = _.memoStyles(_ => ({ contentContainerStyle: { paddingHorizontal: _.wind - _._wind, minHeight: _.window.height + H_BG - _.tabBarHeight }, sectionHeader: { paddingHorizontal: _._wind, backgroundColor: _.colorPlain }, section: { backgroundColor: _.colorBg } }))
NickSmyr/ai-player-agents
A1 - Search and Games/fishing_game_core/game_tree.py
<gh_stars>0 # Game tree for Fishing Derby from copy import deepcopy import numpy as np from fishing_game_core.shared import OBS_TO_MOVES, ACT_TO_MOVES class State: def __init__(self, number_of_fish): # The current player's index - 0 means MAX and 1 means MIN. self.player = None # The player scores: {0: MAX_SCORE, 1: MIN_SCORE} self.player_scores = {} # The index of the caught fish for the two players in a dict. # The fish index -1 means that no fish has been caught. self.player_caught = {} # The positions of the two hooks, provided as (x,y) coordinate tuples. self.hook_positions = {} # The positions of the uncaught fishes, provided as (x,y) coordinate tuples. self.fish_positions = {} # The score values associated with each fish index. self.fish_scores = {} def set_hook_positions(self, player_pos): """ Set the hooks positions for each player :param hook_pos :return: """ p0 = player_pos[0], player_pos[1] p1 = player_pos[2], player_pos[3] self.hook_positions = {0: p0, 1: p1} def set_player(self, player): """ Set current player. :param player: either 0 or 1 :return: """ self.player = player def set_player_scores(self, score_p0, score_p1): """ Set current games scores for each player :param scores: :return: """ self.player_scores = {0: score_p0, 1: score_p1} def set_fish_scores(self, fish_scores): """ Set scores of fish :param fish_scores: :return: """ self.fish_scores = deepcopy(fish_scores) def set_caught(self, caught): """ Set currently caught fish for every player :param caught: tuple of either the fish_numbers or None when no fish has been caught :return: """ p0_caught = caught[0] if caught[0] is not None else -1 p1_caught = caught[1] if caught[1] is not None else -1 self.player_caught = {0: p0_caught, 1: p1_caught} def set_fish_positions(self, fish_number, pos): """ Set the position of the fish. :param fish_number: integer :param pos: tuple positions in x and y :return: """ self.fish_positions[fish_number] = pos def get_hook_positions(self): """ Return the hooks positions :return: dict of 2-tuples with (x, y) values of each player's hook """ return self.hook_positions def get_player(self): """ Return the current player's index :return: either 0 or 1 """ return self.player def get_player_scores(self): """ Returns the score for each player :return: """ return self.player_scores[0], self.player_scores[1] def get_fish_scores(self): """ Return scores of fish :return: """ return self.fish_scores def get_caught(self): """ Return the caught fish of each player :return: 2-tuple with the corresponding fish_number or None for each player """ p0 = self.player_caught[0] if p0 == -1: p0 = None p1 = self.player_caught[1] if p1 == -1: p1 = None return p0, p1 def get_fish_positions(self): """ Return dict of fish positions in current state :return: dict of fish_numbers -> 2-tuple with position (x, y) """ return self.fish_positions def __repr__(self): """ Return array visualization of the state. Meant for visualization on a debugger. :return: str """ return f"{self.data.tolist()}" def remove_fish(self, fish_number): """ Remove fish from state (because it is pulled in) :param fish_number: :return: """ del self.fish_positions[fish_number] def compute_caught_fish(state, current_fishes_on_rod): """ Infer caught fish tuple from the state :param state: a state instance :return: 2-tuple - caught fish for each player """ caught_fish = [None, None] pull_in_fishes = [None, None] hook_positions = state.get_hook_positions() fish_positions = state.get_fish_positions() for player_number in hook_positions: if current_fishes_on_rod[player_number] is not None: # A fish was already attached in the previous step fish_number = current_fishes_on_rod[player_number] if fish_positions[fish_number][1] >= 19: pull_in_fishes[player_number] = fish_number else: caught_fish[player_number] = fish_number else: # Player did not have a fish attached to rod for fish_number in fish_positions: if hook_positions[player_number] == fish_positions[fish_number]: # Pull fish in if it is on the surface if fish_positions[fish_number][1] >= 19: pull_in_fishes[player_number] = fish_number else: caught_fish[player_number] = fish_number break return caught_fish, pull_in_fishes class Node: def __init__(self, root=True, message=None, player=0): # A list of the child Nodes, found one level below in the game tree. # NOTE: this field has to be initialized by self.compute_and_get_children(). self.children = [] # The current state of the game. See the State class for more information. self.state = None # The parent Node in the game tree. self.parent = None # The action that led to this node in the game tree, represented as an int. # Can be transformed to a string (e.g. "left") using ACTION_TO_STR in shared.py. self.move = None # This field can be ignored for this assignment. self.probability = 1.0 if root: # Initialize the following fields: # self.depth (the depth level at the current node - 0 at the root) # self.player (the current player's index; MAX is 0 and MIN is 1) self.initialize_root(message, player) def add_child(self, state: State, move: int, depth: int = 0, observations=None, probability: float = 1.0): """ Add a new node as a child of current node :param State state: child's state :param int move: child's move :param int depth: depth of the child :param dict observations: observations of the game (the entire sequence of fish moves as a dict of lists: {0: [fish0_move0, ..., fishN_move0], ..., M: [fish0_moveM, ..., fishN_moveM]} Fish moves: 4 0 5 2 8 3 6 1 7 :param float probability: probability of accessing child :return: a new Node instance that has been added to current Node instance's children """ if observations is None: observations = {} new_node = self.__class__(root=False) new_node.state = state new_node.parent = self new_node.move = move new_node.depth = depth new_node.observations = observations self.children.append(new_node) new_node.probability = probability return new_node def initialize_root(self, curr_state, player): """ Initialize root node. :param curr_state: parsed dict coming from game_controller :param int player: 0 (we) / 1 (opponent) :return: """ self.depth = 0 self.player = player # Root's player obs = curr_state["observations"] keys = sorted(obs.keys()) obs = np.array([np.array(obs[k]) for k in keys]) obs = obs.T obs = {i: j.tolist() for i, j in enumerate(obs)} self.observations = obs # Translate message state into state object curr_state_s = State(len(curr_state["fishes_positions"].keys())) curr_state_s.set_player(self.player) curr_state_s.set_hook_positions( (*curr_state["hooks_positions"][0], *curr_state["hooks_positions"][1])) curr_state_s.set_caught( (curr_state["caught_fish"][0], curr_state["caught_fish"][1])) for i, f in curr_state["fishes_positions"].items(): curr_state_s.set_fish_positions(i, f) # Set score of players player_scores = curr_state["player_scores"] curr_state_s.set_player_scores(player_scores[0], player_scores[1]) # Set score, i.e. points, for fishes fish_scores = curr_state["fish_scores"] curr_state_s.set_fish_scores(fish_scores) self.state = curr_state_s # Root's state object def compute_and_get_children(self): """ Populate the node with its children. Then return them. :return: list of children nodes """ if len(self.observations) == self.depth: # Cannot compute children any longer return [] if len(self.children) != 0: # If we have already computed the children return self.children current_player = self.state.get_player() caught = self.state.get_caught() if caught[current_player] is not None: # Next action is always up for the current player new_state = self.compute_next_state(self.state, 1, self.observations[self.depth]) self.add_child(new_state, 1, self.depth + 1, self.observations) else: # Any action is possible for act in range(5): new_state = self.compute_next_state( self.state, act, self.observations[self.depth]) self.add_child(new_state, act, self.depth + 1, self.observations) return self.children def compute_next_state(self, current_state, act, observations): """ Given a state and an action, compute the next state. Add the next observations as well. :param current_state: current state object instance :param act: integer of the move :param observations: list of observations for current fish :return: """ current_player = current_state.get_player() next_player = 1 - current_player fish_states = current_state.get_fish_positions() hook_states = current_state.get_hook_positions() new_state = State(len(fish_states.keys())) new_state.set_player(next_player) current_fishes_on_rod = current_state.get_caught() self.compute_new_fish_states(new_state, fish_states, observations, current_player, fishes_on_rod=current_fishes_on_rod) new_hook_positions = self.compute_new_hook_states( hook_states, current_player, ACT_TO_MOVES[act]) new_state.set_hook_positions(new_hook_positions) # Get player scores for new state score_p0, score_p1 = current_state.get_player_scores() # Set fish scores for new state new_state.set_fish_scores(current_state.get_fish_scores()) # Compute the fish that are currently caught by players next_caught_fish, pull_in_fishes = compute_caught_fish(new_state, current_fishes_on_rod) # Update player scores and remove fishes that are caught and at the surface fish_score_points = new_state.get_fish_scores() for i_player, fish_number in enumerate(pull_in_fishes): if fish_number is not None: if i_player == 0: score_p0 += fish_score_points[fish_number] else: score_p1 += fish_score_points[fish_number] # Remove fish new_state.remove_fish(fish_number) # Update players scores new_state.set_player_scores(score_p0, score_p1) new_state.set_caught(next_caught_fish) return new_state def compute_new_hook_states(self, current_hook_states, current_player, move): """ Compute the hook states after a certain move :param current_hook_states: 4-iterable with (x, y) positions of player 0's hook and (x, y) of player 1's hook :param current_player: either 0 or 1 :param move: integer. current_player's action :return: 4 elements list with new (x, y) positions of player 0's hook and (x, y) of player 1's hook """ new_hook_states = [0, 0, 0, 0] next_player = 1 - current_player hook_position_next_player = current_hook_states[next_player] new_hook_states[next_player * 2] = hook_position_next_player[0] new_hook_states[next_player * 2 + 1] = hook_position_next_player[1] hook_position_current_player = self.xy_move( current_hook_states[current_player], move, current_hook_states[next_player]) new_hook_states[current_player * 2] = hook_position_current_player[0] new_hook_states[current_player * 2 + 1] = hook_position_current_player[1] return new_hook_states def compute_new_fish_states(self, new_state, current_fish_positions, observations, current_player, fishes_on_rod=None): """ Compute the new fish states given the observations :param new_state: state instance where to save the new fish positions :param current_fish_positions: map: fish_number -> (x, y) position of the fish :param observations: list of observations, in the order of the sorted keys of the remaining fishes :return: """ for i, k in enumerate(sorted(current_fish_positions.keys())): if fishes_on_rod[current_player] == k: # Fishes on rod of current player can only move up new_fish_obs_code = OBS_TO_MOVES[0] elif fishes_on_rod[1 - current_player] == k: # Fishes on rod of other player do not move new_fish_obs_code = (0, 0) else: obs = observations[i] new_fish_obs_code = OBS_TO_MOVES[obs] curr_pos = current_fish_positions[k] new_state.set_fish_positions(k, self.xy_move(curr_pos, new_fish_obs_code)) def xy_move(self, pos, move, adv_pos=None): """ Return the (x, y) position after a given move of the tuple pos. Wraps the x axis so that trespassing the right margin means appearing in the left and vice versa. Makes sure the hooks cannot cross each other. :param pos: 2-tuple. Current position (x, y) :param move: 2-tuple. Desired move. :return: 2-tuple. pos + move corrected to be in the margins [0, space_subdivisions) """ space_subdivisions = 20 pos_x = (pos[0] + move[0] + space_subdivisions) % space_subdivisions pos_y = pos[1] + move[1] if not 0 <= pos_y < space_subdivisions: pos_y = pos[1] if adv_pos is not None: if pos_x == adv_pos[0]: return pos[0], pos_y return pos_x, pos_y
gangababu/rultor
rultor-web/src/main/java/com/rultor/web/PulseRs.java
<filename>rultor-web/src/main/java/com/rultor/web/PulseRs.java /** * Copyright (c) 2009-2013, rultor.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: 1) Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. 3) Neither the name of the rultor.com nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.rultor.web; import com.jcabi.aspects.Loggable; import com.rultor.spi.Arguments; import com.rultor.spi.Drain; import com.rultor.spi.Pulse; import com.rultor.spi.Repo; import com.rultor.spi.Rule; import com.rultor.spi.SpecException; import com.rultor.spi.Tag; import com.rultor.spi.Wallet; import com.rultor.spi.Work; import com.rultor.tools.Exceptions; import com.rultor.tools.Time; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.NoSuchElementException; import java.util.logging.Level; import javax.validation.constraints.NotNull; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import org.apache.commons.io.IOUtils; /** * Single pulse. * * @author <NAME> (<EMAIL>) * @version $Id$ * @since 1.0 * @checkstyle MultipleStringLiterals (500 lines) * @checkstyle ClassDataAbstractionCoupling (500 lines) */ @Path("/pulse/{name:[\\w\\-]+}/{date:\\d+}") @Loggable(Loggable.DEBUG) public final class PulseRs extends BaseRs { /** * Rule name. */ private transient String name; /** * Pulse date. */ private transient Time date; /** * Inject it from query. * @param rule Rule name */ @PathParam("name") public void setName(@NotNull(message = "rule name is mandatory") final String rule) { this.name = rule; } /** * Inject it from query. * @param time PulseOfDrain time */ @PathParam("date") public void setDate(@NotNull(message = "date is mandatory") final String time) { this.date = new Time(Long.parseLong(time)); } /** * Get stream. * @return The JAX-RS response */ @GET @Path("/stream") @Produces("text/plain; charset=UTF-8") public String stream() { try { return IOUtils.toString(this.pulse().stream()); } catch (IOException ex) { throw this.flash().redirect( this.uriInfo().getBaseUriBuilder() .clone() .path(DrainRs.class) .build(this.name), String.format( "Can't read this pulse: %s", Exceptions.message(ex) ), Level.SEVERE ); } } /** * Get pulse. * @return The pulse */ private Pulse pulse() { final Rule rule; try { rule = this.user().rules().get(this.name); } catch (NoSuchElementException ex) { throw this.flash().redirect(this.uriInfo().getBaseUri(), ex); } return new Pulse() { @Override public String xembly() throws IOException { throw new UnsupportedOperationException(); } @Override public InputStream stream() throws IOException { return PulseRs.this.read(rule); } @Override public String identifier() { throw new UnsupportedOperationException(); } @Override public Collection<Tag> tags() { throw new UnsupportedOperationException(); } }; } /** * Read stream of the drain. * @param rule Rule to read from * @return Stream * @throws IOException If fails */ private InputStream read(final Rule rule) throws IOException { try { return Drain.Source.class.cast( new Repo.Cached( this.repo(), this.user(), rule.spec() ).get().instantiate( this.users(), new Arguments( new Work.Simple( this.user().urn(), this.name, this.date ), new Wallet.Empty() ) ) ).drain().read(); } catch (SpecException ex) { throw this.flash().redirect( this.uriInfo().getBaseUri(), String.format( "Can't instantiate drain of \"%s\": %s", this.name, Exceptions.message(ex) ), Level.SEVERE ); } } }
xiwc/confluence.keygen
com/jgoodies/looks/MicroLayout.java
/* 1: */ package com.jgoodies.looks; /* 2: */ /* 3: */ import java.awt.Insets; /* 4: */ import javax.swing.plaf.InsetsUIResource; /* 5: */ /* 6: */ public final class MicroLayout /* 7: */ { /* 8: */ private final InsetsUIResource textInsets; /* 9: */ private final InsetsUIResource wrappedTextInsets; /* 10: */ private final InsetsUIResource comboBoxEditorInsets; /* 11: */ private final Insets buttonBorderInsets; /* 12: */ private final InsetsUIResource buttonMargin; /* 13: */ private final InsetsUIResource commitButtonMargin; /* 14: */ private final int comboBorderSize; /* 15: */ private final int comboPopupBorderSize; /* 16: */ private final InsetsUIResource checkBoxMargin; /* 17: */ private final InsetsUIResource menuItemMargin; /* 18: */ private final InsetsUIResource menuMargin; /* 19: */ private final InsetsUIResource popupMenuSeparatorMargin; /* 20: */ /* 21: */ public MicroLayout(InsetsUIResource textInsets, InsetsUIResource wrappedTextInsets, InsetsUIResource comboBoxEditorInsets, int comboBorderSize, int comboPopupBorderSize, Insets buttonBorderInsets, InsetsUIResource buttonMargin, InsetsUIResource commitButtonMargin, InsetsUIResource checkBoxMargin, InsetsUIResource menuItemMargin, InsetsUIResource menuMargin, InsetsUIResource popupMenuSeparatorMargin) /* 22: */ { /* 23: 76 */ this.textInsets = textInsets; /* 24: 77 */ this.wrappedTextInsets = wrappedTextInsets; /* 25: 78 */ this.comboBoxEditorInsets = comboBoxEditorInsets; /* 26: 79 */ this.buttonBorderInsets = buttonBorderInsets; /* 27: 80 */ this.buttonMargin = buttonMargin; /* 28: 81 */ this.commitButtonMargin = commitButtonMargin; /* 29: 82 */ this.comboBorderSize = comboBorderSize; /* 30: 83 */ this.comboPopupBorderSize = comboPopupBorderSize; /* 31: 84 */ this.checkBoxMargin = checkBoxMargin; /* 32: 85 */ this.menuItemMargin = menuItemMargin; /* 33: 86 */ this.menuMargin = menuMargin; /* 34: 87 */ this.popupMenuSeparatorMargin = popupMenuSeparatorMargin; /* 35: */ } /* 36: */ /* 37: */ public Insets getButtonBorderInsets() /* 38: */ { /* 39: 99 */ return this.buttonBorderInsets; /* 40: */ } /* 41: */ /* 42: */ public InsetsUIResource getButtonMargin() /* 43: */ { /* 44:119 */ return this.buttonMargin; /* 45: */ } /* 46: */ /* 47: */ public InsetsUIResource getCommitButtonMargin() /* 48: */ { /* 49:135 */ return this.commitButtonMargin; /* 50: */ } /* 51: */ /* 52: */ public int getComboBorderSize() /* 53: */ { /* 54:139 */ return this.comboBorderSize; /* 55: */ } /* 56: */ /* 57: */ public int getComboPopupBorderSize() /* 58: */ { /* 59:143 */ return this.comboPopupBorderSize; /* 60: */ } /* 61: */ /* 62: */ public InsetsUIResource getComboBoxEditorInsets() /* 63: */ { /* 64:147 */ return this.comboBoxEditorInsets; /* 65: */ } /* 66: */ /* 67: */ public InsetsUIResource getCheckBoxMargin() /* 68: */ { /* 69:151 */ return this.checkBoxMargin; /* 70: */ } /* 71: */ /* 72: */ public InsetsUIResource getMenuItemMargin() /* 73: */ { /* 74:156 */ return this.menuItemMargin; /* 75: */ } /* 76: */ /* 77: */ public InsetsUIResource getMenuMargin() /* 78: */ { /* 79:160 */ return this.menuMargin; /* 80: */ } /* 81: */ /* 82: */ public InsetsUIResource getPopupMenuSeparatorMargin() /* 83: */ { /* 84:164 */ return this.popupMenuSeparatorMargin; /* 85: */ } /* 86: */ /* 87: */ public InsetsUIResource getTextInsets() /* 88: */ { /* 89:169 */ return this.textInsets; /* 90: */ } /* 91: */ /* 92: */ public InsetsUIResource getWrappedTextInsets() /* 93: */ { /* 94:174 */ return this.wrappedTextInsets; /* 95: */ } /* 96: */ } /* Location: C:\Users\xi\Desktop\confluence_keygen\confluence_keygen.jar * Qualified Name: com.jgoodies.looks.MicroLayout * JD-Core Version: 0.7.0.1 */
jamiemccrindle/bpmscript
bpmscript-core/src/main/java/org/bpmscript/paging/Query.java
<reponame>jamiemccrindle/bpmscript<filename>bpmscript-core/src/main/java/org/bpmscript/paging/Query.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bpmscript.paging; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * An implementation of the {@link IQuery} interface. */ public class Query implements IQuery, Serializable { /** * @serial serial version id */ private static final long serialVersionUID = -6451150680840278791L; /** * A default ALL query that returns all results, starting at the beginning. */ public static final Query ALL = new Query(); private String filter; private List<IOrderBy> orderBys; private int firstResult = -1; private int maxResults = -1; public Query(IOrderBy[] orderBys, int firstResult, int maxResults) { this.orderBys = orderBys != null ? Arrays.asList(orderBys) : new ArrayList<IOrderBy>(); this.firstResult = firstResult; this.maxResults = maxResults; } public Query() { } public Query(int firstResult, int maxResults) { } public int getFirstResult() { return firstResult; } public void setFirstResult(int firstResult) { this.firstResult = firstResult; } public int getMaxResults() { return maxResults; } public void setMaxResults(int maxResults) { this.maxResults = maxResults; } public List<IOrderBy> getOrderBys() { return orderBys; } public void setOrderBys(List<IOrderBy> orderBys) { this.orderBys = orderBys; } public String getFilter() { return filter; } public void setFilter(String filter) { this.filter = filter; } public void addOrderBy(String field, boolean asc) { if(orderBys == null) { orderBys = new ArrayList<IOrderBy>(); } orderBys.add(new OrderBy(field, asc)); } }
hermannhueck/playground-circe
src/main/scala/ch07circeoptics/Optics.scala
<gh_stars>0 package ch07circeoptics import scala.util.chaining._ import hutil.stringformat._ import io.circe._ import io.circe.parser._ object Optics extends App { dash80.green.println() s"$dash10 Traversing JSON $dash10".magenta.println() val jsonDocument = """ { "order": { "customer": { "name": "<NAME>", "contactDetails": { "address": "1 Fake Street, London, England", "phone": "0123-456-789" } }, "items": [{ "id": 123, "description": "banana", "quantity": 1 }, { "id": 456, "description": "apple", "quantity": 2 }], "total": 123.45 } } """ jsonDocument pipe println val json = parse(jsonDocument).getOrElse(Json.Null) "\n--- retrieving phone number using a cursor:" pipe println val phoneNum: Option[String] = json .hcursor .downField("order") .downField("customer") .downField("contactDetails") .get[String]("phone") .toOption // phoneNum: Option[String] = Some(0123-456-789) phoneNum pipe println "\n--- retrieving phone number with optics:" pipe println import io.circe.optics.JsonPath // import io.circe.optics.JsonPath._ val _phoneNum = JsonPath.root.order.customer.contactDetails.phone.string // _phoneNum: monocle.Optional[io.circe.Json,String] = monocle.POptional$$anon$1@dc15f21 val phoneNum2: Option[String] = _phoneNum.getOption(json) // phoneNum: Option[String] = Some(0123-456-789) phoneNum2 pipe println "\n--- retrieving items and quantities using a cursor:" pipe println val items: Vector[Json] = json .hcursor .downField("order") .downField("items") .focus .flatMap(_.asArray) .getOrElse(Vector.empty) .tap(println) // items: Vector[io.circe.Json] = // Vector({ // "id" : 123, // "description" : "banana", // "quantity" : 1 // }, { // "id" : 456, // "description" : "apple", // "quantity" : 2 // }) println() val quantities: Vector[Int] = items .flatMap(_.hcursor.get[Int]("quantity").toOption) .tap(println) // quantities: Vector[Int] = Vector(1, 2) "\n--- retrieving items and quantities with optics:" pipe println val items2 = JsonPath .root .order .items .arr .getOption(json) .getOrElse(Vector.empty) tap println println() val quantities2: List[Int] = JsonPath .root .order .items .each .quantity .int .getAll(json) tap println // quantities2: List[Int] = List(1, 2) s"$dash10 Modifying JSON $dash10".magenta.println() val doubleQuantities: Json => Json = JsonPath .root .order .items .each .quantity .int .modify(_ * 2) // doubleQuantities: io.circe.Json => io.circe.Json = monocle.PTraversal$$Lambda$9793/0x0000000802610840@6b6cd655 val modifiedJson: Json = doubleQuantities(json) tap println s"$dash10 Recursively modifying JSON $dash10".magenta.println() import io.circe.optics.JsonOptics._ import monocle.function.Plated Plated.transform[Json] { j => json.asNumber match { case Some(n) => Json.fromString(n.toString) case None => j } }(json) pipe println println() s"$dash10 Dynamic $dash10".magenta.println() """| |Some of the code above may look quite magical at first glance. |How are we calling methods like order, items and customer on circe’s JsonPath class? | |The answer is that JsonPath relies on a slightly obscure feature of Scala called Dynamic. |This means you can call methods that don’t actually exist. When you do so, |the selectDynamic method is called, and the name of the method you wanted to call is passed as an argument. |""".stripMargin pipe println s"$dash10 Warning $dash10".magenta.println() """| |The use of Dynamic means that your code is not “typo-safe”. For example, if you fat-finger the previous example: | |This code will compile just fine, but not do what you expect. |Because the JSON document doesn’t have an itemss field, the same document will be returned unmodified. |""".stripMargin pipe println val doubleQuantitiesTypo: Json => Json = // leaves the numbers unchanged JsonPath.root.order.itemss.each.quantity.int.modify(_ * 2) // Note the "itemss" typo val modifiedJsonTypo = doubleQuantitiesTypo(json) tap println dash80.green.println() }
wildland/token_authenticate_me
lib/token_authenticate_me/concerns/models/sessionable.rb
require 'active_support/concern' module TokenAuthenticateMe module Concerns module Models module Sessionable extend ActiveSupport::Concern included do belongs_to :user before_create :generate_unique_key def as_json(options = {}) { session: super({ include: :user }.merge(options)) } end def attributes { 'key' => key, 'expiration' => expiration, 'created_at' => created_at, 'updated_at' => updated_at } end private def generate_unique_key begin self.key = SecureRandom.hex end while self.class.exists?(key: key) # rubocop:disable Lint/Loop self.expiration = expiration_hours.hours.from_now end def expiration_hours 24 end end end end end end
ezLeaks/backdoored
org/spongepowered/asm/mixin/refmap/RemappingReferenceMapper.java
<filename>org/spongepowered/asm/mixin/refmap/RemappingReferenceMapper.java package org.spongepowered.asm.mixin.refmap; import org.spongepowered.asm.mixin.*; import java.util.*; import com.google.common.base.*; import java.io.*; import com.google.common.io.*; import org.apache.logging.log4j.*; public final class RemappingReferenceMapper implements IReferenceMapper { private static final String DEFAULT_RESOURCE_PATH_PROPERTY = "net.minecraftforge.gradle.GradleStart.srg.srg-mcp"; private static final String DEFAULT_MAPPING_ENV = "searge"; private static final Logger logger; private static final Map<String, Map<String, String>> srgs; private final IReferenceMapper refMap; private final Map<String, String> mappings; private final Map<String, Map<String, String>> cache; private RemappingReferenceMapper(final MixinEnvironment a1, final IReferenceMapper a2) { super(); this.cache = new HashMap<String, Map<String, String>>(); (this.refMap = a2).setContext(getMappingEnv(a1)); final String v1 = getResource(a1); this.mappings = loadSrgs(v1); RemappingReferenceMapper.logger.info("Remapping refMap {} using {}", new Object[] { a2.getResourceName(), v1 }); } @Override public boolean isDefault() { return this.refMap.isDefault(); } @Override public String getResourceName() { return this.refMap.getResourceName(); } @Override public String getStatus() { return this.refMap.getStatus(); } @Override public String getContext() { return this.refMap.getContext(); } @Override public void setContext(final String a1) { } @Override public String remap(final String v1, final String v2) { final Map<String, String> v3 = this.getCache(v1); String v4 = v3.get(v2); if (v4 == null) { v4 = this.refMap.remap(v1, v2); for (final Map.Entry<String, String> a1 : this.mappings.entrySet()) { v4 = v4.replace(a1.getKey(), a1.getValue()); } v3.put(v2, v4); } return v4; } private Map<String, String> getCache(final String a1) { Map<String, String> v1 = this.cache.get(a1); if (v1 == null) { v1 = new HashMap<String, String>(); this.cache.put(a1, v1); } return v1; } @Override public String remapWithContext(final String a1, final String a2, final String a3) { return this.refMap.remapWithContext(a1, a2, a3); } private static Map<String, String> loadSrgs(final String v1) { if (RemappingReferenceMapper.srgs.containsKey(v1)) { return RemappingReferenceMapper.srgs.get(v1); } final Map<String, String> v2 = new HashMap<String, String>(); RemappingReferenceMapper.srgs.put(v1, v2); final File v3 = new File(v1); if (!v3.isFile()) { return v2; } try { Files.readLines(v3, Charsets.UTF_8, (LineProcessor)new LineProcessor<Object>() { final /* synthetic */ Map val$map; RemappingReferenceMapper$1() { super(); } public Object getResult() { return null; } public boolean processLine(final String v2) throws IOException { if (Strings.isNullOrEmpty(v2) || v2.startsWith("#")) { return true; } final int v3 = 0; int v4 = 0; int n2; final int n = v2.startsWith("MD: ") ? (n2 = 2) : (v2.startsWith("FD: ") ? (n2 = 1) : (n2 = 0)); v4 = n2; if (n > 0) { final String[] a1 = v2.substring(4).split(" ", 4); v2.put(a1[v3].substring(a1[v3].lastIndexOf(47) + 1), a1[v4].substring(a1[v4].lastIndexOf(47) + 1)); } return true; } }); } catch (IOException a1) { RemappingReferenceMapper.logger.warn("Could not read input SRG file: {}", new Object[] { v1 }); RemappingReferenceMapper.logger.catching((Throwable)a1); } return v2; } public static IReferenceMapper of(final MixinEnvironment a1, final IReferenceMapper a2) { if (!a2.isDefault() && hasData(a1)) { return new RemappingReferenceMapper(a1, a2); } return a2; } private static boolean hasData(final MixinEnvironment a1) { final String v1 = getResource(a1); return v1 != null && new File(v1).exists(); } private static String getResource(final MixinEnvironment a1) { final String v1 = a1.getOptionValue(MixinEnvironment.Option.REFMAP_REMAP_RESOURCE); return Strings.isNullOrEmpty(v1) ? System.getProperty("net.minecraftforge.gradle.GradleStart.srg.srg-mcp") : v1; } private static String getMappingEnv(final MixinEnvironment a1) { final String v1 = a1.getOptionValue(MixinEnvironment.Option.REFMAP_REMAP_SOURCE_ENV); return Strings.isNullOrEmpty(v1) ? "searge" : v1; } static { logger = LogManager.getLogger("mixin"); srgs = new HashMap<String, Map<String, String>>(); } }
dariopascu/squall
caelus/aws/storages/__init__.py
<reponame>dariopascu/squall<filename>caelus/aws/storages/__init__.py<gh_stars>1-10 from .s3_storage import S3Storage __all__ = [ 'S3Storage', ]
jasonfeihe/BitFunnel
src/Plan/src/RegisterAllocator.cpp
<reponame>jasonfeihe/BitFunnel // The MIT License (MIT) // Copyright (c) 2016, Microsoft // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include <algorithm> // For std::max(). #include "BitFunnel/Allocators/IAllocator.h" #include "CompileNode.h" #include "LoggerInterfaces/Logging.h" #include "RegisterAllocator.h" // TODO: get rid of dynamic_cast? namespace BitFunnel { //************************************************************************* // // RegisterAllocator // //************************************************************************* RegisterAllocator::RegisterAllocator() : m_rowCount(0), m_registerCount(0), m_registerBase(0), m_mapping(nullptr), m_abstractRows(nullptr), m_registersAllocated(0), m_rowIdsByRegister(nullptr) { } RegisterAllocator::RegisterAllocator(CompileNode const & root, unsigned rowCount, unsigned registerBase, unsigned registerCount, IAllocator& allocator) : m_rowCount(rowCount), m_registerCount(registerCount), m_registerBase(registerBase) { m_rows = reinterpret_cast<Entry*>(allocator.Allocate(sizeof(Entry) * m_rowCount)); for (unsigned i = 0 ; i < m_rowCount; ++i) { new (m_rows + i) Entry(i); } m_abstractRows = reinterpret_cast<AbstractRow*>(allocator.Allocate(sizeof(AbstractRow) * m_rowCount)); CollectRows(root, 0, 1); std::sort(m_rows, m_rows + m_rowCount); // Generate mapping from abstract row id to position in register // allocation sort. The first positions in this sort will be allocated // to registers. m_mapping = reinterpret_cast<unsigned*>(allocator.Allocate(sizeof(unsigned) * m_rowCount)); for (unsigned i = 0 ; i < m_rowCount; ++i) { m_mapping[m_rows[i].GetId()] = i; } // Generate a mapping from register number (starting at 0) to abstract // row id. m_registersAllocated = 0; m_rowIdsByRegister = reinterpret_cast<unsigned*>(allocator.Allocate(sizeof(unsigned) * m_registerCount)); for (unsigned i = 0; i < m_rowCount && i < m_registerCount; ++i) { if (m_rows[i].IsUsed()) { m_rowIdsByRegister[m_registersAllocated++] = m_rows[i].GetId(); } else { break; } } } bool RegisterAllocator::IsRegister(unsigned id) const { return (m_mapping != nullptr) && (m_mapping[id] < m_registerCount); } unsigned RegisterAllocator::GetRegister(unsigned id) const { LogAssertB(id < m_rowCount, "id must be < m_rowCount."); LogAssertB(m_mapping != nullptr, "m_mapping nullptr."); return m_mapping[id] + m_registerBase; } // TODO: Add unit test for this method. unsigned RegisterAllocator::GetRegistersAllocated() const { return m_registersAllocated; } // TODO: Add unit test for this method. unsigned RegisterAllocator::GetRowIdFromRegister(unsigned reg) const { LogAssertB(reg < m_registersAllocated, "reg number overflow."); LogAssertB(m_rowIdsByRegister != nullptr, "m_rowIdsByRegister nullptr."); return m_rowIdsByRegister[reg]; } AbstractRow const & RegisterAllocator::GetRow(unsigned id) const { LogAssertB(id < m_rowCount, "id overflow."); LogAssertB(m_abstractRows != nullptr, "m_abstractRows nullptr."); return m_abstractRows[id]; } void RegisterAllocator::CollectRows(CompileNode const & root, unsigned depth, unsigned uses) { switch (root.GetType()) { case CompileNode::opAndRowJz: { CompileNode::AndRowJz const & node = dynamic_cast<CompileNode::AndRowJz const &>(root); unsigned id = node.GetRow().GetId(); LogAssertB(id < m_rowCount, "id overflow."); m_rows[id].UpdateDepth(depth, uses); new (m_abstractRows + id) AbstractRow(node.GetRow()); CollectRows(node.GetChild(), depth + 1, uses); } break; case CompileNode::opLoadRowJz: { CompileNode::LoadRowJz const & node = dynamic_cast<CompileNode::LoadRowJz const &>(root); unsigned id = node.GetRow().GetId(); LogAssertB(id < m_rowCount, "id overflow."); m_rows[id].UpdateDepth(depth, uses); new (m_abstractRows + id) AbstractRow(node.GetRow()); CollectRows(node.GetChild(), depth + 1, uses); } break; case CompileNode::opOr: { CompileNode::Or const & node = dynamic_cast<CompileNode::Or const &>(root); CollectRows(node.GetLeft(), depth, uses); CollectRows(node.GetRight(), depth, uses); } break; case CompileNode::opRankDown: { CompileNode::RankDown const & node = dynamic_cast<CompileNode::RankDown const &>(root); CollectRows(node.GetChild(), depth, uses << node.GetDelta()); } break; case CompileNode::opReport: { CompileNode::Report const & node = dynamic_cast<CompileNode::Report const &>(root); CompileNode const * child = node.GetChild(); if (child != nullptr) { CollectRows(*child, depth, uses); } } break; case CompileNode::opAndTree: { CompileNode::AndTree const & node = dynamic_cast<CompileNode::AndTree const &>(root); CollectRows(node.GetLeft(), depth + 1, uses); CollectRows(node.GetRight(), depth + 1, uses); } break; case CompileNode::opLoadRow: { CompileNode::LoadRow const & node = dynamic_cast<CompileNode::LoadRow const &>(root); unsigned id = node.GetRow().GetId(); LogAssertB(id < m_rowCount, "id overflow."); m_rows[id].UpdateDepth(depth, uses); new (m_abstractRows + id) AbstractRow(node.GetRow()); } break; case CompileNode::opOrTree: { CompileNode::OrTree const & node = dynamic_cast<CompileNode::OrTree const &>(root); CollectRows(node.GetLeft(), depth + 1, uses); CollectRows(node.GetRight(), depth + 1, uses); } break; case CompileNode::opNot: { CompileNode::Not const & node = dynamic_cast<CompileNode::Not const &>(root); CollectRows(node.GetChild(), depth, uses); } break; default: LogAbortB("Unknown node type."); break; } } //************************************************************************* // // RegisterAllocator::Entry // //************************************************************************* RegisterAllocator::Entry::Entry(unsigned id) : m_id(id), m_depth(c_noAssociatedRow), m_uses(0) { } void RegisterAllocator::Entry::UpdateDepth(unsigned depth, unsigned uses) { if (depth < m_depth) { m_depth = depth; m_uses = uses; } else if (depth == m_depth) { m_uses += uses; } } bool RegisterAllocator::Entry::operator<(Entry const & other) const { if (m_depth == other.m_depth) { return m_uses > other.m_uses; } else { return m_depth < other.m_depth; } } unsigned RegisterAllocator::Entry::GetDepth() const { return m_depth; } unsigned RegisterAllocator::Entry::GetId() const { return m_id; } unsigned RegisterAllocator::Entry::GetUses() const { return m_uses; } bool RegisterAllocator::Entry::IsUsed() const { return m_depth != c_noAssociatedRow; } }
uktrade/export-wins-data
wins/migrations/0007_auto_20160609_1239.py
<filename>wins/migrations/0007_auto_20160609_1239.py<gh_stars>1-10 # -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-06-09 12:39 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wins', '0006_auto_20160608_1602'), ] operations = [ migrations.AlterField( model_name='win', name='has_hvo_specialist_involvement', field=models.BooleanField(verbose_name='Have HVO Specialists been involved?'), ), migrations.AlterField( model_name='win', name='is_line_manager_confirmed', field=models.BooleanField(verbose_name='My line manager has confirmed the decision to record this win'), ), migrations.AlterField( model_name='win', name='is_prosperity_fund_related', field=models.BooleanField(verbose_name='Is this win prosperity fund related?'), ), ]
ShoukriKattan/ForgedUI-Eclipse
com.forgedui.editor/src/com/forgedui/editor/preference/CodeGenerationPreferences.java
<reponame>ShoukriKattan/ForgedUI-Eclipse /** * */ package com.forgedui.editor.preference; /** * @author shoukry * */ public class CodeGenerationPreferences { public static final String CODE_GENERATION_STYLE_PROPERTY_NAME="com.forgedui.codegen.prefs.codegen.style"; public static final int CODE_GEN_STYLE_VALUE_BASIC=0; public static final int CODE_GEN_STYLE_VALUE_OO_MODULE=1; public static final int CODE_GEN_STYLE_VALUE_COMMON_JS=2; public static final String CODE_GENERATION_STYLE_SUPPORT_JSS_PROPERTY_NAME="com.forgedui.codegen.prefs.codegen.supportjss"; }
Sajaki/intellij-community
platform/lang-impl/src/com/intellij/util/ui/classpath/SingleRootClasspathElement.java
package com.intellij.util.ui.classpath; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.vfs.JarFileSystem; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.util.Collections; import java.util.List; public class SingleRootClasspathElement implements SimpleClasspathElement { @NonNls public static final String URL_ELEMENT = "url"; private final String myUrl; public SingleRootClasspathElement(@NotNull String url) { myUrl = url; } @Override public String getPresentableName() { String url; if (myUrl.endsWith(JarFileSystem.JAR_SEPARATOR)) { url = myUrl.substring(0, myUrl.length() - JarFileSystem.JAR_SEPARATOR.length()); } else { url = myUrl; } int startIndex = Math.min(url.lastIndexOf('/') + 1, url.length() - 1); return url.substring(startIndex); } @Override public Library getLibrary() { return null; } @Override public String getLibraryName() { return null; } @Override public void serialize(Element element) throws IOException { element.addContent(new Element(URL_ELEMENT).setText(myUrl)); } @Override public List<String> getClassesRootUrls() { return Collections.singletonList(myUrl); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SingleRootClasspathElement element = (SingleRootClasspathElement)o; if (!myUrl.equals(element.myUrl)) return false; return true; } @Override public int hashCode() { return myUrl.hashCode(); } }
huzecong/nnlib
nnlib/utils/string.py
from typing import List __all__ = ['ordinal', 'to_camelcase', 'to_underscore', 'to_capitalized'] def ordinal(x: int) -> str: suffix = 'th' if 10 <= x % 100 < 19 else {1: 'st', 2: 'nd', 3: 'rd'}.get(x % 10, 'th') return str(x) + suffix def _get_name_pieces(name: str) -> List[str]: if '_' in name: # underscore return [x.lower() for x in name.split('_')] else: # camelcase / capitalized pos = [idx for idx, ch in enumerate(name) if ch.upper() == ch] + [len(name)] if pos[0] != 0: pos = [0] + pos return [name[l:r].lower() for l, r in zip(pos[:-1], pos[1:])] def to_underscore(name: str) -> str: spl = _get_name_pieces(name) return '_'.join(spl) def to_camelcase(name: str) -> str: spl = _get_name_pieces(name) if len(spl) == 0: return '' return spl[0] + ''.join(x.capitalize() for x in spl[1:]) def to_capitalized(name: str) -> str: spl = _get_name_pieces(name) return ''.join(x.capitalize() for x in spl)
daodao10/chart
cn/002061_d.js
<gh_stars>1-10 var data=[['20060816',4.152], ['20060817',4.465], ['20060818',4.413], ['20060821',4.531], ['20060822',4.536], ['20060823',4.572], ['20060824',5.101], ['20060825',5.577], ['20060828',5.767], ['20060829',6.106], ['20060830',6.142], ['20060831',6.054], ['20060901',6.731], ['20060904',6.742], ['20060905',6.562], ['20060906',6.629], ['20060907',7.065], ['20060908',6.972], ['20060911',7.480], ['20060912',7.270], ['20060913',7.301], ['20060914',6.808], ['20060915',6.772], ['20060918',6.880], ['20060919',6.726], ['20060920',6.859], ['20060921',6.983], ['20060922',7.029], ['20060925',6.808], ['20060926',6.526], ['20060927',6.818], ['20060928',6.849], ['20060929',7.075], ['20061009',7.024], ['20061010',7.075], ['20061011',7.670], ['20061012',7.516], ['20061013',7.444], ['20061016',7.485], ['20061017',7.229], ['20061018',7.265], ['20061019',7.259], ['20061020',7.290], ['20061023',7.306], ['20061024',7.583], ['20061025',7.583], ['20061026',7.906], ['20061027',7.772], ['20061030',7.413], ['20061031',7.511], ['20061101',7.249], ['20061103',7.244], ['20061106',6.998], ['20061107',7.280], ['20061108',7.126], ['20061109',7.265], ['20061110',6.916], ['20061113',6.716], ['20061114',6.870], ['20061115',6.906], ['20061116',7.024], ['20061117',6.926], ['20061120',6.629], ['20061121',6.777], ['20061122',6.783], ['20061123',6.706], ['20061124',6.936], ['20061127',7.162], ['20061128',7.198], ['20061129',7.172], ['20061130',7.336], ['20061201',7.388], ['20061204',7.608], ['20061205',7.434], ['20061206',6.998], ['20061207',6.685], ['20061208',6.588], ['20061211',6.665], ['20061212',6.444], ['20061213',6.516], ['20061214',6.680], ['20061215',6.665], ['20061218',6.511], ['20061219',6.911], ['20061220',7.126], ['20061221',6.793], ['20061222',6.608], ['20061225',6.613], ['20061226',6.485], ['20061227',6.501], ['20061228',5.962], ['20061229',6.018], ['20070104',5.824], ['20070105',6.167], ['20070108',6.383], ['20070109',6.454], ['20070110',6.588], ['20070111',6.485], ['20070112',6.424], ['20070115',7.049], ['20070116',7.408], ['20070117',7.024], ['20070118',7.654], ['20070119',7.957], ['20070122',8.665], ['20070123',8.593], ['20070124',8.552], ['20070125',7.818], ['20070126',7.747], ['20070129',8.152], ['20070130',7.880], ['20070131',7.434], ['20070201',7.254], ['20070202',7.275], ['20070205',7.331], ['20070206',7.562], ['20070207',7.670], ['20070208',7.603], ['20070209',7.854], ['20070212',8.070], ['20070213',8.408], ['20070214',8.408], ['20070215',9.229], ['20070216',9.434], ['20070226',9.526], ['20070227',8.501], ['20070228',8.511], ['20070301',7.788], ['20070302',8.085], ['20070305',7.998], ['20070306',8.013], ['20070307',8.885], ['20070308',8.957], ['20070309',9.213], ['20070312',9.352], ['20070313',9.352], ['20070314',9.080], ['20070315',9.624], ['20070316',10.388], ['20070319',11.157], ['20070320',11.029], ['20070321',11.101], ['20070322',11.239], ['20070323',11.588], ['20070326',11.588], ['20070327',11.142], ['20070328',10.736], ['20070329',10.757], ['20070330',10.536], ['20070402',10.808], ['20070403',10.921], ['20070404',10.721], ['20070405',10.808], ['20070406',10.962], ['20070409',11.331], ['20070410',10.998], ['20070411',10.752], ['20070412',10.936], ['20070413',10.793], ['20070416',11.059], ['20070417',11.280], ['20070418',11.885], ['20070419',10.767], ['20070423',11.142], ['20070424',10.885], ['20070425',10.454], ['20070426',10.552], ['20070427',10.213], ['20070430',9.952], ['20070508',10.593], ['20070509',10.295], ['20070510',10.434], ['20070511',11.536], ['20070514',11.383], ['20070515',10.618], ['20070516',10.767], ['20070517',10.859], ['20070518',11.059], ['20070521',11.275], ['20070522',11.490], ['20070523',11.388], ['20070524',11.136], ['20070525',11.280], ['20070528',12.459], ['20070529',12.767], ['20070530',11.439], ['20070531',11.013], ['20070601',9.952], ['20070604',8.947], ['20070605',9.085], ['20070606',9.742], ['20070607',9.952], ['20070608',9.993], ['20070611',10.075], ['20070612',11.136], ['20070613',11.367], ['20070614',10.921], ['20070615',11.506], ['20070618',12.408], ['20070619',12.295], ['20070620',12.049], ['20070621',12.336], ['20070622',11.280], ['20070626',11.536], ['20070627',11.972], ['20070628',10.865], ['20070629',10.613], ['20070702',10.408], ['20070703',10.818], ['20070704',11.126], ['20070705',10.459], ['20070706',11.013], ['20070709',11.526], ['20070710',11.157], ['20070711',11.193], ['20070712',11.859], ['20070713',11.798], ['20070716',11.536], ['20070717',12.295], ['20070718',12.049], ['20070719',11.859], ['20070720',12.331], ['20070723',13.229], ['20070724',12.977], ['20070725',13.224], ['20070726',12.972], ['20070727',12.618], ['20070730',12.521], ['20070731',13.824], ['20070801',12.967], ['20070802',13.393], ['20070803',13.947], ['20070806',14.013], ['20070807',13.398], ['20070808',12.588], ['20070809',12.818], ['20070810',12.193], ['20070813',12.101], ['20070814',12.408], ['20070815',12.152], ['20070816',12.506], ['20070817',12.203], ['20070820',12.562], ['20070821',12.747], ['20070822',12.716], ['20070823',13.126], ['20070824',13.034], ['20070827',12.844], ['20070828',12.424], ['20070829',11.885], ['20070830',12.065], ['20070831',12.152], ['20070903',12.408], ['20070904',11.972], ['20070905',12.265], ['20070906',12.490], ['20070907',11.972], ['20070910',12.285], ['20070911',11.526], ['20070912',11.429], ['20070913',11.521], ['20070914',11.485], ['20070917',11.706], ['20070918',11.983], ['20070919',11.485], ['20070920',11.126], ['20070921',10.870], ['20070924',11.024], ['20070925',10.675], ['20070926',10.454], ['20070927',10.418], ['20070928',10.618], ['20071008',10.972], ['20071009',10.818], ['20071010',10.598], ['20071011',10.275], ['20071012',9.813], ['20071015',9.747], ['20071016',10.193], ['20071017',10.598], ['20071018',9.983], ['20071019',9.870], ['20071022',9.485], ['20071023',9.742], ['20071024',9.501], ['20071025',9.024], ['20071026',9.203], ['20071029',9.059], ['20071030',9.485], ['20071031',9.793], ['20071101',9.388], ['20071102',9.244], ['20071105',9.547], ['20071106',9.603], ['20071107',9.434], ['20071108',9.024], ['20071109',8.721], ['20071112',8.357], ['20071113',8.418], ['20071114',8.721], ['20071115',8.470], ['20071116',8.644], ['20071119',9.029], ['20071120',9.542], ['20071121',9.706], ['20071122',9.244], ['20071126',9.321], ['20071127',9.075], ['20071128',8.701], ['20071129',8.818], ['20071130',8.752], ['20071203',8.859], ['20071204',8.818], ['20071205',9.116], ['20071206',9.090], ['20071207',9.295], ['20071210',9.572], ['20071211',9.608], ['20071212',9.690], ['20071213',9.552], ['20071214',9.849], ['20071217',10.075], ['20071218',9.895], ['20071219',10.142], ['20071220',10.229], ['20071221',10.485], ['20071224',10.813], ['20071225',10.962], ['20071226',11.203], ['20071227',10.977], ['20071228',10.639], ['20080102',11.731], ['20080103',11.772], ['20080104',11.875], ['20080107',12.408], ['20080108',11.783], ['20080109',12.403], ['20080110',11.895], ['20080111',12.249], ['20080114',12.131], ['20080115',12.490], ['20080116',12.613], ['20080117',12.244], ['20080118',11.783], ['20080121',10.726], ['20080122',9.634], ['20080123',10.490], ['20080124',10.731], ['20080125',10.890], ['20080128',10.116], ['20080129',10.254], ['20080130',10.090], ['20080131',9.906], ['20080201',9.229], ['20080204',10.203], ['20080205',10.352], ['20080213',10.049], ['20080214',10.259], ['20080215',10.162], ['20080218',10.726], ['20080219',11.024], ['20080220',10.998], ['20080221',11.372], ['20080222',10.972], ['20080225',11.080], ['20080226',10.301], ['20080227',10.434], ['20080228',9.957], ['20080229',9.808], ['20080303',9.936], ['20080304',10.152], ['20080305',9.870], ['20080306',9.813], ['20080307',9.752], ['20080310',9.208], ['20080311',8.967], ['20080312',8.690], ['20080313',8.193], ['20080314',8.357], ['20080317',7.885], ['20080318',7.085], ['20080319',7.844], ['20080320',8.265], ['20080321',8.111], ['20080324',7.895], ['20080325',7.783], ['20080326',7.721], ['20080327',7.536], ['20080328',7.511], ['20080331',7.075], ['20080401',6.316], ['20080402',5.813], ['20080403',6.024], ['20080407',6.495], ['20080408',6.706], ['20080409',6.172], ['20080410',6.403], ['20080411',6.665], ['20080414',6.716], ['20080415',7.101], ['20080416',6.777], ['20080417',6.362], ['20080418',5.793], ['20080421',5.162], ['20080422',4.593], ['20080423',4.783], ['20080424',5.311], ['20080425',5.331], ['20080428',5.126], ['20080429',5.116], ['20080430',5.454], ['20080506',6.049], ['20080507',6.701], ['20080508',6.675], ['20080509',6.521], ['20080512',6.613], ['20080513',6.347], ['20080514',6.613], ['20080515',7.049], ['20080516',6.613], ['20080519',6.511], ['20080520',5.808], ['20080521',6.024], ['20080522',6.152], ['20080523',5.834], ['20080526',5.393], ['20080527',5.506], ['20080528',5.736], ['20080529',5.572], ['20080530',5.434], ['20080602',5.485], ['20080603',5.613], ['20080604',5.475], ['20080605',5.659], ['20080606',5.818], ['20080610',5.188], ['20080611',4.618], ['20080612',4.731], ['20080613',4.208], ['20080616',3.736], ['20080617',3.383], ['20080618',3.629], ['20080619',3.213], ['20080620',3.157], ['20080623',2.988], ['20080624',3.167], ['20080625',3.372], ['20080626',3.613], ['20080627',3.254], ['20080630',3.583], ['20080701',3.511], ['20080702',3.777], ['20080703',3.849], ['20080704',3.624], ['20080707',3.767], ['20080708',3.803], ['20080709',4.213], ['20080710',4.193], ['20080711',4.024], ['20080714',4.162], ['20080715',3.885], ['20080716',3.659], ['20080717',3.536], ['20080718',3.659], ['20080721',3.834], ['20080722',4.075], ['20080723',3.931], ['20080724',3.998], ['20080725',3.972], ['20080728',4.224], ['20080729',3.952], ['20080730',3.895], ['20080731',3.747], ['20080801',3.747], ['20080804',3.639], ['20080805',3.480], ['20080806',3.511], ['20080807',3.536], ['20080808',3.152], ['20080811',2.808], ['20080812',2.757], ['20080813',2.752], ['20080814',2.772], ['20080815',2.767], ['20080818',2.490], ['20080819',2.511], ['20080820',2.793], ['20080821',2.603], ['20080822',2.572], ['20080825',2.624], ['20080826',2.413], ['20080827',2.383], ['20080828',2.449], ['20080829',2.593], ['20080901',2.521], ['20080902',2.531], ['20080903',2.526], ['20080904',2.608], ['20080905',2.649], ['20080908',2.352], ['20080909',2.213], ['20080911',2.054], ['20080912',2.054], ['20080916',2.008], ['20080917',1.947], ['20080918',1.839], ['20080919',2.054], ['20080922',2.142], ['20080923',1.895], ['20080924',1.921], ['20080925',1.947], ['20080926',1.947], ['20081006',1.818], ['20081007',1.834], ['20081008',1.742], ['20081009',1.726], ['20081010',1.552], ['20081013',1.567], ['20081014',1.536], ['20081015',1.511], ['20081016',1.434], ['20081017',1.465], ['20081020',1.521], ['20081021',1.542], ['20081022',1.521], ['20081023',1.511], ['20081024',1.618], ['20081027',1.424], ['20081028',1.470], ['20081029',1.434], ['20081030',1.444], ['20081031',1.418], ['20081103',1.388], ['20081104',1.388], ['20081105',1.449], ['20081106',1.418], ['20081107',1.470], ['20081111',1.547], ['20081112',1.603], ['20081113',1.670], ['20081114',1.736], ['20081117',1.942], ['20081118',2.018], ['20081119',2.126], ['20081120',1.962], ['20081121',1.993], ['20081124',1.813], ['20081125',1.731], ['20081126',1.721], ['20081127',1.818], ['20081128',2.024], ['20081201',2.157], ['20081202',2.090], ['20081203',2.229], ['20081204',2.177], ['20081205',2.290], ['20081208',2.352], ['20081209',2.213], ['20081210',2.465], ['20081211',2.347], ['20081212',2.131], ['20081215',2.142], ['20081216',2.388], ['20081217',2.347], ['20081218',2.424], ['20081219',2.695], ['20081222',2.808], ['20081223',2.495], ['20081224',2.495], ['20081225',2.495], ['20081226',2.506], ['20081229',2.316], ['20081230',2.254], ['20081231',2.254], ['20090105',2.357], ['20090106',2.459], ['20090107',2.485], ['20090108',2.388], ['20090109',2.572], ['20090112',2.588], ['20090113',2.383], ['20090114',2.511], ['20090115',2.577], ['20090116',2.670], ['20090119',2.834], ['20090120',2.736], ['20090121',2.639], ['20090122',2.654], ['20090123',2.562], ['20090202',2.644], ['20090203',2.711], ['20090204',2.859], ['20090205',2.767], ['20090206',2.885], ['20090209',3.024], ['20090210',3.142], ['20090211',3.280], ['20090212',3.388], ['20090213',3.639], ['20090216',3.567], ['20090217',3.285], ['20090218',3.188], ['20090219',3.229], ['20090220',3.336], ['20090223',3.459], ['20090224',3.234], ['20090225',3.311], ['20090226',3.101], ['20090227',2.762], ['20090302',2.890], ['20090303',2.906], ['20090304',3.085], ['20090305',3.424], ['20090306',3.280], ['20090309',3.111], ['20090310',3.290], ['20090311',3.439], ['20090312',3.326], ['20090313',3.198], ['20090316',3.203], ['20090317',3.372], ['20090318',3.357], ['20090319',3.393], ['20090320',3.418], ['20090323',3.459], ['20090324',3.408], ['20090325',3.234], ['20090326',3.290], ['20090327',3.459], ['20090330',3.495], ['20090331',3.470], ['20090401',3.547], ['20090402',3.526], ['20090403',3.398], ['20090407',3.434], ['20090408',3.295], ['20090409',3.321], ['20090410',3.408], ['20090413',3.516], ['20090414',3.567], ['20090415',3.639], ['20090416',3.577], ['20090417',3.716], ['20090420',4.121], ['20090421',4.090], ['20090422',3.818], ['20090423',3.777], ['20090424',3.813], ['20090427',3.562], ['20090428',3.567], ['20090429',3.695], ['20090430',3.813], ['20090504',4.085], ['20090505',4.101], ['20090506',4.131], ['20090507',4.244], ['20090508',4.080], ['20090511',3.783], ['20090512',3.921], ['20090514',3.957], ['20090515',4.208], ['20090518',4.301], ['20090519',4.326], ['20090520',4.418], ['20090521',4.203], ['20090522',4.157], ['20090525',4.167], ['20090526',4.306], ['20090527',4.249], ['20090601',4.301], ['20090602',4.326], ['20090603',4.413], ['20090604',4.280], ['20090605',4.203], ['20090608',4.357], ['20090609',4.490], ['20090610',4.449], ['20090611',4.331], ['20090612',4.218], ['20090615',4.326], ['20090616',4.352], ['20090617',4.372], ['20090618',4.675], ['20090619',4.501], ['20090622',4.983], ['20090623',5.054], ['20090624',5.142], ['20090625',5.511], ['20090626',5.685], ['20090629',5.495], ['20090630',5.362], ['20090701',5.362], ['20090702',5.459], ['20090703',5.562], ['20090706',5.357], ['20090707',5.459], ['20090708',5.680], ['20090709',6.049], ['20090710',5.839], ['20090713',5.885], ['20090714',5.824], ['20090715',5.854], ['20090716',6.213], ['20090717',6.444], ['20090720',6.429], ['20090721',6.290], ['20090722',6.695], ['20090723',6.439], ['20090724',6.188], ['20090727',6.177], ['20090728',6.275], ['20090729',6.234], ['20090730',6.162], ['20090731',6.403], ['20090803',7.054], ['20090804',7.034], ['20090805',6.757], ['20090806',6.475], ['20090807',6.506], ['20090810',6.639], ['20090811',6.783], ['20090812',6.259], ['20090813',6.070], ['20090814',5.736], ['20090817',5.229], ['20090818',5.454], ['20090819',5.275], ['20090820',5.649], ['20090821',6.059], ['20090824',6.044], ['20090825',6.254], ['20090826',6.398], ['20090827',6.434], ['20090828',6.039], ['20090831',6.070], ['20090901',6.495], ['20090902',6.659], ['20090903',6.798], ['20090904',6.706], ['20090907',6.936], ['20090908',6.839], ['20090909',6.865], ['20090910',6.813], ['20090911',7.213], ['20090914',7.357], ['20090915',7.265], ['20090916',7.172], ['20090917',7.218], ['20090918',6.859], ['20090921',6.849], ['20090922',6.690], ['20090923',6.762], ['20090924',6.798], ['20090925',6.788], ['20090928',6.690], ['20090929',6.701], ['20090930',6.859], ['20091009',7.080], ['20091012',7.208], ['20091013',7.475], ['20091014',7.388], ['20091015',7.254], ['20091016',7.439], ['20091019',7.506], ['20091020',7.490], ['20091021',7.306], ['20091022',7.280], ['20091023',7.306], ['20091026',7.726], ['20091027',7.357], ['20091028',7.449], ['20091029',7.090], ['20091030',7.085], ['20091102',7.121], ['20091103',7.475], ['20091104',7.511], ['20091105',7.567], ['20091106',7.577], ['20091109',7.577], ['20091110',7.921], ['20091111',7.813], ['20091112',7.808], ['20091113',7.624], ['20091116',7.808], ['20091117',7.706], ['20091118',7.844], ['20091119',8.080], ['20091120',7.921], ['20091123',7.942], ['20091124',7.413], ['20091125',7.629], ['20091126',7.090], ['20091127',6.931], ['20091130',7.244], ['20091201',7.444], ['20091202',7.495], ['20091203',7.562], ['20091204',7.126], ['20091207',7.234], ['20091208',7.685], ['20091209',7.331], ['20091210',7.459], ['20091211',7.362], ['20091214',7.070], ['20091215',7.049], ['20091216',7.003], ['20091217',6.742], ['20091218',6.506], ['20091221',6.639], ['20091222',6.393], ['20091223',6.521], ['20091224',6.726], ['20091225',6.772], ['20091228',6.854], ['20091229',6.752], ['20091230',6.618], ['20091231',6.890], ['20100104',7.013], ['20100105',7.044], ['20100106',7.044], ['20100107',6.793], ['20100108',6.890], ['20100111',6.824], ['20100112',7.080], ['20100113',7.259], ['20100114',7.526], ['20100115',7.634], ['20100118',7.983], ['20100119',7.906], ['20100120',7.485], ['20100121',7.803], ['20100122',7.408], ['20100125',7.326], ['20100126',7.049], ['20100127',6.983], ['20100128',7.280], ['20100129',7.193], ['20100201',7.280], ['20100202',7.167], ['20100203',7.024], ['20100204',6.870], ['20100205',6.588], ['20100208',6.659], ['20100209',6.706], ['20100210',6.767], ['20100211',6.752], ['20100212',6.793], ['20100222',6.813], ['20100223',6.813], ['20100224',7.039], ['20100225',7.085], ['20100226',7.054], ['20100301',7.193], ['20100302',7.244], ['20100303',7.275], ['20100304',7.024], ['20100305',7.024], ['20100308',7.049], ['20100309',7.070], ['20100310',7.203], ['20100311',7.280], ['20100312',7.208], ['20100315',7.003], ['20100316',7.198], ['20100317',7.439], ['20100318',7.398], ['20100319',7.577], ['20100322',7.639], ['20100323',7.618], ['20100324',7.721], ['20100325',7.403], ['20100326',7.495], ['20100329',7.367], ['20100330',7.177], ['20100331',7.254], ['20100401',7.475], ['20100402',7.331], ['20100406',7.321], ['20100407',7.434], ['20100408',7.434], ['20100409',7.444], ['20100412',7.367], ['20100413',7.372], ['20100414',7.306], ['20100415',7.029], ['20100416',7.024], ['20100419',6.716], ['20100420',6.762], ['20100421',6.926], ['20100422',6.901], ['20100426',6.675], ['20100427',6.352], ['20100428',6.280], ['20100429',5.839], ['20100430',5.475], ['20100504',5.475], ['20100505',5.644], ['20100506',5.301], ['20100507',5.244], ['20100510',5.362], ['20100511',5.203], ['20100512',5.029], ['20100513',5.126], ['20100514',5.142], ['20100517',4.777], ['20100518',4.726], ['20100519',4.649], ['20100520',4.685], ['20100521',4.772], ['20100524',4.983], ['20100525',4.895], ['20100526',4.952], ['20100527',5.080], ['20100528',5.131], ['20100531',4.880], ['20100601',4.711], ['20100602',4.757], ['20100603',4.701], ['20100604',4.777], ['20100607',5.126], ['20100608',5.454], ['20100609',5.429], ['20100610',5.459], ['20100611',5.244], ['20100618',4.972], ['20100621',5.259], ['20100622',5.357], ['20100623',5.270], ['20100624',5.147], ['20100625',5.034], ['20100628',5.218], ['20100629',5.465], ['20100630',5.203], ['20100701',5.413], ['20100702',5.654], ['20100705',5.526], ['20100706',5.767], ['20100707',5.777], ['20100708',5.629], ['20100709',5.757], ['20100712',5.690], ['20100713',5.567], ['20100714',5.624], ['20100715',5.342], ['20100716',5.306], ['20100719',5.454], ['20100720',5.624], ['20100721',5.526], ['20100722',5.752], ['20100723',5.685], ['20100726',5.716], ['20100727',5.562], ['20100728',5.762], ['20100729',5.880], ['20100730',5.777], ['20100802',5.957], ['20100803',5.834], ['20100804',5.844], ['20100805',5.762], ['20100806',5.916], ['20100809',6.003], ['20100810',5.865], ['20100811',5.834], ['20100812',5.567], ['20100813',5.685], ['20100816',5.813], ['20100817',5.875], ['20100818',5.921], ['20100819',6.018], ['20100820',5.752], ['20100823',5.731], ['20100824',5.798], ['20100825',5.654], ['20100826',5.690], ['20100827',5.603], ['20100830',5.752], ['20100831',5.834], ['20100901',5.675], ['20100902',5.757], ['20100903',5.818], ['20100906',5.972], ['20100907',5.972], ['20100908',6.018], ['20100909',6.090], ['20100910',6.413], ['20100913',6.311], ['20100914',6.152], ['20100915',6.034], ['20100916',5.844], ['20100917',5.772], ['20100920',5.767], ['20100921',5.829], ['20100927',5.931], ['20100928',5.572], ['20100929',5.362], ['20100930',5.434], ['20101008',5.547], ['20101011',5.629], ['20101012',5.675], ['20101013',5.752], ['20101014',5.439], ['20101015',5.454], ['20101018',5.347], ['20101019',5.547], ['20101020',5.552], ['20101021',5.690], ['20101022',5.665], ['20101025',5.854], ['20101026',6.034], ['20101027',5.829], ['20101028',5.885], ['20101029',5.813], ['20101101',5.977], ['20101102',6.101], ['20101103',5.921], ['20101104',6.075], ['20101105',6.090], ['20101108',6.224], ['20101109',6.198], ['20101110',6.383], ['20101111',6.239], ['20101112',5.767], ['20101115',5.952], ['20101116',5.818], ['20101117',5.547], ['20101118',5.588], ['20101119',5.716], ['20101123',5.675], ['20101124',5.936], ['20101125',5.977], ['20101126',6.090], ['20101129',6.162], ['20101130',5.911], ['20101201',5.947], ['20101202',6.142], ['20101203',6.029], ['20101206',5.875], ['20101207',5.993], ['20101208',5.977], ['20101209',5.747], ['20101210',5.793], ['20101213',5.967], ['20101214',5.988], ['20101216',6.034], ['20101217',6.029], ['20101220',5.988], ['20101221',6.167], ['20101222',6.075], ['20101223',5.983], ['20101224',5.859], ['20101227',5.701], ['20101228',5.439], ['20101229',5.501], ['20101230',5.583], ['20101231',5.701], ['20110104',5.742], ['20110105',5.875], ['20110106',5.972], ['20110107',5.947], ['20110110',6.065], ['20110118',5.588], ['20110119',6.003], ['20110120',5.988], ['20110121',6.244], ['20110124',6.013], ['20110125',5.598], ['20110126',5.675], ['20110127',5.742], ['20110128',5.859], ['20110131',5.895], ['20110201',5.762], ['20110209',6.213], ['20110210',6.577], ['20110214',6.593], ['20110215',6.613], ['20110216',6.757], ['20110217',6.716], ['20110218',6.818], ['20110221',7.075], ['20110222',6.695], ['20110223',6.988], ['20110224',7.121], ['20110225',7.075], ['20110301',7.813], ['20110302',7.993], ['20110303',7.706], ['20110304',7.577], ['20110307',7.972], ['20110308',7.844], ['20110309',7.957], ['20110310',7.783], ['20110311',7.977], ['20110314',8.244], ['20110315',7.859], ['20110316',7.859], ['20110317',7.429], ['20110318',7.295], ['20110321',7.408], ['20110323',7.588], ['20110324',7.501], ['20110325',7.859], ['20110328',8.377], ['20110329',8.372], ['20110330',8.126], ['20110331',7.536], ['20110401',7.690], ['20110406',7.803], ['20110407',7.972], ['20110408',7.988], ['20110411',7.742], ['20110412',7.593], ['20110413',7.680], ['20110414',7.977], ['20110415',8.152], ['20110418',8.603], ['20110419',8.598], ['20110420',8.172], ['20110421',8.157], ['20110422',7.952], ['20110425',7.701], ['20110426',7.639], ['20110427',7.506], ['20110428',6.998], ['20110429',7.126], ['20110503',7.429], ['20110504',6.880], ['20110505',6.901], ['20110506',6.829], ['20110509',6.818], ['20110510',7.049], ['20110511',7.152], ['20110512',6.803], ['20110513',6.870], ['20110516',7.059], ['20110517',7.003], ['20110518',7.177], ['20110519',6.962], ['20110520',7.059], ['20110523',6.490], ['20110524',6.480], ['20110525',6.511], ['20110526',6.516], ['20110527',6.213], ['20110530',6.085], ['20110531',6.203], ['20110601',6.306], ['20110602',6.075], ['20110603',6.188], ['20110607',6.321], ['20110608',6.480], ['20110609',6.172], ['20110610',6.254], ['20110613',6.193], ['20110614',6.398], ['20110615',6.290], ['20110616',6.065], ['20110617',5.931], ['20110620',5.793], ['20110621',5.901], ['20110622',5.901], ['20110623',6.029], ['20110624',6.218], ['20110627',6.367], ['20110628',6.434], ['20110629',6.342], ['20110630',6.567], ['20110701',6.495], ['20110704',6.588], ['20110705',6.639], ['20110706',6.798], ['20110707',6.659], ['20110708',6.665], ['20110711',6.685], ['20110712',6.475], ['20110713',6.659], ['20110718',6.531], ['20110719',6.521], ['20110720',6.572], ['20110721',6.567], ['20110722',6.418], ['20110725',6.013], ['20110726',5.983], ['20110727',6.095], ['20110728',6.008], ['20110729',6.177], ['20110801',6.229], ['20110802',6.393], ['20110803',6.475], ['20110804',6.459], ['20110805',6.352], ['20110808',5.798], ['20110809',5.885], ['20110810',6.008], ['20110811',6.029], ['20110812',6.285], ['20110815',6.465], ['20110816',6.439], ['20110817',6.408], ['20110818',6.126], ['20110819',6.049], ['20110822',6.090], ['20110823',6.131], ['20110824',6.034], ['20110825',6.126], ['20110826',6.306], ['20110829',6.331], ['20110830',6.424], ['20110831',6.311], ['20110901',6.326], ['20110902',6.501], ['20110905',6.542], ['20110906',6.588], ['20110907',6.962], ['20110908',6.747], ['20110909',6.762], ['20110913',6.147], ['20110914',6.070], ['20110916',6.131], ['20110919',5.844], ['20110920',5.906], ['20110921',6.075], ['20110922',5.885], ['20110923',5.757], ['20110926',5.767], ['20110927',5.859], ['20110928',5.757], ['20110929',5.588], ['20110930',5.721], ['20111010',5.911], ['20111011',5.926], ['20111012',6.193], ['20111013',6.203], ['20111014',6.198], ['20111017',6.290], ['20111018',5.962], ['20111019',5.752], ['20111020',5.618], ['20111021',5.239], ['20111024',4.870], ['20111025',4.972], ['20111026',5.018], ['20111027',4.885], ['20111028',5.018], ['20111031',5.095], ['20111101',5.244], ['20111102',5.290], ['20111103',5.290], ['20111104',5.249], ['20111107',5.306], ['20111108',5.095], ['20111109',5.121], ['20111110',5.029], ['20111111',5.049], ['20111114',5.177], ['20111115',5.285], ['20111116',5.111], ['20111117',5.018], ['20111118',4.813], ['20111121',4.849], ['20111122',4.844], ['20111123',4.839], ['20111124',4.757], ['20111125',4.762], ['20111128',4.772], ['20111129',4.880], ['20111130',4.501], ['20111201',4.572], ['20111202',4.449], ['20111205',4.501], ['20111206',4.490], ['20111207',4.388], ['20111208',4.285], ['20111209',4.188], ['20111212',4.121], ['20111213',3.798], ['20111214',3.654], ['20111215',3.485], ['20111216',3.603], ['20111219',3.593], ['20111220',3.644], ['20111221',3.536], ['20111222',3.413], ['20111223',3.439], ['20111228',3.347], ['20111229',3.280], ['20111230',3.424], ['20120104',3.254], ['20120105',3.024], ['20120106',3.003], ['20120109',3.213], ['20120110',3.383], ['20120111',3.408], ['20120112',3.413], ['20120116',3.049], ['20120117',3.285], ['20120118',3.177], ['20120119',3.244], ['20120120',3.259], ['20120130',3.239], ['20120131',3.152], ['20120201',3.152], ['20120202',3.213], ['20120203',3.342], ['20120206',3.706], ['20120207',3.701], ['20120208',3.752], ['20120209',3.772], ['20120210',3.859], ['20120214',3.767], ['20120215',3.834], ['20120216',3.880], ['20120217',4.101], ['20120220',4.049], ['20120221',4.485], ['20120222',4.552], ['20120223',4.531], ['20120224',4.480], ['20120227',4.439], ['20120228',4.295], ['20120229',4.177], ['20120301',4.198], ['20120302',4.285], ['20120305',4.203], ['20120306',4.301], ['20120307',4.342], ['20120308',4.377], ['20120309',4.367], ['20120312',4.413], ['20120313',4.495], ['20120314',4.101], ['20120315',3.931], ['20120316',3.993], ['20120319',4.044], ['20120320',3.906], ['20120321',3.942], ['20120322',3.926], ['20120323',3.829], ['20120326',3.685], ['20120327',3.680], ['20120328',3.383], ['20120329',3.326], ['20120330',3.270], ['20120405',3.383], ['20120406',3.480], ['20120409',3.434], ['20120410',3.475], ['20120411',3.639], ['20120412',3.675], ['20120416',3.665], ['20120417',3.624], ['20120418',3.706], ['20120419',3.747], ['20120420',3.767], ['20120423',3.629], ['20120424',3.526], ['20120426',3.911], ['20120427',3.988], ['20120502',4.177], ['20120503',4.136], ['20120504',4.198], ['20120507',4.188], ['20120508',4.203], ['20120509',4.152], ['20120510',4.357], ['20120511',4.229], ['20120514',4.131], ['20120515',4.080], ['20120516',4.162], ['20120517',4.239], ['20120518',4.075], ['20120521',4.095], ['20120522',4.403], ['20120523',4.418], ['20120524',4.362], ['20120525',4.398], ['20120528',4.418], ['20120529',4.459], ['20120530',4.408], ['20120531',4.475], ['20120601',4.547], ['20120604',4.408], ['20120605',4.536], ['20120606',4.721], ['20120607',4.701], ['20120608',4.793], ['20120611',4.829], ['20120612',4.695], ['20120613',4.731], ['20120614',4.572], ['20120615',4.706], ['20120618',4.706], ['20120619',4.747], ['20120620',4.701], ['20120621',4.434], ['20120625',4.177], ['20120626',4.218], ['20120628',4.116], ['20120629',4.126], ['20120702',4.090], ['20120703',4.126], ['20120704',4.280], ['20120705',4.306], ['20120706',4.259], ['20120709',3.993], ['20120710',3.824], ['20120711',3.895], ['20120712',4.003], ['20120713',3.906], ['20120716',3.757], ['20120717',3.808], ['20120718',3.829], ['20120719',3.967], ['20120720',3.916], ['20120723',3.967], ['20120724',3.988], ['20120725',3.859], ['20120726',3.824], ['20120727',3.829], ['20120730',3.711], ['20120731',3.752], ['20120801',3.783], ['20120802',3.880], ['20120803',3.947], ['20120806',4.039], ['20120807',4.029], ['20120808',4.039], ['20120809',4.070], ['20120810',3.998], ['20120813',3.998], ['20120814',4.049], ['20120815',3.921], ['20120816',3.854], ['20120817',3.901], ['20120820',3.895], ['20120821',3.967], ['20120822',3.998], ['20120823',4.080], ['20120824',3.983], ['20120827',3.829], ['20120828',4.029], ['20120829',3.972], ['20120830',3.834], ['20120831',3.818], ['20120903',3.865], ['20120904',3.818], ['20120905',3.890], ['20120906',3.952], ['20120907',4.111], ['20120910',4.147], ['20120911',4.167], ['20120912',4.301], ['20120913',4.172], ['20120914',4.111], ['20120917',4.183], ['20120918',4.357], ['20120919',4.347], ['20120920',4.085], ['20120921',4.136], ['20120924',3.947], ['20120925',3.849], ['20120926',3.747], ['20120927',3.931], ['20120928',3.962], ['20121008',3.942], ['20121009',4.090], ['20121010',4.142], ['20121011',4.075], ['20121012',4.213], ['20121015',4.562], ['20121016',4.562], ['20121017',4.557], ['20121018',4.603], ['20121019',4.490], ['20121022',4.547], ['20121023',4.413], ['20121024',4.362], ['20121025',4.398], ['20121026',4.198], ['20121029',4.234], ['20121030',4.244], ['20121031',4.331], ['20121101',4.377], ['20121102',4.434], ['20121105',4.326], ['20121106',4.188], ['20121107',4.198], ['20121108',3.962], ['20121109',3.921], ['20121112',3.993], ['20121113',3.880], ['20121114',3.916], ['20121115',3.803], ['20121116',3.798], ['20121119',3.921], ['20121120',3.865], ['20121121',3.942], ['20121122',3.895], ['20121123',3.854], ['20121126',3.906], ['20121127',3.706], ['20121128',3.526], ['20121129',3.408], ['20121130',3.475], ['20121203',3.270], ['20121204',3.362], ['20121205',3.516], ['20121206',3.485], ['20121207',3.598], ['20121210',3.685], ['20121211',3.624], ['20121212',3.613], ['20121213',3.665], ['20121214',3.865], ['20121217',3.870], ['20121218',3.859], ['20121219',3.865], ['20121220',3.844], ['20121221',3.870], ['20121224',3.977], ['20121225',4.095], ['20121226',4.229], ['20121227',4.101], ['20121228',4.147], ['20121231',4.152], ['20130104',4.111], ['20130107',4.285], ['20130108',4.316], ['20130109',4.280], ['20130110',4.280], ['20130111',4.106], ['20130114',4.383], ['20130115',4.501], ['20130116',4.547], ['20130117',4.511], ['20130118',4.562], ['20130121',5.049], ['20130122',5.398], ['20130123',5.357], ['20130124',5.049], ['20130125',5.106], ['20130128',5.224], ['20130129',5.244], ['20130130',5.111], ['20130131',4.967], ['20130201',4.977], ['20130204',5.059], ['20130205',5.162], ['20130206',5.234], ['20130207',5.254], ['20130208',5.316], ['20130218',5.336], ['20130219',5.090], ['20130220',5.136], ['20130221',4.849], ['20130222',4.721], ['20130225',4.803], ['20130226',4.742], ['20130227',4.808], ['20130228',4.890], ['20130301',5.018], ['20130304',5.157], ['20130305',5.234], ['20130306',5.531], ['20130307',5.424], ['20130308',5.501], ['20130311',5.290], ['20130312',4.865], ['20130313',4.844], ['20130314',4.947], ['20130315',4.854], ['20130318',5.167], ['20130319',5.095], ['20130320',5.275], ['20130321',5.311], ['20130322',5.398], ['20130325',5.942], ['20130326',5.788], ['20130327',5.793], ['20130328',5.434], ['20130329',5.362], ['20130401',5.521], ['20130402',5.362], ['20130403',5.136], ['20130408',5.290], ['20130409',5.434], ['20130410',5.224], ['20130411',5.152], ['20130412',5.188], ['20130415',5.208], ['20130416',5.301], ['20130417',5.418], ['20130418',5.454], ['20130419',5.654], ['20130422',5.675], ['20130423',5.413], ['20130424',5.526], ['20130425',5.680], ['20130426',5.080], ['20130502',4.542], ['20130503',4.552], ['20130506',4.618], ['20130507',4.680], ['20130508',4.624], ['20130509',4.747], ['20130510',4.793], ['20130513',4.972], ['20130514',4.865], ['20130515',4.803], ['20130516',4.842], ['20130517',4.857], ['20130520',4.865], ['20130521',4.903], ['20130522',5.026], ['20130523',4.934], ['20130524',5.203], ['20130527',5.249], ['20130528',5.180], ['20130529',5.157], ['20130530',5.249], ['20130531',5.126], ['20130603',5.072], ['20130604',4.911], ['20130605',4.888], ['20130606',4.834], ['20130607',4.703], ['20130613',4.795], ['20130614',4.772], ['20130617',4.757], ['20130618',4.649], ['20130619',4.449], ['20130620',4.203], ['20130621',4.142], ['20130624',3.718], ['20130625',3.595], ['20130626',3.618], ['20130627',3.580], ['20130628',3.818], ['20130701',3.818], ['20130702',3.811], ['20130703',3.695], ['20130704',3.726], ['20130705',3.703], ['20130708',3.457], ['20130709',3.488], ['20130710',3.611], ['20130711',3.711], ['20130712',3.703], ['20130715',3.742], ['20130716',3.780], ['20130717',3.788], ['20130718',3.695], ['20130719',3.534], ['20130722',3.703], ['20130723',3.780], ['20130724',3.818], ['20130725',3.742], ['20130726',3.695], ['20130729',3.680], ['20130730',3.657], ['20130731',3.665], ['20130801',3.772], ['20130802',3.757], ['20130805',4.065], ['20130806',4.088], ['20130807',4.003], ['20130808',4.080], ['20130809',4.072], ['20130812',4.111], ['20130813',4.288], ['20130814',4.257], ['20130815',4.095], ['20130816',4.011], ['20130819',4.072], ['20130820',4.103], ['20130821',4.165], ['20130822',4.118], ['20130823',4.065], ['20130826',4.149], ['20130827',4.149], ['20130828',4.034], ['20130829',4.026], ['20130830',3.934], ['20130902',3.972], ['20130903',4.042], ['20130904',4.042], ['20130905',4.026], ['20130906',3.972], ['20130909',4.003], ['20130910',4.042], ['20130911',4.172], ['20130912',4.103], ['20130913',4.142], ['20130916',4.165], ['20130917',4.611], ['20130918',4.457], ['20130923',4.534], ['20130924',4.442], ['20130925',4.503], ['20130926',4.388], ['20130927',4.272], ['20130930',4.388], ['20131008',4.349], ['20131009',4.380], ['20131010',4.303], ['20131011',4.357], ['20131014',4.534], ['20131015',4.526], ['20131016',4.380], ['20131017',4.426], ['20131018',4.557], ['20131021',4.626], ['20131022',4.534], ['20131023',4.326], ['20131024',4.365], ['20131025',4.234], ['20131028',4.218], ['20131029',3.942], ['20131030',3.988], ['20131031',4.072], ['20131101',4.034], ['20131104',4.049], ['20131105',4.057], ['20131106',4.072], ['20131107',3.926], ['20131108',3.857], ['20131111',3.872], ['20131112',3.949], ['20131113',3.865], ['20131114',3.865], ['20131115',3.942], ['20131118',4.034], ['20131119',4.080], ['20131120',4.142], ['20131121',4.080], ['20131122',4.511], ['20131125',4.357], ['20131126',4.372], ['20131127',4.442], ['20131128',4.411], ['20131129',4.357], ['20131202',4.065], ['20131203',4.218], ['20131204',4.665], ['20131205',4.895], ['20131206',4.911], ['20131209',4.972], ['20131210',4.865], ['20131211',4.772], ['20131212',4.742], ['20131213',4.826], ['20131216',4.618], ['20131217',4.518], ['20131218',4.572], ['20131219',4.595], ['20131220',4.734], ['20131223',4.665], ['20131224',4.680], ['20131225',4.680], ['20131226',4.357], ['20131227',4.357], ['20131230',4.434], ['20131231',4.388], ['20140102',4.442], ['20140103',4.565], ['20140106',4.426], ['20140107',4.480], ['20140108',4.511], ['20140109',4.295], ['20140110',4.126], ['20140113',3.972], ['20140114',4.049], ['20140115',4.065], ['20140116',4.111], ['20140117',4.149], ['20140120',4.149], ['20140121',4.249], ['20140122',4.342], ['20140123',4.311], ['20140124',4.318], ['20140127',4.311], ['20140128',4.311], ['20140129',4.342], ['20140130',4.311], ['20140207',4.349], ['20140210',4.495], ['20140211',4.488], ['20140212',4.549], ['20140213',4.457], ['20140214',4.488], ['20140217',4.595], ['20140218',4.618], ['20140219',4.611], ['20140220',4.426], ['20140221',4.449], ['20140224',4.411], ['20140225',4.042], ['20140226',3.949], ['20140227',3.934], ['20140228',3.857], ['20140303',3.911], ['20140304',3.926], ['20140305',3.957], ['20140306',3.911], ['20140307',3.942], ['20140310',3.872], ['20140311',3.949], ['20140312',3.911], ['20140313',4.018], ['20140314',3.972], ['20140317',4.003], ['20140318',4.034], ['20140319',4.103], ['20140320',3.988], ['20140321',4.065], ['20140324',4.072], ['20140325',4.065], ['20140326',4.072], ['20140327',4.003], ['20140328',3.934], ['20140331',3.649], ['20140401',3.672], ['20140402',3.688], ['20140403',3.703], ['20140404',3.711], ['20140408',3.757], ['20140409',3.757], ['20140410',3.772], ['20140411',3.749], ['20140414',3.780], ['20140415',3.757], ['20140416',3.772], ['20140417',3.703], ['20140418',3.726], ['20140421',3.742], ['20140422',3.803], ['20140423',3.772], ['20140424',3.718], ['20140425',3.642], ['20140428',3.403], ['20140429',3.418], ['20140430',3.449], ['20140505',3.495], ['20140506',3.542], ['20140507',3.526], ['20140508',3.526], ['20140509',3.488], ['20140512',3.540], ['20140513',3.560], ['20140514',3.530], ['20140515',3.490], ['20140516',3.490], ['20140519',3.500], ['20140520',3.490], ['20140521',3.490], ['20140522',3.550], ['20140523',3.510], ['20140526',3.510], ['20140527',3.430], ['20140528',3.440], ['20140529',3.410], ['20140530',3.390], ['20140603',3.380], ['20140604',3.320], ['20140605',3.360], ['20140606',3.330], ['20140609',3.320], ['20140610',3.350], ['20140611',3.350], ['20140612',3.400], ['20140613',3.420], ['20140616',3.430], ['20140617',3.380], ['20140618',3.400], ['20140619',3.270], ['20140620',3.250], ['20140623',3.280], ['20140624',3.310], ['20140625',3.280], ['20140626',3.310], ['20140627',3.380], ['20140630',3.410], ['20140701',3.410], ['20140702',3.430], ['20140703',3.450], ['20140704',3.450], ['20140707',3.390], ['20140708',3.440], ['20140709',3.370], ['20140710',3.400], ['20140711',3.460], ['20140714',3.510], ['20140715',3.550], ['20140716',3.540], ['20140717',3.530], ['20140718',3.530], ['20140721',3.510], ['20140722',3.540], ['20140723',3.520], ['20140724',3.530], ['20140725',3.580], ['20140728',3.630], ['20140729',3.680], ['20140730',3.680], ['20140731',3.740], ['20140801',3.700], ['20140804',3.800], ['20140805',3.800], ['20140806',3.810], ['20140807',3.750], ['20140808',3.800], ['20140811',3.940], ['20140812',3.960], ['20140813',4.060], ['20140814',4.080], ['20140815',4.110], ['20140818',4.140], ['20140819',4.100], ['20140820',4.110], ['20140821',4.070], ['20140822',4.150], ['20140825',4.100], ['20140826',3.990], ['20140827',4.050], ['20140828',4.070], ['20140829',4.190], ['20140901',4.300], ['20140902',4.290], ['20140903',4.340], ['20140904',4.350], ['20140905',4.370], ['20140909',4.360], ['20140910',4.460], ['20140911',4.440], ['20140912',4.510], ['20140915',4.660], ['20140916',4.540], ['20140917',4.720], ['20140918',4.750], ['20140919',4.780], ['20140922',4.710], ['20140923',4.740], ['20140924',4.780], ['20140925',4.750], ['20140926',4.690], ['20140929',4.790], ['20140930',4.830], ['20141008',5.020], ['20141009',5.030], ['20141010',5.000], ['20141013',4.940], ['20141014',4.890], ['20141015',4.910], ['20141016',4.800], ['20141017',4.650], ['20141020',4.840], ['20141021',4.990], ['20141022',4.940], ['20141023',4.740], ['20141024',4.800], ['20141027',4.760], ['20141028',4.920], ['20141029',4.950], ['20141030',5.000], ['20141031',4.990], ['20141103',4.970], ['20141104',4.960], ['20141105',5.140], ['20141106',5.210], ['20141107',4.980], ['20141110',4.990], ['20141111',4.750], ['20141112',4.900], ['20141113',4.910], ['20141114',4.840], ['20141117',4.870], ['20141118',4.870], ['20141119',4.970], ['20141120',5.030], ['20141121',5.030], ['20141124',5.040], ['20141125',5.110], ['20141126',5.090], ['20141127',5.100], ['20141128',5.320], ['20141201',5.210], ['20141202',5.350], ['20141203',5.420], ['20141204',5.540], ['20141205',5.200], ['20141208',5.230], ['20141209',4.890], ['20141210',5.060], ['20141211',5.070], ['20141212',5.160], ['20141215',5.310], ['20141216',5.290], ['20141217',5.380], ['20141218',5.360], ['20141219',5.160], ['20141222',4.850], ['20141223',4.730], ['20141224',4.900], ['20141225',5.100], ['20141226',5.060], ['20141229',4.900], ['20141230',4.970], ['20141231',4.980], ['20150105',5.070], ['20150106',5.040], ['20150107',5.210], ['20150108',5.220], ['20150109',5.180], ['20150112',5.060], ['20150113',5.060], ['20150114',5.130], ['20150115',5.290], ['20150116',5.560], ['20150119',5.610], ['20150120',6.190], ['20150121',6.130], ['20150122',6.260], ['20150123',6.130], ['20150126',6.420], ['20150127',6.430], ['20150128',6.310], ['20150129',6.410], ['20150130',6.680], ['20150202',6.660], ['20150203',6.530], ['20150204',6.260], ['20150205',6.270], ['20150206',6.180], ['20150209',5.880], ['20150210',6.240], ['20150211',6.240], ['20150212',6.430], ['20150213',6.480], ['20150216',6.660], ['20150217',6.720], ['20150225',6.640], ['20150226',6.610], ['20150227',6.630], ['20150302',6.600], ['20150303',6.510], ['20150304',7.180], ['20150305',7.180], ['20150306',7.860], ['20150309',7.820], ['20150310',7.820], ['20150311',8.620], ['20150312',8.330], ['20150313',8.760], ['20150316',8.910], ['20150317',8.730], ['20150318',8.610], ['20150319',8.870], ['20150320',8.790], ['20150323',8.760], ['20150324',8.510], ['20150325',8.690], ['20150326',9.580], ['20150327',9.580], ['20150330',9.560], ['20150331',9.480], ['20150401',9.570], ['20150402',10.090], ['20150403',10.020], ['20150407',10.280], ['20150408',10.560], ['20150409',11.060], ['20150410',11.720], ['20150413',12.910], ['20150414',13.570], ['20150415',12.380], ['20150416',12.410], ['20150417',12.280], ['20150420',11.340], ['20150421',12.130], ['20150422',12.210], ['20150423',12.350], ['20150424',13.190], ['20150427',13.230], ['20150428',12.590], ['20150429',13.870], ['20150430',14.040], ['20150504',13.470], ['20150505',12.760], ['20150506',12.480], ['20150507',11.210], ['20150508',11.480], ['20150511',11.950], ['20150512',12.370], ['20150513',12.200], ['20150514',12.720], ['20150515',12.860], ['20150518',12.980], ['20150519',12.940], ['20150520',13.440], ['20150521',13.770], ['20150522',13.890], ['20150525',14.940], ['20150526',15.070], ['20150527',14.840], ['20150528',13.600], ['20150529',14.200], ['20150601',14.700], ['20150602',16.190], ['20150603',16.890], ['20150604',18.600], ['20150715',16.720], ['20150716',15.030], ['20150717',13.510], ['20150720',12.530], ['20150721',11.270], ['20150722',11.780], ['20150723',11.700], ['20150724',11.430], ['20150727',10.270], ['20150728',9.220], ['20150729',9.430], ['20150730',8.580], ['20150731',7.850], ['20150803',7.050], ['20150804',7.780], ['20150805',8.580], ['20150806',8.250], ['20150807',8.590], ['20150810',9.060], ['20150811',8.880], ['20150812',8.700], ['20150813',9.590], ['20150814',9.750], ['20150817',10.110], ['20150818',10.120], ['20150819',11.150], ['20150820',10.010], ['20150821',8.990], ['20150824',8.070], ['20150825',7.240], ['20150826',6.490], ['20150827',6.290], ['20150828',6.940], ['20150831',6.850], ['20150901',6.140], ['20150902',5.500], ['20150907',5.620], ['20150908',6.090], ['20150909',6.510], ['20151210',7.180], ['20151211',7.920], ['20151214',8.730], ['20151215',8.370], ['20151216',8.540], ['20151217',8.620], ['20151218',8.350], ['20151221',8.540], ['20151222',8.620], ['20151223',8.710], ['20151224',8.600], ['20151225',9.020], ['20151228',8.600], ['20151229',8.800], ['20151230',8.810], ['20151231',9.040], ['20160104',8.110], ['20160105',7.530], ['20160106',7.930], ['20160107',7.120], ['20160108',7.110], ['20160111',6.380], ['20160112',6.380], ['20160113',5.890], ['20160114',6.260], ['20160115',6.250], ['20160118',6.390], ['20160119',6.680], ['20160120',6.750], ['20160121',6.430], ['20160122',6.450], ['20160125',6.520], ['20160126',5.880], ['20160127',5.650], ['20160128',5.320], ['20160129',5.500], ['20160201',5.300], ['20160202',5.490], ['20160203',5.770], ['20160204',6.080], ['20160205',6.110], ['20160215',6.110], ['20160216',6.350], ['20160217',6.420], ['20160218',6.400], ['20160219',6.380], ['20160222',6.480], ['20160223',6.410], ['20160224',6.580], ['20160225',5.900], ['20160226',5.810], ['20160301',5.510], ['20160302',5.610], ['20160303',5.700], ['20160304',5.400], ['20160307',5.580], ['20160308',5.570], ['20160309',5.450], ['20160310',5.310], ['20160311',5.250], ['20160314',5.450], ['20160315',5.430], ['20160316',5.450], ['20160317',5.580], ['20160318',5.810], ['20160321',5.950], ['20160322',5.970], ['20160323',6.050], ['20160324',5.860], ['20160325',5.940], ['20160328',5.970], ['20160329',5.820], ['20160330',5.980], ['20160331',5.980], ['20160401',6.000], ['20160405',6.310], ['20160406',6.460], ['20160407',6.690], ['20160408',6.500], ['20160411',6.840], ['20160419',6.790], ['20160420',6.630], ['20160428',6.670], ['20160429',6.640], ['20160503',6.980], ['20160504',6.920], ['20160505',6.950], ['20160506',6.610], ['20160509',6.640], ['20160510',6.570], ['20160511',6.670], ['20160512',6.600], ['20160513',6.500], ['20160516',6.550], ['20160517',6.660], ['20160518',6.450], ['20160519',6.410], ['20160520',6.400], ['20160523',6.550], ['20160524',6.600], ['20160525',6.660], ['20160526',6.570], ['20160527',6.550], ['20160530',6.490], ['20160531',6.700], ['20160601',6.730], ['20160602',7.040], ['20160603',6.880], ['20160606',6.900], ['20160607',6.820], ['20160608',6.640], ['20160613',6.340], ['20160614',6.370], ['20160615',6.520], ['20160616',6.470], ['20160617',6.570], ['20160620',6.480], ['20160621',6.500], ['20160622',6.530], ['20160623',6.540], ['20160624',6.480], ['20160627',6.580], ['20160628',6.680], ['20160629',6.660], ['20160630',6.700], ['20160701',6.930], ['20160704',6.950], ['20160705',6.920], ['20160706',6.820], ['20160707',6.850], ['20160708',6.850], ['20160711',6.800], ['20160712',6.820], ['20160713',7.040], ['20160714',7.160], ['20160715',7.130], ['20160718',7.140], ['20160719',7.150], ['20160720',7.040], ['20160721',7.090], ['20160722',7.010], ['20160725',7.020], ['20160726',7.080], ['20160727',6.760], ['20160728',6.760], ['20160729',6.750], ['20160801',6.580], ['20160802',6.600], ['20160803',6.670], ['20160804',6.710], ['20160805',6.770], ['20160808',6.840], ['20160809',6.840], ['20160810',6.830], ['20160811',6.780], ['20160812',6.830], ['20160815',6.920], ['20160816',6.980], ['20160817',7.020], ['20160818',7.070], ['20161118',7.430], ['20161121',7.680], ['20161122',8.080], ['20161123',7.910], ['20161124',7.900], ['20161125',7.860], ['20161128',7.900], ['20161129',8.060], ['20161130',7.840], ['20161201',7.830], ['20161202',7.840], ['20161205',8.000], ['20161206',8.330], ['20161207',8.350], ['20161208',8.470], ['20161209',8.540], ['20161212',8.100], ['20161213',8.180], ['20161214',8.600], ['20161215',8.560], ['20161216',8.590], ['20161219',8.870], ['20161220',8.820], ['20161221',8.680], ['20161222',8.610], ['20161223',8.320], ['20161226',8.360], ['20161227',8.360], ['20161228',8.500], ['20161229',8.490], ['20161230',8.770], ['20170103',8.920], ['20170104',9.100], ['20170105',9.090], ['20170106',9.020], ['20170109',9.210], ['20170110',9.210], ['20170111',8.750], ['20170112',8.690], ['20170113',8.680], ['20170116',8.240], ['20170117',8.440], ['20170118',8.420], ['20170119',8.390], ['20170120',8.660], ['20170123',8.870], ['20170124',8.840], ['20170125',8.660], ['20170126',8.740], ['20170512',7.840], ['20170515',7.520], ['20170516',7.980], ['20170517',7.860], ['20170518',7.710], ['20170519',7.710], ['20170522',7.330], ['20170523',6.980], ['20170524',6.930], ['20170525',7.110], ['20170526',7.370], ['20170531',7.230], ['20170601',7.400], ['20170602',7.480], ['20170605',7.610], ['20170606',7.590], ['20170607',7.670], ['20170608',7.710], ['20170609',7.640], ['20170612',7.350], ['20170613',7.460], ['20170614',7.480], ['20170615',7.720], ['20170616',7.670], ['20170619',7.860], ['20170620',7.780], ['20170621',7.980], ['20170622',7.820], ['20170623',7.750], ['20170626',8.550], ['20170627',9.430], ['20170628',9.680], ['20170629',9.460], ['20170630',9.260], ['20170703',9.320], ['20170704',9.160], ['20170705',9.480], ['20170706',9.410], ['20170707',9.540], ['20170710',9.200], ['20170711',8.790], ['20170712',8.940], ['20170713',9.120], ['20170714',9.450], ['20170717',8.860], ['20170718',9.520], ['20170719',10.240], ['20170720',10.380], ['20170721',10.280], ['20170724',11.090], ['20170725',10.940], ['20170726',10.820], ['20170727',10.270], ['20170728',10.370], ['20170731',10.840], ['20170801',10.960], ['20170802',10.480], ['20170803',10.500], ['20170804',10.910], ['20170807',10.660], ['20170808',10.630], ['20170809',11.520], ['20170810',11.810], ['20170811',11.210], ['20170814',11.980], ['20170815',12.150], ['20170816',11.790], ['20170817',11.840], ['20170818',11.810], ['20170821',11.760], ['20170822',11.500], ['20170823',11.310], ['20170824',10.830], ['20170825',10.970], ['20170828',11.190], ['20170829',11.220], ['20170830',11.570], ['20170831',12.060], ['20170901',12.060], ['20170904',12.090], ['20170905',11.930], ['20170906',12.480], ['20170907',12.300], ['20170918',11.970], ['20170919',11.570], ['20170920',11.810], ['20170921',11.610], ['20170922',11.510], ['20170925',11.200], ['20170926',11.500], ['20170927',11.530], ['20170928',11.680], ['20170929',11.840], ['20171009',11.970], ['20171010',12.010], ['20171011',11.840], ['20171012',11.530], ['20171013',11.770], ['20171016',11.550], ['20171017',11.700], ['20171018',11.730], ['20171019',12.080], ['20171020',12.390], ['20171023',12.530], ['20171024',12.530], ['20171025',12.930], ['20171026',13.060], ['20171027',13.680], ['20171030',14.050], ['20171031',13.800], ['20171101',13.900], ['20171102',13.630], ['20171103',13.780], ['20171106',14.170], ['20171107',14.700], ['20171108',14.590], ['20171109',14.630], ['20171110',14.680], ['20171113',15.380], ['20171114',15.280], ['20171115',15.270], ['20171116',15.490], ['20171117',13.980], ['20171120',14.540], ['20171121',15.370], ['20171122',15.170], ['20171123',14.730], ['20171124',13.960], ['20171127',13.670], ['20171128',13.930], ['20171129',14.470], ['20171130',14.470], ['20171201',15.000], ['20171204',15.410], ['20171205',14.480], ['20171206',15.010], ['20171207',14.980], ['20171208',15.080], ['20171211',14.930], ['20171212',15.290], ['20171213',15.360], ['20171214',15.240], ['20171215',14.790], ['20171218',14.400], ['20171219',14.650], ['20171220',14.630], ['20171221',14.740], ['20171222',15.070], ['20171225',15.090], ['20171226',15.090], ['20171227',14.750], ['20171228',14.820], ['20171229',15.070], ['20180102',15.790], ['20180103',15.810], ['20180104',16.240], ['20180105',16.230], ['20180108',16.280], ['20180109',16.150], ['20180110',15.780], ['20180111',15.280], ['20180112',15.080], ['20180115',14.780], ['20180116',14.080], ['20180117',14.570], ['20180118',15.040], ['20180119',15.030], ['20180122',14.900], ['20180123',14.940], ['20180124',14.910], ['20180125',14.810], ['20180126',15.040], ['20180129',14.860], ['20180130',14.880], ['20180131',14.930], ['20180201',14.780], ['20180202',14.820], ['20180205',14.720], ['20180206',14.270], ['20180207',14.270], ['20180208',14.580], ['20180209',13.980], ['20180212',14.580], ['20180213',14.790], ['20180214',14.870], ['20180222',15.250], ['20180223',15.310], ['20180226',15.340], ['20180227',15.160], ['20180228',15.080], ['20180301',15.250], ['20180302',15.150], ['20180305',15.040], ['20180306',15.050], ['20180307',15.080], ['20180308',14.980], ['20180309',15.050], ['20180312',15.270], ['20180313',15.080], ['20180314',14.930], ['20180315',14.660], ['20180316',14.580], ['20180319',14.350], ['20180320',14.340], ['20180321',14.000], ['20180322',13.540], ['20180323',12.230], ['20180326',12.840], ['20180327',13.140], ['20180328',13.010], ['20180329',13.010], ['20180330',12.590], ['20180402',12.570], ['20180403',12.580], ['20180404',12.500], ['20180409',11.880], ['20180410',11.680], ['20180411',11.690], ['20180412',11.710], ['20180413',11.840], ['20180416',11.610], ['20180417',11.480], ['20180418',11.650], ['20180419',11.690], ['20180420',11.380], ['20180423',11.280], ['20180424',11.510], ['20180425',11.450], ['20180426',10.750], ['20180427',10.740], ['20180502',11.600], ['20180503',11.890], ['20180504',11.860], ['20180507',12.300], ['20180508',12.190], ['20180509',12.040], ['20180510',12.170], ['20180511',11.990], ['20180514',12.170], ['20180515',12.080], ['20180516',11.930], ['20180517',12.060], ['20180518',12.090], ['20180521',11.860], ['20180522',11.800], ['20180523',11.400], ['20180524',11.580], ['20180525',11.430], ['20180528',11.090], ['20180529',11.230], ['20180530',10.930], ['20180531',10.970], ['20180601',10.580], ['20180604',10.750], ['20180605',11.070], ['20180606',11.040], ['20180607',10.920], ['20180608',10.770], ['20180611',10.860], ['20180612',10.940], ['20180613',10.710], ['20180614',10.680], ['20180615',10.350], ['20180619',9.330], ['20180620',9.570], ['20180621',9.700], ['20180622',10.170], ['20180625',10.250], ['20180626',10.150], ['20180627',10.340], ['20180628',10.180], ['20180629',10.350], ['20180702',10.000], ['20180703',10.360], ['20180704',10.140], ['20180705',9.850], ['20180706',9.840], ['20180709',10.010], ['20180710',10.110], ['20180711',9.810], ['20180712',10.140], ['20180713',10.300], ['20180716',10.110], ['20180717',10.010], ['20180718',9.940], ['20180719',9.800], ['20180720',9.890], ['20180723',10.110], ['20180724',10.880], ['20180725',10.910], ['20180726',10.580], ['20180727',10.470], ['20180730',10.480], ['20180731',10.540], ['20180801',10.800], ['20180802',10.720], ['20180803',10.340], ['20180806',9.980], ['20180807',10.630], ['20180808',10.780], ['20180809',10.900], ['20180810',10.820], ['20180813',10.810], ['20180814',10.700], ['20180815',10.540], ['20180816',10.280], ['20180817',10.070], ['20180820',10.110], ['20180821',10.180], ['20180822',9.980], ['20180823',10.070], ['20180824',10.070], ['20180827',10.230], ['20180828',10.180], ['20180829',10.060], ['20180830',9.890], ['20180831',9.570], ['20180903',9.030], ['20180904',9.050], ['20180905',8.810], ['20180906',8.720], ['20180907',8.710], ['20180910',8.410], ['20180911',8.230], ['20180912',8.350], ['20180913',8.390], ['20180914',8.280], ['20180917',7.990], ['20180918',8.260], ['20180919',8.300], ['20180920',8.270], ['20180921',8.400], ['20180925',8.410], ['20180926',8.470], ['20180927',8.280], ['20180928',8.360], ['20181008',8.010], ['20181009',8.010], ['20181010',8.000], ['20181011',7.240], ['20181012',7.140], ['20181015',7.170], ['20181016',7.130], ['20181017',7.130], ['20181018',7.000], ['20181019',7.580], ['20181022',8.080], ['20181023',7.990], ['20181024',7.880], ['20181025',8.280], ['20181026',8.290], ['20181029',8.380], ['20181030',8.550], ['20181031',8.570], ['20181101',8.640], ['20181102',8.970], ['20181105',9.050], ['20181106',9.170], ['20181107',9.500], ['20181108',9.530], ['20181109',10.230], ['20181112',10.870], ['20181113',10.860], ['20181114',10.780], ['20181115',10.890], ['20181116',11.480], ['20181119',11.370], ['20181120',10.770], ['20181121',10.860], ['20181122',10.900], ['20181123',10.960], ['20181126',10.780], ['20181127',11.010], ['20181128',11.160], ['20181129',10.830], ['20181130',10.950], ['20181203',11.330], ['20181204',11.230], ['20181205',11.140], ['20181206',11.140], ['20181207',11.710], ['20181210',11.870], ['20181211',12.010], ['20181212',11.860], ['20181213',11.760], ['20181214',11.610], ['20181217',11.670], ['20181218',11.690], ['20181219',11.640], ['20181220',11.580], ['20181221',11.900], ['20181224',11.770], ['20181225',11.740], ['20181226',11.380], ['20181227',10.230], ['20181228',10.150], ['20190102',9.690], ['20190103',9.370], ['20190104',9.410], ['20190107',8.880], ['20190108',8.760], ['20190109',8.650], ['20190110',8.590], ['20190111',8.660], ['20190114',8.610], ['20190115',8.550], ['20190116',8.420], ['20190117',8.220], ['20190118',8.230], ['20190121',8.290], ['20190122',8.120], ['20190123',7.970], ['20190124',8.010], ['20190125',7.860], ['20190128',7.790], ['20190129',7.510], ['20190130',7.860], ['20190131',7.590], ['20190201',7.860], ['20190211',8.050], ['20190212',8.130], ['20190213',8.200], ['20190214',8.340], ['20190215',8.290], ['20190218',8.780], ['20190219',8.660], ['20190220',9.040], ['20190221',8.820], ['20190222',8.810], ['20190225',9.090], ['20190226',9.040], ['20190227',8.870], ['20190228',8.930], ['20190301',8.970], ['20190304',9.020], ['20190305',9.130], ['20190306',9.580], ['20190307',9.770], ['20190308',9.110], ['20190311',9.340], ['20190312',9.420], ['20190313',9.150], ['20190314',8.830], ['20190315',9.000], ['20190318',9.280], ['20190319',9.170], ['20190320',9.140], ['20190321',9.180], ['20190322',9.090], ['20190325',8.970], ['20190326',8.670], ['20190327',8.620], ['20190328',8.410], ['20190329',8.620], ['20190401',8.800], ['20190402',8.720], ['20190403',8.950], ['20190404',9.160], ['20190408',9.310], ['20190409',9.070], ['20190410',9.060], ['20190411',8.860], ['20190412',8.740], ['20190415',8.620], ['20190416',8.720], ['20190417',8.840], ['20190418',8.750], ['20190419',8.820], ['20190422',8.810], ['20190423',8.520], ['20190424',8.550], ['20190425',7.950], ['20190426',7.680], ['20190429',7.380], ['20190430',7.290], ['20190506',6.630], ['20190507',6.730], ['20190508',6.690], ['20190509',6.790], ['20190510',6.930], ['20190513',6.790], ['20190514',6.660], ['20190515',6.880], ['20190516',7.010], ['20190517',6.760], ['20190520',6.610], ['20190521',6.670], ['20190522',6.510], ['20190523',6.280], ['20190524',6.350], ['20190527',6.470], ['20190528',6.500], ['20190529',6.480], ['20190530',6.410], ['20190531',6.350], ['20190701',6.080]]; var source='wstock.net';
mcknote/akame
akame/notification/formatters/core.py
<reponame>mcknote/akame import logging from typing import List from akame.comparison.delta.core import DeltaBase logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class FormatterBase: """Class that defines base formatter Args: delta (DeltaBase): Delta object """ def __init__(self, delta: DeltaBase) -> None: self.parts_matched = delta.parts_matched self.parts_changed_a = delta.parts_changed_a self.parts_changed_b = delta.parts_changed_b
Bhaskers-Blu-Org2/pmod
src/foundation/TypeInfoFactory.h
<reponame>Bhaskers-Blu-Org2/pmod<filename>src/foundation/TypeInfoFactory.h /*** * Copyright (C) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. * * File:TypeInfoFactory.h ****/ #pragma once #include <map> #include <foundation/ctl/com_library.h> #include <foundation/com_ptr.h> #include <foundation/library/foundation_library.h> #include <foundation/dictionary_ptr.h> #include <foundation/interfaces/enumerable.h> class CPropertyTypeInfoFactoryCache { public: static CPropertyTypeInfoFactoryCache& GetInstance(); static HRESULT CreatePropertyTypeInfoInternal( _In_ const foundation::PropertyTypeInfo *pTypeInfo, _COM_Outptr_ foundation::IPropertyTypeInfo **ppPropertyTypeInfo); public: HRESULT CreateOrGetFactoryPropertyTypeInfo( foundation::PropertyType type, _COM_Outptr_ foundation::IPropertyTypeInfo **ppPropertyTypeInfo); HRESULT CreateOrGetFactoryPropertyTypeInfo( _In_ const foundation::PropertyTypeInfo *pTypeInfo, _COM_Outptr_ foundation::IPropertyTypeInfo **ppPropertyTypeInfo); private: typedef std::map<foundation::PropertyType, foundation::ComPtr<foundation::IPropertyTypeInfo>> _FoundationPropertyTypeInfo_MapType; _FoundationPropertyTypeInfo_MapType _foundationPropertyTypeInfos; }; class CTypeInfoFactory : public foundation::ctl::ComInspectableBase, public foundation::library::ITypeInfoFactory { public: static foundation::library::ITypeInfoFactory *GetInstance(); static HRESULT GetOrCreateInstance(foundation::library::ITypeInfoFactory **ppTypeInfoFactory); static HRESULT _DeserializePropertyTypeInfo( const foundation::DictionaryPtr& type_info_ptr, LPCSTR_t propertyTypeInfoKey, _COM_Outptr_ foundation::IPropertyTypeInfo **ppPropertyTypeInfo); static HRESULT _SerializePropertyTypeInfo( foundation::DictionaryPtr& type_info_ptr, LPCSTR_t propertyTypeInfoKey, _In_ foundation::IPropertyTypeInfo *pPropertyTypeInfo); static HRESULT _DeserializePropertyTypeInfo( const foundation::DictionaryPtr& property_type_info_ptr, foundation::PropertyType& propertyType, IID& typeInfoType); static HRESULT _SerializePropertyTypeInfo( foundation::DictionaryPtr& property_type_info_ptr, _In_ foundation::IPropertyTypeInfo *pPropertyTypeInfo); //Interface ITypeInfoFactory STDMETHOD(CreatePropertyTypeInfo)( foundation::PropertyType type, GUID modelType, _COM_Outptr_ foundation::IPropertyTypeInfo **ppPropertyTypeInfo); STDMETHOD(CreatePropertyInfo)( UINT32 Id, _In_ HSTRING name, foundation::PropertyType type, UINT32 flags, GUID modelType, _COM_Outptr_ foundation::IPropertyInfo **ppPropertyInfo); STDMETHOD(CreateMethodInfo)( _In_ UINT32 methodId, _In_ HSTRING name, _In_ foundation::PropertyType returnPropertyType, _In_ GUID *pReturnModelType, _In_ bool isAsync, _Outptr_ foundation::library::IMethodInfoClass **ppMethodInfoClass); STDMETHOD(CreateEnumTypeInfo)( UINT32 typeId, GUID iidType, _In_ HSTRING name, bool isFlags, UINT32 size, _In_ HSTRING *pName, _In_ UINT32 *pValues, _COM_Outptr_ foundation::IEnumTypeInfo **ppEnumTypeInfo); STDMETHOD(CreateAsyncOperationTypeInfo)( UINT32 typeId, GUID iidType, _In_ HSTRING name, _In_ foundation::IPropertyTypeInfo *pResultTypeInfo, _COM_Outptr_ foundation::IAsyncOperationTypeInfo **ppAsyncOperationTypeInfo); STDMETHOD(CreateEnumerableTypeInfo)( _In_ UINT32 typeId, _In_ GUID iidType, _In_ HSTRING name, _In_ foundation::IPropertyTypeInfo *pItemTypeInfo, _In_ UINT32 type, _Outptr_ foundation::IEnumerableTypeInfo **ppEnumerableTypeInfo); STDMETHOD(RegisterEnumTypeInfo)(_In_ foundation::IEnumTypeInfo *pEnumTypeInfo); STDMETHOD(RegisterAsyncOperationTypeInfo)(_In_ foundation::IAsyncOperationTypeInfo *pAsyncOperationTypeInfo); STDMETHOD(RegisterEnumerableTypeInfo)(_In_ foundation::IEnumerableTypeInfo *pEnumerableTypeInfo); STDMETHOD(RegisterTypeInfo)( _In_ const foundation::TypeInfo* pTypeInfoEntry); STDMETHOD(RegisterMultipleTypeInfos)( _In_ const foundation::TypeInfo* pTypeInfoEntries[]); STDMETHOD(RegisterMultipleTypeInfos)( UINT32 size, foundation::IDictionary **ppDictionaryTypeInfo); STDMETHOD(SerializeTypeInfo)( foundation::IObjectTypeInfo *pTypeInfo, foundation::IDictionary **ppDictionaryTypeInfo); protected: HRESULT QueryInterfaceImpl(REFIID iid, foundation::IUnknown **ppInterface) override { if (iid == foundation::library::ITypeInfoFactory::GetIID()) { *ppInterface = static_cast<foundation::library::ITypeInfoFactory *>(this); } else { return foundation::ctl::ComInspectableBase::QueryInterfaceImpl(iid, ppInterface); } return S_OK; } private: static HRESULT CreatePropertyTypeInfoInternal( foundation::PropertyType type, GUID modelType, _COM_Outptr_ foundation::IPropertyTypeInfo **ppPropertyTypeInfo); };
EliahKagan/old-practice-snapshot
main/count-the-paths/count-the-paths.cpp
<reponame>EliahKagan/old-practice-snapshot #include <cstddef> #include <functional> #include <iostream> #include <stdexcept> #include <vector> namespace { using Graph = std::vector<std::vector<std::size_t>>; // adjacency lists inline void check_src_dest(const Graph& graph, const std::size_t src, const std::size_t dest) { if (src >= graph.size() || dest >= graph.size()) throw std::out_of_range{"no such vertex"}; } inline void add_edge(Graph& graph, const std::size_t src, const std::size_t dest) { check_src_dest(graph, src, dest); graph[src].push_back(dest); } Graph read_graph() { std::size_t v {}, e {}; std::cin >> v >> e; Graph graph (v); while (e-- != 0u) { std::size_t src {}, dest {}; std::cin >> src >> dest; add_edge(graph, src, dest); } return graph; } int count_paths(const Graph& graph, const std::size_t src, const std::size_t dest) { std::vector<bool> vis (graph.size()); const std::function<int(std::size_t)> dfs {[&dfs, &graph, &vis, dest](const std::size_t cur) { if (vis[cur]) return 0; if (cur == dest) return 1; vis[cur] = true; auto ret = 0; for (const auto next : graph[cur]) ret += dfs(next); vis[cur] = false; return ret; }}; return dfs(src); } } int main() { std::ios_base::sync_with_stdio(false); auto t = 0; for (std::cin >> t; t > 0; --t) { const auto graph = read_graph(); std::size_t src {}, dest {}; std::cin >> src >> dest; check_src_dest(graph, src, dest); std::cout << count_paths(graph, src, dest) << '\n'; } }
KuoZD/BlueSkyFlightControl
SRC/DRIVER/drv_spi.h
<reponame>KuoZD/BlueSkyFlightControl #ifndef __DRV_SPI_H__ #define __DRV_SPI_H__ #include "board.h" void Spi_GPIO_Init(void); void Spi_Open(uint8_t deviceNum); uint8_t Spi_SingleWirteAndRead(uint8_t deviceNum, uint8_t dat); void SPI_MultiWriteAndRead(uint8_t deviceNum, uint8_t *out, uint8_t *in, int len); void Spi_GyroSingleWrite(uint8_t reg, uint8_t value); void Spi_GyroMultiRead(uint8_t reg,uint8_t *data, uint8_t length); void Spi_BaroSingleWrite(uint8_t reg, uint8_t value); void Spi_BaroMultiRead(uint8_t reg,uint8_t *data, uint8_t length); #endif
jerry-sc/webhunger
webhunger-crawler/src/main/java/us/codecraft/webmagic/pipeline/Pipeline.java
package us.codecraft.webmagic.pipeline; import me.shenchao.webhunger.entity.webmagic.ResultItems; import us.codecraft.webmagic.LifeCycle; /** * 重构Pipeline去掉ResultItem类 * * Pipeline is the persistent and offline process part of crawler.<br> * The interface Pipeline can be implemented to customize ways of persistent. * * @author <EMAIL> <br> * @since 0.1.0 */ public interface Pipeline { /** * Process extracted results. * * @param resultItems resultItems * @param task task */ void process(ResultItems resultItems, LifeCycle task); }
gonzaloruizdevilla/alicates
lib/modules/functional/f.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var f = function f() { return false; }; exports.f = f;
JanoCodes/Registry
db/migrate/20190302111152_add_object_changes_to_versions.rb
class AddObjectChangesToVersions < ActiveRecord::Migration def change add_column :versions, :object_changes, :jsonb end end
bakhodir10/AlgoCS
src/leetcode_problems/easy/IntersectionArray_349.java
package leetcode_problems.easy; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class IntersectionArray_349 { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for (int i = 0; i < nums1.length; i++) { set1.add(nums1[i]); } for (int i = 0; i < nums2.length; i++) { boolean b = set1.contains(nums2[i]); if (b) set2.add(nums2[i]); } int arr[] = new int[set2.size()]; Iterator<Integer> it = set2.iterator(); int i = 0; while (it.hasNext()) { arr[i++] = it.next(); } return arr; } }
moody-person/11ty-website
src/_data/community/global-data-tannerdolby.js
<reponame>moody-person/11ty-website module.exports = { url: "https://tannerdolby.com/writing/generate-page-content-from-a-global-data-file-using-eleventy/", author: "tannerdolby", title: "Generate Page Content from a Global Data File", key: "data" };
ashishjayamohan/competitive-programming
Practice/cme.py
<reponame>ashishjayamohan/competitive-programming<gh_stars>0 t = int(input()) answer = [] for a in range(t): val = int(input()) if(val == 2): answer.append(2) elif(val%2 == 1): answer.append(1) else: answer.append(0) for b in answer: print(str(b))
lanlandetiankong/egg_manager
egg-facade/src/main/java/com/egg/manager/persistence/em/user/pojo/mapstruct/imap/EmUserDepartmentMapstruct.java
package com.egg.manager.persistence.em.user.pojo.mapstruct.imap; import com.egg.manager.persistence.em.user.db.mysql.entity.EmUserDepartmentEntity; import com.egg.manager.persistence.em.user.pojo.dto.EmUserDepartmentDto; import com.egg.manager.persistence.em.user.pojo.mapstruct.conversion.EmUserDepartmentConversion; import com.egg.manager.persistence.em.user.pojo.vo.EmUserDepartmentVo; import com.egg.manager.persistence.exchange.pojo.mysql.mapstruct.imap.fundamental.MyBaseMysqlMapstruct; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Mappings; import org.mapstruct.ReportingPolicy; import org.mapstruct.factory.Mappers; /** * @author zhoucj * @description * @date 2020/10/20 */ @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.ERROR, uses = {EmUserDepartmentConversion.class} ) public interface EmUserDepartmentMapstruct extends MyBaseMysqlMapstruct<EmUserDepartmentEntity, EmUserDepartmentVo, EmUserDepartmentDto> { EmUserDepartmentMapstruct INSTANCE = Mappers.getMapper(EmUserDepartmentMapstruct.class); /** * vo转entity * @param vo * @return */ @Mappings({}) EmUserDepartmentEntity transferVoToEntity(EmUserDepartmentVo vo); /** * entity转vo * @param entity * @return */ @Mappings({ @Mapping(target = "createUser", ignore = true), @Mapping(target = "lastModifyer", ignore = true) }) EmUserDepartmentVo transferEntityToVo(EmUserDepartmentEntity entity); /** * dto转vo * @param dto * @return */ @Mappings({ @Mapping(target = "createUser", expression = "java(translateCreateUserEntityToVo(dto.getLastModifyer()))"), @Mapping(target = "lastModifyer", expression = "java(translateUpdateUserEntityToVo(dto.getLastModifyer()))") }) EmUserDepartmentVo transferDtoToVo(EmUserDepartmentDto dto); }
Franckyi/Emerald
src/main/java/com/github/franckyi/emerald/service/web/MojangAuthException.java
package com.github.franckyi.emerald.service.web; import com.github.franckyi.emerald.service.web.resource.mojang.auth.AuthError; import java.io.IOException; public class MojangAuthException extends IOException { private final AuthError error; public MojangAuthException(AuthError error) { super(error.getErrorMessage()); this.error = error; } public AuthError getError() { return error; } }
XuefengWu/aost
core/src/test/groovy/org/telluriumsource/ut/Trie_UT.java
package org.telluriumsource.ut; import org.junit.Test; import static org.junit.Assert.assertNotNull; import org.telluriumsource.misc.Trie; import org.telluriumsource.misc.Node; import java.util.Random; import java.util.List; import java.util.ArrayList; /** * @author <NAME> (<EMAIL>) * * Date: Dec 21, 2009 */ public class Trie_UT { public String[] randomize(String[] dictionary){ if(dictionary != null && dictionary.length > 0){ Random rand = new Random(); List<String> list = new ArrayList<String>(); for(String str: dictionary){ list.add(str); } List<String> nlist = new ArrayList<String>(); while(list.size() > 0){ int index = rand.nextInt(list.size()); nlist.add(list.remove(index)); } return nlist.toArray(new String[0]); } return null; } @Test public void testInsert(){ String[] dictionary = {"a", "an", "and", "andy", "bo", "body", "bodyguard", "some", "someday", "goodluck", "joke"}; Trie trie = new Trie(); String[] ndict = randomize(dictionary); trie.buildTree(ndict); trie.checkAndIndexLevel(); trie.printMe(); Node deepest = trie.getDeepestNode(); assertNotNull(deepest); System.out.println("deepest word: " + deepest.getFullWord() + ", level: " + deepest.getLevel()); } }
xm-online/xm-ms-dashboard
src/main/java/com/icthh/xm/ms/dashboard/service/dto/DashboardDto.java
<gh_stars>1-10 package com.icthh.xm.ms.dashboard.service.dto; import com.icthh.xm.ms.dashboard.domain.Dashboard; import com.icthh.xm.ms.dashboard.domain.Widget; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class DashboardDto { private Long id; private String name; private String owner; private String typeKey; private Boolean isPublic; private Map<String, Object> layout = new HashMap<>(); private Map<String, Object> config = new HashMap<>(); private Set<WidgetDto> widgets = new HashSet<>(); public DashboardDto(Dashboard dashboard) { super(); this.id = dashboard.getId(); this.name = dashboard.getName(); this.owner = dashboard.getOwner(); this.typeKey = dashboard.getTypeKey(); this.isPublic = dashboard.isIsPublic(); this.layout = dashboard.getLayout() == null ? this.layout : dashboard.getLayout(); this.config = dashboard.getConfig() == null ? this.config : dashboard.getConfig(); this.widgets = dashboard.getWidgets() == null ? this.widgets : toWidgetsDto(dashboard.getWidgets()); } public static Set<WidgetDto> toWidgetsDto(Collection<Widget> widgets) { return widgets.stream().map(WidgetDto::new).collect(Collectors.toSet()); } }
14ms/Minecraft-Disclosed-Source-Modifications
Skizzle/com/sun/jna/IntegerType.java
/* * Decompiled with CFR 0.150. */ package com.sun.jna; import com.sun.jna.FromNativeContext; import com.sun.jna.NativeMapped; public abstract class IntegerType extends Number implements NativeMapped { private static final long serialVersionUID = 1L; private int size; private Number number; private boolean unsigned; private long value; public IntegerType(int size) { this(size, 0L, false); } public IntegerType(int size, boolean unsigned) { this(size, 0L, unsigned); } public IntegerType(int size, long value) { this(size, value, false); } public IntegerType(int size, long value, boolean unsigned) { this.size = size; this.unsigned = unsigned; this.setValue(value); } public void setValue(long value) { long truncated = value; this.value = value; switch (this.size) { case 1: { if (this.unsigned) { this.value = value & 0xFFL; } truncated = (byte)value; this.number = (byte)value; break; } case 2: { if (this.unsigned) { this.value = value & 0xFFFFL; } truncated = (short)value; this.number = (short)value; break; } case 4: { if (this.unsigned) { this.value = value & 0xFFFFFFFFL; } truncated = (int)value; this.number = (int)value; break; } case 8: { this.number = value; break; } default: { throw new IllegalArgumentException("Unsupported size: " + this.size); } } if (this.size < 8) { long mask = (1L << this.size * 8) - 1L ^ 0xFFFFFFFFFFFFFFFFL; if (value < 0L && truncated != value || value >= 0L && (mask & value) != 0L) { throw new IllegalArgumentException("Argument value 0x" + Long.toHexString(value) + " exceeds native capacity (" + this.size + " bytes) mask=0x" + Long.toHexString(mask)); } } } @Override public Object toNative() { return this.number; } @Override public Object fromNative(Object nativeValue, FromNativeContext context) { long value = nativeValue == null ? 0L : ((Number)nativeValue).longValue(); try { IntegerType number = (IntegerType)this.getClass().newInstance(); number.setValue(value); return number; } catch (InstantiationException e) { throw new IllegalArgumentException("Can't instantiate " + this.getClass()); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Not allowed to instantiate " + this.getClass()); } } @Override public Class<?> nativeType() { return this.number.getClass(); } @Override public int intValue() { return (int)this.value; } @Override public long longValue() { return this.value; } @Override public float floatValue() { return this.number.floatValue(); } @Override public double doubleValue() { return this.number.doubleValue(); } public boolean equals(Object rhs) { return rhs instanceof IntegerType && this.number.equals(((IntegerType)rhs).number); } public String toString() { return this.number.toString(); } public int hashCode() { return this.number.hashCode(); } public static <T extends IntegerType> int compare(T v1, T v2) { if (v1 == v2) { return 0; } if (v1 == null) { return 1; } if (v2 == null) { return -1; } return IntegerType.compare(v1.longValue(), v2.longValue()); } public static int compare(IntegerType v1, long v2) { if (v1 == null) { return 1; } return IntegerType.compare(v1.longValue(), v2); } public static final int compare(long v1, long v2) { if (v1 == v2) { return 0; } if (v1 < v2) { return -1; } return 1; } }
KZzizzle/osparc-simcore
services/storage/src/simcore_service_storage/__version__.py
""" Current version of the simcore_service_storage application and its API """ import pkg_resources from semantic_version import Version __version__: str = pkg_resources.get_distribution("simcore_service_storage").version version = Version(__version__) api_version_prefix: str = f"v{version.major}"
yevheniiatsiurupa/job4j
chapter_008/src/main/java/ru/job4j/lsp/StorageBlock.java
package ru.job4j.lsp; import java.util.ArrayList; import java.util.List; public class StorageBlock { private List<Storage> storage = new ArrayList<>(); /** * Конструктор. */ public StorageBlock() { } public List<Storage> getStorage() { return storage; } /** * Метод добавляет продукт в хранилище, где accept возвращает true. * @param food добавляемый продукт. */ public void add(Food food) { for (Storage tmp : storage) { if (tmp.accept(food)) { tmp.add(food); break; } } } public void addStorage(Storage st) { storage.add(st); } public List<Food> removeAllFood() { List<Food> removed = new ArrayList<>(); for (Storage tmp : storage) { removed.addAll(tmp.removeFood()); } return removed; } }
12roshan12/Hotel-website
apps/frontend/hotel/migrations/0004_auto_20211130_2207.py
# Generated by Django 3.2.6 on 2021-11-30 16:37 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('hotel', '0003_auto_20211130_2133'), ] operations = [ migrations.RenameField( model_name='staff', old_name='email', new_name='emails', ), migrations.RenameField( model_name='staff', old_name='firstname', new_name='firstnames', ), migrations.RenameField( model_name='staff', old_name='lastname', new_name='lastnames', ), migrations.RenameField( model_name='staff', old_name='mobile', new_name='mobiles', ), migrations.AddField( model_name='staff', name='last_login', field=models.DateTimeField(blank=True, null=True, verbose_name='last login'), ), migrations.AddField( model_name='staff', name='password', field=models.CharField(default=django.utils.timezone.now, max_length=50), preserve_default=False, ), ]
shuaicj/hello-java
hello-mockito/src/test/java/shuaicj/hello/mockito/mockbean/MockBean1Test.java
<reponame>shuaicj/hello-java package shuaicj.hello.mockito.mockbean; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; /** * Test the spring annotation @MockBean. * * Mock beans will reset after each test method. * * Strange: Mock list when get(0) returns null instead of throwing IndexOutOfBoundsException. * * @author shuaicj 2017/03/17 */ @RunWith(SpringRunner.class) public class MockBean1Test { @MockBean List list; @Test public void testGetDefault() throws Exception { assertThat(list.get(0)).isNull(); } @Test public void testGet1() throws Exception { assertThat(list.get(0)).isNull(); when(list.get(0)).thenReturn("abc"); assertThat(list.get(0)).isEqualTo("abc"); } @Test public void testGet2() throws Exception { assertThat(list.get(0)).isNull(); when(list.get(0)).thenReturn("def"); assertThat(list.get(0)).isEqualTo("def"); } }
StdUtil/wormhole
src/main/java/net/stackoverflow/blog/dao/MenuDao.java
<filename>src/main/java/net/stackoverflow/blog/dao/MenuDao.java package net.stackoverflow.blog.dao; import net.stackoverflow.blog.common.Page; import net.stackoverflow.blog.pojo.entity.Menu; import org.apache.ibatis.annotations.Mapper; import java.util.List; import java.util.Map; /** * menu表DAO类 * * @author 凉衫薄 */ @Mapper public interface MenuDao { List<Menu> selectByPage(Page page); List<Menu> selectByCondition(Map<String, Object> searchMap); Menu selectById(String id); List<Menu> selectByIds(List<String> ids); int insert(Menu menu); int batchInsert(List<Menu> list); int delete(String id); int batchDelete(List<String> list); int update(Menu menu); int batchUpdate(List<Menu> list); }
ponfee/commons-core
src/main/java/code/ponfee/commons/ws/adapter/ResultPageAdapter.java
package code.ponfee.commons.ws.adapter; import javax.xml.bind.annotation.adapters.XmlAdapter; import code.ponfee.commons.model.Page; import code.ponfee.commons.model.Result; import code.ponfee.commons.reflect.GenericUtils; import code.ponfee.commons.ws.adapter.model.TransitPage; /** * Result<Page<T>>转换器 * @param <T> * * @see org.springframework.data.domain.jaxb.PageAdapter * * @author Ponfee */ public abstract class ResultPageAdapter<T> extends XmlAdapter<Result<TransitPage<T>>, Result<Page<T>>> { protected final Class<T> type; protected ResultPageAdapter() { type = GenericUtils.getActualTypeArgument(this.getClass()); } @Override public Result<Page<T>> unmarshal(Result<TransitPage<T>> v) { if (v.getData() == null) { return v.copy(null); } else if ( v.getData().getRows() == null || v.getData().getRows().getItem() == null) { return v.copy(new Page<>()); } return v.copy(TransitPage.recover(v.getData())); } @Override public Result<TransitPage<T>> marshal(Result<Page<T>> v) { if (v.getData() == null) { return v.copy(null); } else if (v.getData().getRows() == null) { return v.copy(new TransitPage<>()); } return v.copy(TransitPage.transform(v.getData(), type)); } }
GeraltShi/Tracing-Android
MapModule/app/src/main/java/com/fdwireless/trace/httpclass/my_Volley.java
package com.fdwireless.trace.httpclass; import android.content.Context; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; /** * Created by 汪励颢 on 2017/2/6. */ public class my_Volley { private static RequestQueue instance; public static RequestQueue getInstace(Context pContext){ if(instance==null){ instance= Volley.newRequestQueue(pContext); } return instance; } }
IMLDG/shoppingPj
src/main/java/com/group6/shopping/files/controllers/FilesRestController.java
package com.group6.shopping.files.controllers; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/files") public class FilesRestController { }
Remmeauth/remme-client-java
src/main/java/sawtooth/sdk/protobuf/SettingOuterClass.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: setting.proto package sawtooth.sdk.protobuf; public final class SettingOuterClass { private SettingOuterClass() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_Setting_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_Setting_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_Setting_Entry_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_Setting_Entry_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\rsetting.proto\"O\n\007Setting\022\037\n\007entries\030\001 " + "\003(\0132\016.Setting.Entry\032#\n\005Entry\022\013\n\003key\030\001 \001(" + "\t\022\r\n\005value\030\002 \001(\tB&\n\025sawtooth.sdk.protobu" + "fP\001Z\013setting_pb2b\006proto3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); internal_static_Setting_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_Setting_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_Setting_descriptor, new java.lang.String[] { "Entries", }); internal_static_Setting_Entry_descriptor = internal_static_Setting_descriptor.getNestedTypes().get(0); internal_static_Setting_Entry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_Setting_Entry_descriptor, new java.lang.String[] { "Key", "Value", }); } // @@protoc_insertion_point(outer_class_scope) }
mygodness100/paradise-study-hadoop
paradise-study-scala/src/main/java/com/wy/example/oop/Euro.scala
//package com.wy.oop //case class Euro(value: Double) extends Amount // This class doesn't compile since Amount is sealed in another file
dennis-park/OOGALoompas
src/main/java/schema/GameSchema.java
<gh_stars>0 package main.java.schema; import java.io.Serializable; import java.util.HashSet; import java.util.Set; /** * the higher level settings defining the type of game and some basic * overarching stats */ public class GameSchema extends AbstractSchema { public static final String LIVES = "lives"; public static final String MONEY = "money"; public static final String MUSIC = "music"; public static final String LEVELDIFFICULTY = "difficulty"; public static final String ISSURVIVALMODE = "survivalModeEnabled"; /** * The value should be of type Boolean */ public GameSchema() { super(); } @Override public void addAttribute(String attributeName, Serializable attributeValue) { myAttributesMap.put(attributeName, attributeValue); myAttributeSet.add(ISSURVIVALMODE); } @Override protected Set<String> populateAdditionalAttributes() { return new HashSet<String>(); } }
hanford/Mobile-Github-Client
src/redux/loading/actions.js
import t from './actionTypes' export function requestIssues () { return { type: t.REQUEST_ISSUES } } export function receiveIssues () { return { type: t.RECEIVE_ISSUES } } export function requestRepos () { return { type: t.REQUEST_REPOS } } export function receiveRepos () { return { type: t.RECEIVE_REPOS } } export function requestTimeline () { return { type: t.REQUEST_TIMELINE } } export function receiveTimeline () { return { type: t.RECEIVE_TIMELINE } } export function requestNotifications () { return { type: t.REQUEST_NOTIFICATIONS } } export function receiveNotifications () { return { type: t.RECEIVE_NOTIFICATIONS } } export function requestTrending () { return { type: t.REQUEST_TRENDING } } export function receiveTrending () { return { type: t.RECEIVE_TRENDING } } export function requestProfile () { return { type: t.REQUEST_PROFILE } } export function receiveProfile () { return { type: t.RECEIVE_PROFILE } } export function requestSearch () { return { type: t.REQUEST_SEARCH } } export function receiveSearch () { return { type: t.RECEIVE_SEARCH } }
ChrisBarker-NOAA/tamoc
tamoc/psf.py
<filename>tamoc/psf.py """ Particle Size Functions ======================= This module provides empirical functions for computing particle sizes (bubble and droplets) from jet releases into water. Model equations are from:: Johansen et al. (2013) Li et al. (2017) Wang et al. (2018) Utilities are also included to generate log-normal or Rosin-Rammler size distributions and to apply the d_95 rule (the idea that the d_95 value of a volume-size distribution should not exceed the maximum stable particle size). The functions in this module are used by the `particle_size_models` module and are not intended to be called directly. In the future, these functions could, for example, be ported to Fortran or another language and wrapped in Python for use by the `particle_size_models` class objects. See Also -------- particle_size_models.ModelBase, particle_size_models.PureJet, particle_size_models.Model Notes ----- Particle size distributions are computed from the following sources:: * <NAME>., <NAME>., and <NAME>. (2013) "Droplet breakup in subsea oil releases - Part 2: Predictions of droplet size distributions with and without injection of chemical dispersants." Mar Pollut Bull, 73(1), 327-335. This reference is intended for liquid oil breakup only. * <NAME>., <NAME>., <NAME>., <NAME>., and <NAME>. (2017) "Development of a unified oil droplet size distribution model with application to surface breaking waves and subsea blowout releases considering dispersant effects." Mar Pollut Bull, 114(1), 247-257. The authors apply this reference for breakup of gas bubble or oil droplets. * <NAME>., <NAME>., <NAME>., <NAME>., and <NAME>. C. (2018). "Behavior and dynamics of bubble breakup in gas pipeline leaks and accidental subsea oil well blowouts." <NAME>, 131, 72-86. This reference is only intended for gas bubble breakup. The maximum stable droplet size of an immiscible liquid in seawater is taken from:: * <NAME>., <NAME>., and <NAME>. (1978) *Bubbles, Drops, and \ Particles*, Dover Publications, Inc., Mineola, New York. For gas bubbles in water, the maximum stable bubble size is taken from a method in Grace et al:: * <NAME>., <NAME>., <NAME>., (1978) "Break-up of drops and bubbles in stagnant media," Can. J. Chem. Eng. 56 (1), 3-8. """ # <NAME>, December 2019, Texas A&M University <<EMAIL>> from __future__ import (absolute_import, division, print_function) from tamoc import dbm import numpy as np from scipy.optimize import fsolve from scipy.optimize import minimize # Use SI units throughout G = 9.81 # General Utilities ---------------------------------------------------------- def mass2vol(m, rho): """ Convert a mass or mass flux to a volume or volume flux Parameters ---------- m : ndarray Array of masses (kg) or mass fluxes (kg/s) for each component of a given fluid rho : float In-situ density of a given fluid (kg/m^3) Returns ------- q : float Corresponding volume (m^3) or volume flux (m^3/s) of a given fluid """ # Compute volume handling zero-fluxes correctly if np.sum(m) > 0: q = np.sum(m) / rho else: q = 0. return q # Probabiity Density Functions ----------------------------------------------- def rosin_rammler(nbins, d50, k, alpha): """ Return the volume size distribution from the Rosin-Rammler distribution Returns the fluid particle diameters in the selected number of bins on a volume-fraction basis from the Rosin Rammler distribution with parameters d_50, k, and alpha. Parameters ---------- nbins : int Desired number of size bins in the particle volume size distribution d50 : float Volume mean particle diameter (m) k : float Scale parameter of the Rosin-Rammler distribution (=log(0.5) for d_50) alpha : float Shape parameter of the Rosin-Rammler distribution Returns ------- de : ndarray Array of particle sizes at the center of each bin in the distribution (m) vf : ndarray Volume fraction in each bin (--) """ # Get the de/d50 ratio for the edges of each bin in the distribution # using a log-spacing a99 = (np.log(1. - 0.995) / k)**(1. / alpha) a01 = (np.log(1. - 0.01) / k)**(1. / alpha) bin_edges = np.logspace(np.log10(a01), np.log10(a99), nbins + 1) # Find the logarithmic average location of the center of each bin bin_centers = np.zeros(len(bin_edges) - 1) for i in range(len(bin_centers)): bin_centers[i] = np.exp(np.log(bin_edges[i]) + (np.log(bin_edges[i+1]) - np.log(bin_edges[i])) / 2.) # Compute the actual diameters of each particle de = d50 * bin_centers # Get the volume fraction within each bin if d50 == 0: vf = np.zeros(len(bin_centers)) else: vn = 1. - np.exp(k * bin_edges**alpha) vf = np.zeros(len(bin_centers)) for i in range(len(bin_edges) - 1): vf[i] = vn[i+1] - vn[i] vf = vf / np.sum(vf) # Return the particle size distribution return (de, vf) def log_normal(nbins, d50, sigma): """ Return the volume size distribution from the Log-normal distribution Returns the fluid particle diameters in the selected number of bins on a volume-fraction basis from the Log-normal distribution with parameters d50 and sigma_x. Parameters ---------- nbins : int Desired number of size bins in the particle volume size distribution d50 : float Volume mean particle diameter (m) sigma : float Standard deviation of the Log-normal distribution in logarithmic units. Returns ------- de : ndarray Array of particle sizes at the center of each bin in the distribution (m) vf : ndarray Volume fraction in each bin (--) Notes ----- This function uses the log-normal distribution defined at:: https://en.wikipedia.org/wiki/Log-normal_distribution last accessed on 1/10/2020. The relationship between mu_x and sigma_x of the real x values and mu and sigma of the log(x) values is from the notes for ENGR 102 posted here: https://ceprofs.civil.tamu.edu/ssocolofsky/ENGR102/ Downloads/19c/Week_12/week_12.pdf last accessed on 1/10/2020. """ # Get the de/d50 ratio for the edges of each bin in the distribution # using a log-spacing a0 = np.exp(np.log(d50) - 2.8 * sigma) / d50 a1 = np.exp(np.log(d50) + 2.3 * sigma) / d50 bin_edges = np.logspace(np.log10(a0), np.log10(a1), nbins + 1) # Find the logarithmic average location of the center of each bin bin_centers = np.zeros(len(bin_edges) - 1) for i in range(len(bin_centers)): bin_centers[i] = np.exp(np.log(bin_edges[i]) + (np.log(bin_edges[i+1]) - np.log(bin_edges[i])) / 2.) # Compute the actual diameters of each particle de = d50 * bin_centers # Compute log-normal parameters for de/d50 distribution mu = np.log(1.) # Get the volume fraction within each bin if d50 == 0: vf = np.zeros(len(bin_centers)) else: vf = 1. / bin_centers * 1. / (sigma * np.sqrt(2. * np.pi)) * \ np.exp(-(np.log(bin_centers) - mu)**2 / (2. * sigma**2)) vf = vf / np.sum(vf) # Return the particle size distribution return (de, vf) def ln2rr(d50, sigma): """ Convert the parameters of a log-normal distribution to Rosin-Rammler Parameters ---------- d50 : float The median particle size of a volume distribution sigma : float Standard deviation of the Log-normal distribution in logarithmic units. Returns ------- d50 : float Volume mean particle diameter (m) k : float Scale parameter of the Rosin-Rammler distribution (=log(0.5) for d_50) alpha : float Shape parameter of the Rosin-Rammler distribution """ # Compute d95 of the log-normal distribution mu = np.log(d50) mu_95 = mu + 1.6449 * sigma d95 = np.exp(mu_95) # Find parameters of Rosin-Rammler with same d50 and d95 k = np.log(0.5) alpha = np.log(np.log(1. - 0.95) / k) / np.log(d95 / d50) return (d50, k, alpha) def rr2ln(d50, k, alpha): """ Convert the parameters of a Rosin-Rammler distribution to log-normal Parameters ---------- d50 : float Volume mean particle diameter (m) k : float Scale parameter of the Rosin-Rammler distribution (=log(0.5) for d_50) alpha : float Shape parameter of the Rosin-Rammler distribution Returns ------- d50 : float The median particle size of a volume distribution sigma : float Standard deviation of the Log-normal distribution in logarithmic units. """ # Compute d95 of the Rosin-Rammler distribution k = np.log(0.5) d95 = d50 * (np.log(1. - 0.95) / k)**(1. / alpha) # Find the parameters of log-normal with same d50 and d95 sigma = (np.log(d95) - np.log(d50)) / 1.6449 return (d50, sigma) def rosin_rammler_fit(d50, d_max, alpha=1.8): """ Return d_50, k, and alpha for the Rosin-Rammler distribution Parameters ---------- d_50 : float Volume median diameter (m) d_max : float Maximum stable diameter (m) alpha : float, default=1.8 Returns ------- d_50 : float Volume median diameter (m) k : float Scale parameter for the Rosin-Rammler size distribution (--) alpha : float Shape parameter for the Rosin-Rammler size distribution (--) Notes ----- This function follows the idea of Sintef to not let d_95 of the Rosin- Rammler distribution exceed the maximum stable particle size. If the original d_50 and d_max result in d_95 exceeding d_max, the d_50 is shifted downward such that d_95 will equal d_max. Otherwise, the original d_50 is preserved. Uses the Rosin-Rammler distribution equations at: https://en.wikipedia.org/wiki/Particle-size_distribution last access on 03/17/20. """ # k parameter for d50 k = np.log(0.5) # Adjust down if d95 exceeds the de_max if d_max == None: d50 = d50 else: # Compute d95 for the given d50 d95 = d50 * (np.log(1. - 0.95) / k)**(1. / alpha) # Adjust d50 so that d95 does not exceed d_max if d95 > d_max: d95 = d_max k95 = np.log(0.05) d50 = d95 * (np.log(1. - 0.5) / k95)**(1. / alpha) # Return the final distribution fit return (d50, k, alpha) def log_normal_fit(d50, d_max, sigma=0.27): """ Return d_50 and sigma for the log-normal distribution Parameters ---------- d_50 : float Volume median diameter (m) d_max : float Maximum stable diameter (m) sigma : float, default=0.27 Standard deviation of the Log-normal distribution in logarithmic units. Returns ------- d_50 : float Volume median diameter (m) sigma : float Standard deviation of the Log-normal distribution in logarithmic units. Notes ----- This function follows the idea of Sintef to not let d_95 of the particle size distribution exceed the maximum stable particle size. If the original d_50 and d_max result in d_95 exceeding d_max, the d_50 is shifted downward such that d_95 will equal d_max. Otherwise, the original d_50 is preserved. """ # Adjust down if d50 exceeds the de_max if d_max == None: # Do not adjust the fit d50 = d50 else: # Comnpute d95 for the given d50 and sigma mu = np.log(d50) mu_95 = mu + 1.6449 * sigma d95 = np.exp(mu_95) # Adjust d_50 so that d_95 does not exceed d_max if d95 > d_max: d50 = np.exp(np.log(d_max) - 1.6449 * sigma) # Return the final distribution fit return (d50, sigma) # Functions for computing maximum stable particle size ----------------------- def de_max_oil(rho_p, sigma, rho): """ Calculate the maximum stable oil droplet size Predicts the maximum stable liquid particle size per Clift et al. (1978) via the equation: d_max = 4. * np.sqrt(sigma / (g (rho - rho_p))) Parameters ---------- rho_p : float Density of the phase undergoing breakup (kg/m^3) sigma : float Interfacial tension between the phase undergoing breakup and the ambient receiving continuous phase (N/m) rho : float Density of the ambient receiving continuous phase (kg/m^3) Returns ------- d_max : float Maximum stable particle size (m) """ return 4. * np.sqrt(sigma / (G * (rho - rho_p))) def grow_rate(n, k, nu_c, nu_d, sigma, g, dp, rho_c, rho_d, K): """ Compute the instability growth rate on a gas bubble Write instability growth rate equation in Grace et al. as a root problem for n = f(k) Returns ------- res : float The residual of the growth-rate equation expressed as a root-finding problem. Notes ----- This function is used by the `grace()` function for maximum stable particle size. It should not be called directly. """ # Compute more derived variables m_c = np.sqrt(k**2 + n / nu_c) m_d = np.sqrt(k**2 + n / nu_d) mu_c = nu_c / rho_c # Compute the residual of the root function res = (sigma * k**3 - g * k * dp + n**2 * (rho_c + rho_d)) * \ (k + m_c + K * (k + m_d)) + 4 * n * k * mu_c * (k + K * m_d) * \ (K * k + m_c) # Return the residual return res def grow_time(lam, de, U, nu_c, nu_d, sigma, g, dp, rho_c, rho_d, K, c_0): """ Compare the available and needed disturbance growth times for instability Compares the time available for a disturbance to grow to the time needed for that disturbance to break a bubble. Returns ------- t_cr : float The critical time (s) for which the required grow time equals the available time Notes ----- This function is used by the `grace()` function for maximum stable particle size. It should not be called directly. """ # Compute the derived variables k = 2. * np.pi / lam # Consider disturbances with a node at the nose theta_1 = lam / (2. * de) # Compute the available time for disturbance growth t_a = de / 2 / U * (1. + 3. / 2. * K) * np.log(1. / np.tan( theta_1 / 2.)) # Compute the grwoth rate of this disturbance n0 = 1. / t_a n = fsolve(grow_rate, n0, args=(k, nu_c, nu_d, sigma, g, dp, rho_c, rho_d, K) )[0] # Relate n to t_e t_e = 1. / n # Return the critical growth time return c_0 * t_e - t_a def find_de(de, rho_d, rho_c, mu_d, mu_c, sigma, nu_d, nu_c, g, dp, K, lam_crit, c_0): """ Search for the critical stable bubble size Search for the maximum stable bubble size of a gas bubble in water using the method in Grace et al. Returns ------- t_min : float The minimum time required for a disturbance of the given size to break the fluid particle. Notes ----- This function is used by the `grace()` function for maximum stable particle size. It should not be called directly. """ # Time available for growth, t_a # The travel time from the position where disturance starts to the equator from tamoc import dbm_f # Compute the rise velocity of this bubble size shape = dbm_f.particle_shape(de, rho_d, rho_c, mu_c, sigma) if shape == 1: U = dbm_f.us_sphere(de, rho_d, rho_c, mu_c) elif shape == 2: U = dbm_f.us_ellipsoid(de, rho_d, rho_c, mu_d, mu_c, sigma, -1) else: U = dbm_f.us_spherical_cap(de, rho_d, rho_c) # lam_max is upper limit on leading interface disturbance size lam_max = np.pi * de / 2. # Find the wave length that corresponds to the maximum growth rate lam = minimize(grow_time, 1.001 * lam_crit, args=(de, U, nu_c, nu_d, sigma, g, dp, rho_c, rho_d, K, c_0), bounds=[(lam_crit, lam_max)] ).x[0] t_min = grow_time(lam, de, U, nu_c, nu_d,sigma, g, dp, rho_c, rho_d, K, c_0) # Return the growth time return t_min def grace(rho_c, rho_d, mu_c, mu_d, sigma, fp_type=0): """ Implement the Grace et al. algorithm for maximum stable particle size Computes the maximum stable particle size of an immiscible particle rising in stagnant water following a method in Grace et al. Parameters ---------- rho_c : float Density of the continuous-phase ambient fluid (kg/m^3) rho_d : float Density of the immiscible fluid particle subject to breakup (kg/m^3) mu_c : float Dynamic viscosity of the continuous-phase ambient fluid (Pa s) mu_d : float Dynamic viscosity of the immiscible fluid particle subject to breakup (Pa s) sigma : float Interfacial tension between the continuous phase ambient fluid and the immiscible fluid particle subject to breakup (N/m) fp_type : int, default=0 Phase of the immiscible fluid particle; 0 = gas, 1 = liquid. Returns ------- de_max : float Equivalent spherical diameter of the maximum stable fluid particle subject to breakup in stagnant water (m) See Also -------- grow_rate, grow_time, find_de Notes ----- Implements the method in * <NAME>., <NAME>., <NAME>., (1978) "Break-up of drops and bubbles in stagnant media," Can. J. Chem. Eng. 56 (1), 3-8. """ # Set the fit parameter if fp_type == 0: # This is gas c_0 = 3.8 else: # This is liquid c_0 = 1.4 # Compute the derived properties dp = np.abs(rho_c - rho_d) K = mu_d / mu_c nu_c = mu_c / rho_c nu_d = mu_d / rho_d # Region of instability. # lam_crit is lower limit on unstable wavelengths lam_crit = 2. * np.pi * np.sqrt(sigma / (G * dp)) # Lower limit on maximum stable diameter is lam_crit = lam_max de_max_star = 2. / np.pi * lam_crit # Choose Initialize the search near this minimum de = 1.01 * de_max_star # Find the maximum stable bubble size de_max = fsolve(find_de, de, args=(rho_d, rho_c, mu_d, mu_c, sigma, nu_d, nu_c, G, dp, K, lam_crit, c_0) )[0] # Return the result return de_max # SINTEF Model Equations ----------------------------------------------------- def sintef(d0, m_gas, rho_gas, m_oil, rho_oil, mu_p, sigma, rho, mu, fp_type=1, use_d95=True): """ Compute characteristic values for jet breakup Computes the characteristic particle sizes for jet breakup using the equations in Johansen et al. (2013) (sintef model equations) and using the model coefficients updated in technical reports to API. Parameters ---------- d0 : float Equivalent circular diameter of the release (m) m_gas : np.array Mass fluxes of each pseudo-component of the gas-phase fluid at the release (kg/s) rho_gas : float Density of the gas-phase petroleum fluid at the release (kg/m^3) m_oil : np.array Mass fluxes of each pseudo-component of the liquid-phase petroleum fluid at the release (kg/s) rho_oil : float Density of the liquid-phase petroleum fluid at the release (kg/m^3) mu_p : float Dynamic viscosity of the fluid phase of interest at the release (Pa s) sigma : float Interfacial tension between the fluid phase of interest and water at the release (N/m) rho : float Density of seawater at the release (kg/m^3) mu : float Dynamic viscosity of seawater at the release (Pa s) fp_type : int, default=1 Fluid phase to compute breakup; 0 = gas, 1 = liquid. The SINTEF equation authors do not recommend using this method for gas; hence, fp_type should normally equal 1. use_d95 : bool, default=True Flag indicating whether or not to implement the d_95 rule (see module documentation above); `True` means to use the rule. Returns ------- d50 : float Volume median diameter of the fluid phase of interest (m) de_max : float Maximum stable particle size of the fluid phase of interest (m) k : float Scale parameter for the Rosin-Rammler size distribution (--) alpha : float Shape parameter for the Rosin-Rammler size distribution (--) """ # Convert mass-flux to volume flux if np.sum(m_gas) > 0: q_gas = mass2vol(m_gas, rho_gas) else: q_gas = 0. if np.sum(m_oil) > 0: q_oil = mass2vol(m_oil, rho_oil) else: q_oil = 0. # Get the void-fraction adjusted characteristic exit velocity n = q_gas / (q_gas + q_oil) if q_oil == 0.: # This is gas only Un = 4. * q_gas / (np.pi * d0**2) rho_m = rho_gas elif q_gas == 0: # This is oil only Un = 4. * q_oil / (np.pi * d0**2) rho_m = rho_oil else: # This is oil and gas Un = 4. * q_oil / (np.pi * d0**2) / (1. - n)**(1./2.) rho_m = rho_oil * (1. - n) + rho_gas * n Fr = Un / (G * (rho - rho_m) / rho * d0)**(1./2.) Uc = Un * (1. + 1./Fr) # Compute the particle size distribution parameters if fp_type == 0: d50, de_max, k, alpha = sintef_model(Uc, d0, q_gas, rho_gas, mu_p, sigma, rho, mu, is_gas=True, use_d95=use_d95) else: d50, de_max, k, alpha = sintef_model(Uc, d0, q_oil, rho_oil, mu_p, sigma, rho, mu, is_gas=False, use_d95=use_d95) return (d50, de_max, k, alpha) def sintef_model(Uc, d0, q, rho_p, mu_p, sigma, rho, mu, is_gas=False, use_d95=True): """ Computes the particle size for the Sintef equation Evaluates the parameters of the particle size distribution for the SINTEF equation and implements the d_95 rule as appropriate. This function returns the parameters of the Rosin-Rammler size distribution with the spreading rates as reported in Johansen et al. Returns ------- d50 : float Volume median diameter of the fluid phase of interest (m) de_max : float Maximum stable particle size of the fluid phase of interest (m) k : float Scale parameter for the Rosin-Rammler size distribution (--) alpha : float Shape parameter for the Rosin-Rammler size distribution (--) Notes ----- This function is called by the `sintef()` function after several intermediate parameters are computed. This function should not be called directly. """ if q > 0.: # Compute d_50 from the We model d50 = sintef_d50(Uc, d0, rho_p, mu_p, sigma, rho) # Get an estimate of de_max if is_gas: de_max = grace(rho, rho_p, mu, mu_p, sigma, fp_type=0) else: de_max = de_max_oil(rho_p, sigma, rho) # Get the adjusted particle size distribution d50_from95, k, alpha = rosin_rammler_fit(d50, de_max) # Return the desired value for d50 if use_d95: # Use the d_95 rule d50 = d50_from95 elif d50 > de_max: # Truncate the distribution d50 = de_max else: # Return an empty set of particles de_max = None d50, k, alpha = rosin_rammler_fit(0., de_max) return (d50, de_max, k, alpha) def sintef_d50(u0, d0, rho_p, mu_p, sigma, rho): """ Compute d_50 from the SINTEF equations Returns ------- d50 : float Volume median diameter of the fluid phase of interest (m) Notes ----- This function is called by the `sintef()` function after several intermediate parameters are computed. This function should not be called directly. """ # Compute the non-dimensional constants We = rho_p * u0**2 * d0 / sigma Vi = mu_p * u0 / sigma if We > 350.: # Atomization...use the the We model A = 24.8 B = 0.08 # Solve for the volume mean diameter from the implicit equation def residual(dp): """ Compute the residual of the SINTEF modified Weber number model Evaluate the residual of the non-dimensional diameter dp = de_50 / D for the SINTEF droplet break-up model. Input variables are: We, Vi, A, B = constant and global from above dp = Non-dimensional diameter de_50 / D (--) """ # Compute the non-dimensional diameter and return the residual return dp - A * (We / (1. + B * Vi * dp**(1./3.)))**(-3./5.) # Find the gas and liquid fraction for the mixture dp = fsolve(residual, 5.)[0] # Compute the final d_50 d50 = dp * d0 else: # Sinuous wave breakup...use the pipe diameter d50 = 1.2 * d0 # Return the result return d50 # Li et al. Equations -------------------------------------------------------- def li_etal(d0, m_gas, rho_gas, m_oil, rho_oil, mu_p, sigma, rho, mu, fp_type=1): """ Compute characteristic values for jet breakup Computes the characteristic particle sizes for jet breakup using the equations in Li et al. (2017) (li_etal model equations). The authors provide different equation fit parameters for gas or liquid breakup, and this function selects the correct parameters for the fluid phase of interest. Parameters ---------- d0 : float Equivalent circular diameter of the release (m) m_gas : np.array Mass fluxes of each pseudo-component of the gas-phase fluid at the release (kg/s) rho_gas : float Density of the gas-phase petroleum fluid at the release (kg/m^3) m_oil : np.array Mass fluxes of each pseudo-component of the liquid-phase petroleum fluid at the release (kg/s) rho_oil : float Density of the liquid-phase petroleum fluid at the release (kg/m^3) mu_p : float Dynamic viscosity of the fluid phase of interest at the release (Pa s) sigma : float Interfacial tension between the fluid phase of interest and water at the release (N/m) rho : float Density of seawater at the release (kg/m^3) mu : float Dynamic viscosity of seawater at the release (Pa s) fp_type : int, default=1 Fluid phase to compute breakup; 0 = gas, 1 = liquid. The SINTEF equation authors do not recommend using this method for gas; hence, fp_type should normally equal 1. Returns ------- d50 : float Volume median diameter of the fluid phase of interest (m) de_max : float Maximum stable particle size of the fluid phase of interest (m) k : float Scale parameter for the Rosin-Rammler size distribution (--) alpha : float Shape parameter for the Rosin-Rammler size distribution (--) """ # Convert mass-flux to volume flux q_gas = mass2vol(m_gas, rho_gas) q_oil = mass2vol(m_oil, rho_oil) # Get the void-fraction adjusted characteristic exit velocity n = q_gas / (q_gas + q_oil) if fp_type == 0: Uc = 4. * q_gas / (np.pi * d0**2) / n elif fp_type == 1: Uc = 4. * q_oil / (np.pi * d0**2) / (1. - n) # Compute the particle size distribution for gas and oil if fp_type == 0: d50, de_max, k, alpha = li_etal_model(Uc, d0, q_gas, rho_gas, mu_p, sigma, rho, mu, is_gas=True) else: d50, de_max, k, alpha = li_etal_model(Uc, d0, q_oil, rho_oil, mu_p, sigma, rho, mu, is_gas=False) return (d50, de_max, k, alpha) def li_etal_model(Uc, d0, q, rho_p, mu_p, sigma, rho, mu, is_gas=False): """ Computes the particle size for the Li et al. equation Evaluates the parameters of the particle size distribution for the Li et al. equation and implements the d_95 rule. This function returns the parameters of the Rosin-Rammler size distribution with the spreading rates as reported in Li et al. Returns ------- d50 : float Volume median diameter of the fluid phase of interest (m) de_max : float Maximum stable particle size of the fluid phase of interest (m) k : float Scale parameter for the Rosin-Rammler size distribution (--) alpha : float Shape parameter for the Rosin-Rammler size distribution (--) Notes ----- This function is called by the `li_etal()` function after several intermediate parameters are computed. This function should not be called directly. """ if q > 0.: # Compute d_50 from the We model d50 = li_etal_d50(Uc, d0, rho_p, mu_p, sigma, rho, is_gas) # Get an estimate of de_max if is_gas: de_max = grace(rho, rho_p, mu, mu_p, sigma, fp_type=0) else: de_max = de_max_oil(rho_p, sigma, rho) # Get the adjusted particle size distribution d50, k, alpha = rosin_rammler_fit(d50, None) else: # Return an empty set of particles de_max = None d50, k, alpha = rosin_rammler_fit(0., de_max) return (d50, de_max, k, alpha) def li_etal_d50(Uc, d0, rho_p, mu_p, sigma, rho, is_gas=True): """ Compute d_50 from the Li et al. equations Returns ------- d50 : float Volume median diameter of the fluid phase of interest (m) Notes ----- This function is called by the `li_etal()` function after several intermediate parameters are computed. This function should not be called directly. """ # Get the constants of the fit for a jet release p = 0.460 q = -0.518 if is_gas: r = 2.988 else: r = 14.05 # The Li et al. (2017) model wrongly uses the oil equation for the # maximum stable particle size of gas de_max = de_max_oil(sigma, rho_p, rho) if de_max < d0: dc = de_max else: dc = d0 # Compute dimensionless groups We = rho * Uc**2 * dc / sigma Oh = mu_p / np.sqrt(rho_p * sigma * dc) # Compute the non-dimensional d50 ds = r * (1 + 10 * Oh)**p * We**q d50 = ds * dc return d50 # Wang et al. Equations ------------------------------------------------------ def wang_etal(d0, m_g, rho_g, mu_g, sigma_g, rho, mu, m_l=0., rho_l=None, P=4.e6, T=288.15): """ Compute characteristic values for gas jet breakup Computes the characteristic gas bubble sizes for jet breakup using the equations in Wang et al. (2018) (wang_etal model equations). Parameters ---------- d0 : float Equivalent circular diameter of the release (m) m_g : np.array Mass fluxes of each pseudo-component of the gas-phase fluid at the release (kg/s) rho_g : float Density of the gas-phase fluid at the release (kg/m^3) mu_g : float Dynamic viscosity of the gas-phase fluid at the release (Pa s) sigma_g : float Interfacial tension between the gas-phase fluid and water at the release (N/m) rho : float Density of seawater at the release (kg/m^3) mu : float Dynamic viscosity of seawater at the release (Pa s) m_l : np.array Mass fluxes of each pseudo-component of the liquid-phase fluid at the release (kg/s) rho_l : float Density of the liquid-phase fluid at the release (kg/m^3) P : float, default=4.e6 Pressure in the receiving fluid (Pa); used to compute the speed of sound in the released gas. T : float, default=288.15 Temperature of the gas phase at the release (K); used to compute the speed of sound in the released gas. Returns ------- d50_gas : float Volume median diameter of the gas bubbles (m) m_gas : float Mass fluxes of each pseudo-component of the gas-phase fluid at the release (kg/s). This may be different from the input value in the case of choked flow at the orifice. m_oil : float Mass fluxes of each pseudo-component of the liquid-phase fluid at the release (kg/s). This may be different from the input value in the case of choked flow at the orifice. de_max : float Maximum stable particle size of the fluid phase of interest (m) sigma : float Standard deviation of the Log-normal distribution in logarithmic units. """ # Convert mass-flux to volume flux Qg = mass2vol(m_g, rho_g) if np.sum(m_l) == 0.: Ql = 0. else: Ql = mass2vol(m_l, rho_l) # Compute the exit velocity assuming no choked flow and single exit # velocity n = Qg / (Qg + Ql) A = np.pi * d0**2 / 4. Ug = (Qg + Ql) / A # Check for choked flow using methane for speed of sound ch4 = dbm.FluidMixture(['methane']) delta_rho = ch4.density(np.array([1.]), T, P)[0,0] - \ ch4.density(np.array([1.]), T, 1.01 * P)[0,0] a = np.sqrt((P - 1.01 * P) / delta_rho) if 10. * Ug < a: U_E = Ug else: # Compute the cp / cv ratio cp_ch4 = 35.69 # J/mol/K; CO2 = 37.13 cv_ch4 = cp_ch4 - 8.31451 # From Poling et al. for ideal gases kappa = cp_ch4 / cv_ch4 # Assume approximately ok for petroleum # Get the Mach number Ma = Ug / a # Correct the exit velocity for choked flow if Ma < np.sqrt((kappa + 1.) / 2.): U_E = a * (-1. + np.sqrt(1. + 2. * (kappa - 1.) * Ma**2.)) / \ ((kappa - 1.) * Ma) else: U_E = a * np.sqrt(2. / (kappa + 1.)) # Update the gas and oil exit velocities if Qg > 0: Ug = U_E else: Ug = 0 if Ql > 0: Ul = U_E else: Ul = 0 # Compute the particle size distribution for gas d50_gas, m_gas, m_oil, de_max, sigma = wang_etal_model(A, n, Ug, rho_g, mu_g, sigma_g, Ul, rho_l, rho, mu) return (d50_gas, m_gas, m_oil, de_max, sigma) def wang_etal_model(A, n, Ug, rho_g, mu_g, sigma_g, Ul, rho_l, rho, mu): """ Computes the particle size for the Wang et al. equation Evaluates the parameters of the gas bubble size distribution for the Wang et al. equation and implements the d_95 rule. This function returns the parameters of the log-normal size distribution with the spreading rates as reported in Wang et al. Returns ------- d50_gas : float Volume median diameter of the gas bubbles (m) m_gas : float Mass fluxes of each pseudo-component of the gas-phase fluid at the release (kg/s). This may be different from the input value in the case of choked flow at the orifice. m_oil : float Mass fluxes of each pseudo-component of the liquid-phase fluid at the release (kg/s). This may be different from the input value in the case of choked flow at the orifice. de_max : float Maximum stable particle size of the fluid phase of interest (m) sigma_ln : float Standard deviation of the Log-normal distribution in logarithmic units. Notes ----- This function is called by the `wang_etal()` function after several intermediate parameters are computed. This function should not be called directly. """ if Ug > 0: # Compute d50 from the model (d, m_gas, m_oil) = wang_etal_d50(A, n, Ug, rho_g, mu_g, sigma_g, Ul, rho_l, rho, mu) # Compute the maximum stable bubble size de_max = grace(rho, rho_g, mu, mu_g, sigma_g, fp_type=0) # Get the adjusted particle size distribution d50_gas, sigma_ln = log_normal_fit(d, de_max, sigma=0.27) else: # Return an empty set of particles m_gas = 0. m_oil = rho_l * A * Ul de_max = None d50_gas, sigma_ln = log_normal_fit(0., de_max) return (d50_gas, m_gas, m_oil, de_max, sigma_ln) def wang_etal_d50(A, n, Ug, rho_g, mu_g, sigma_g, Ul, rho_l, rho, mu): """ Compute d_50 from the Wang et al. equations Returns ------- d50 : float Volume median diameter of the gas bubbles (m) Notes ----- This function is called by the `wang_etal()` function after several intermediate parameters are computed. This function should not be called directly. """ # Compute the total dynamic momentum and buoyancy fluxes Ag = A * n Al = A * (1. - n) mg = rho_g * Ag * Ug**2 bg = (rho - rho_g) * G * Ag * Ug if n == 1: ml = 0. bl = 0. else: ml = rho_l * Al * Ul**2 bl = (rho - rho_l) * G * Al * Ul mo = mg + ml bo = bg + bl # The kinematic momentum and buoyancy fluxes are M = mo / rho B = bo / rho # Jet-to-plume transition length scale l_M = M**(3./4.) / B**(1./2.) # Characteristic velocity scale Ua = np.sqrt(mo / (rho * A)) # Compute the mixture density if n == 1: rho_l = 0. rho_m = n * rho_g + (1. - n) * rho_l # Get the modified Weber number We_m = rho_m * Ua**2 * l_M / sigma_g # Compute the characteristic droplet size d = 4.3 * We_m**(-3./5.) * l_M # Compute the actual gas and oil flow rate m_g = rho_g * Ag * Ug m_l = rho_l * Al * Ul # Return the characteristic size return (d, m_g, m_l)
Chris-Coraggio/pyplyn
plugin-api/src/main/java/com/salesforce/pyplyn/processor/AbstractMeteredExtractProcessor.java
/* * Copyright (c) 2016-2017, Salesforce.com, Inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see the LICENSE.txt file in repo root * or https://opensource.org/licenses/BSD-3-Clause */ package com.salesforce.pyplyn.processor; import com.google.inject.Inject; import com.salesforce.pyplyn.model.Extract; import com.salesforce.pyplyn.model.ThresholdType; import com.salesforce.pyplyn.status.*; /** * Metered processor base class * <p/> * Provides helper methods used to meter {@link ExtractProcessor}s and provide runtime information * to an instance of {@link SystemStatus}. * <p/> * <p/>This class is similar in implementation to {@link AbstractMeteredLoadProcessor}. * * @author <NAME> &lt;<EMAIL>&gt; * @since 3.0 */ public abstract class AbstractMeteredExtractProcessor<T extends Extract> implements ExtractProcessor<T> { protected SystemStatus systemStatus; /** * Override this method and provide a name for the metered class * this name will be used in the AppConfig's alert section to define the required alerting thresholds * * @return the name used by the implementation of this class */ protected abstract String meterName(); /** * Call this method when the operation has succeeded */ protected void succeeded() { systemStatus.meter(meterName(), new MeterType(null, ProcessStatus.ExtractSuccess)).mark(); } /** * Call this method when the operation has failed */ protected void failed() { systemStatus.meter(meterName(), new MeterType(null, ProcessStatus.ExtractFailure)).mark(); } /** * Call this method when the endpoint returns no data */ protected void noData() { systemStatus.meter(meterName(), new MeterType(null, ProcessStatus.ExtractNoDataReturned)).mark(); } /** * Call this method when attempting to authenticate to the endpoint failed */ protected void authenticationFailure() { systemStatus.meter(meterName(), new MeterType(null, ProcessStatus.AuthenticationFailure)).mark(); } /** * Allows {@link com.google.inject.Guice} to inject a SystemStatus object * * @param systemStatus the {@link SystemStatus} singleton used to meter this processor */ @Inject public void setSystemStatus(SystemStatus systemStatus) { this.systemStatus = systemStatus; } }
codehaus/waffle
examples/mydvds-example/src/main/java/org/codehaus/waffle/example/mydvds/persistence/HibernateSessionFactory.java
package org.codehaus.waffle.example.mydvds.persistence; import org.codehaus.waffle.Startable; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class HibernateSessionFactory implements Startable { private SessionFactory sessionFactory; private AnnotationConfiguration configuration; public Session getSession() { return sessionFactory.openSession(); } public void start() { try { configuration = new AnnotationConfiguration(); configuration.configure(); sessionFactory = configuration.buildSessionFactory(); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } public void stop() { sessionFactory.close(); } }
Tokelon/tokTales
tokTales-core/tokTales-core-library/src/main/java/com/tokelon/toktales/core/engine/Engine.java
<filename>tokTales-core/tokTales-core-library/src/main/java/com/tokelon/toktales/core/engine/Engine.java package com.tokelon.toktales.core.engine; import javax.inject.Inject; import com.tokelon.toktales.core.engine.content.IContentService; import com.tokelon.toktales.core.engine.input.IInputService; import com.tokelon.toktales.core.engine.render.IRenderService; import com.tokelon.toktales.core.engine.storage.IStorageService; import com.tokelon.toktales.core.engine.ui.IUIService; public class Engine implements IEngine { private IEngineDriver engineDriver; private IEnvironment environment; private IUIService uiService; private IContentService contentService; private IStorageService storageService; private IRenderService renderService; private IInputService inputService; @Inject public Engine( IEngineDriver engineDriver, IEnvironment environment, IUIService uiService, IContentService contentService, IStorageService storageService, IRenderService renderService, IInputService inputService ) { this.engineDriver = engineDriver; this.environment = environment; this.uiService = uiService; this.contentService = contentService; this.storageService = storageService; this.renderService = renderService; this.inputService = inputService; } @Override public IEngineDriver getEngineDriver() { return engineDriver; } @Override public IEnvironment getEnvironment() { return environment; } @Override public IUIService getUIService() { return uiService; } @Override public IContentService getContentService() { return contentService; } @Override public IStorageService getStorageService() { return storageService; } @Override public IRenderService getRenderService() { return renderService; } @Override public IInputService getInputService() { return inputService; } }
TorinKwok/Authenticator
Authenticator/ATCPasswordCollectionView.h
// // ATCPasswordCollectionView.h // Authenticator // // Created by <NAME>. on 2/24/16. // Copyright © 2016 <NAME>. All rights reserved. // #import "ATCBeautifulView.h" // ATCPasswordCollectionView class @interface ATCPasswordCollectionView : ATCBeautifulView @end // ATCPasswordCollectionView class
Timlis/share-car
ruoyi-car/src/main/java/com/ruoyi/car/service/ICountNumService.java
<reponame>Timlis/share-car package com.ruoyi.car.service; import com.ruoyi.car.domain.*; /** * @author timlis * @date 2021/02/18 */ public interface ICountNumService { CountNums countFirstPageNums(); CountLineNum countLineNums(); CountPieNums countPieNums(); BarValue[] countBarNums(); }
fossabot/go-labs
lab083/lab002/main.go
package main import ( "context" "fmt" elastic "github.com/olivere/elastic" "io/ioutil" "log" "math/rand" "os" "os/signal" "syscall" "time" ) type ActionLog struct { PlayerId int `json:"playerId"` Cmd int `json:"cmd"` Content string `json:"content"` } const mapping = ` { "settings":{ "number_of_shards": 1, "number_of_replicas": 0 }, "mappings":{ "actionLog":{ "properties":{ "playerId":{ "type":"keyword" }, "cmd":{ "type":"keyword" } } } } }` const ( INDEX_NAME = "server900001" TYPE_NAME = "actionLog" ) func main() { //读取ip data, err := ioutil.ReadFile("ip.conf") if err != nil { log.Fatalf("ReadFile error:%v", err) } url := string(data) log.Printf("url=%s\n", url) // Starting with elastic.v5, you must pass a context to execute each service ctx := context.Background() // Obtain a client and connect to the default Elasticsearch installation // on 127.0.0.1:9200. Of course you can configure your client to connect // to other hosts and configure it in various other ways. client, err := elastic.NewClient(elastic.SetURL(url)) if err != nil { log.Fatalf("NewClient error:%v", err) } // Ping the Elasticsearch server to get e.g. the version number info, code, err := client.Ping(url).Do(ctx) if err != nil { log.Fatalf("client.Ping error:%v", err) } log.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number) // Getting the ES version number is quite common, so there's a shortcut esversion, err := client.ElasticsearchVersion(url) if err != nil { log.Fatalf("ElasticsearchVersion error:%v", err) } log.Printf("Elasticsearch version %s\n", esversion) // Use the IndexExists service to check if a specified index exists. exists, err := client.IndexExists(INDEX_NAME).Do(ctx) if err != nil { log.Fatalf("IndexExists error:%v", err) } if !exists { // Create a new index. createIndex, err := client.CreateIndex(INDEX_NAME).BodyString(mapping).Do(ctx) if err != nil { log.Fatalf("CreateIndex error:%v", err) } if !createIndex.Acknowledged { // Not acknowledged } } // Index a tweet (using JSON serialization) actionLog1 := ActionLog{PlayerId: 68, Cmd: 2088, Content: "行为日志"} put1, err := client.Index(). Index(INDEX_NAME). Type(TYPE_NAME). Id("1"). BodyJson(actionLog1). Do(ctx) if err != nil { log.Fatalf("Index error:%v", err) } log.Printf("Indexed tweet %s to index %s, type %s\n", put1.Id, put1.Index, put1.Type) // Index a second tweet (by string) actionLog2 := `{"playerId":67,"cmd":2008,"content":"行为日志2"}` put2, err := client.Index(). Index(INDEX_NAME). Type(TYPE_NAME). Id("2"). BodyString(actionLog2). Do(ctx) if err != nil { log.Fatalf("Index error:%v", err) } log.Printf("Indexed tweet %s to index %s, type %s\n", put2.Id, put2.Index, put2.Type) // Get tweet with specified ID get1, err := client.Get(). Index(INDEX_NAME). Type(TYPE_NAME). Id("1"). Do(ctx) if err != nil { log.Fatalf("Get error:%v", err) } if get1.Found { log.Printf("Got document %s in version %d from index %s, type %s\n", get1.Id, get1.Version, get1.Index, get1.Type) } // Flush to make sure the documents got written. _, err = client.Flush().Index(INDEX_NAME).Do(ctx) if err != nil { log.Fatalf("Flush error:%v", err) } sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT) go func() { playerIds := []int{4, 11, 68, 70} cmds := []int{2001, 2003, 2005, 2401, 2088, 2009, 2006, 2409, 2004, 2007, 2002} i := 0 for { playerId := playerIds[rand.Intn(len(playerIds))] cmd := cmds[rand.Intn(len(cmds))] actionLog := ActionLog{PlayerId: playerId, Cmd: cmd, Content: fmt.Sprintf("行为日志%d", i)} _, err := client.Index(). Index(INDEX_NAME). Type(TYPE_NAME). BodyJson(actionLog). Do(ctx) if err != nil { log.Fatalf("Index error:%v", err) } else { log.Printf("insert success") } i++ time.Sleep(time.Second * 3) } }() <-sigs _, err = client.Flush().Index(INDEX_NAME).Do(ctx) if err != nil { log.Fatalf("Flush error:%v", err) } log.Println("end") }
FXTi/peachfuzz-code
3rdParty/pin/pin-2.13-61206-msvc10-windows/source/tools/Tests/probe.cpp
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2013 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. END_LEGAL */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "pin.H" using namespace std; #if defined (TARGET_MAC) // Mac #define LIBC "libSystem.B.dylib" #else // Linux #define LIBC "libc.so" #endif FILE * trace; BOOL DoneLoad(IMG img) { if (IMG_Type(img) == IMG_TYPE_STATIC) return true; // Give up after libc.so is loaded if (strstr(IMG_Name(img).c_str(), LIBC)) return true; return false; } INT32 readcount = 0; VOID Mem(ADDRINT a, ADDRINT s) {} VOID ImageLoad(IMG img, VOID * v) { fprintf(trace,"Loading %s\n", IMG_Name(img).c_str()); fflush(trace); // Scan the instructions to test image parsing code for (SEC sec = IMG_SecHead(img); SEC_Valid(sec); sec = SEC_Next(sec)) { for (RTN rtn = SEC_RtnHead(sec); RTN_Valid(rtn); rtn = RTN_Next(rtn)) { #if 0 fprintf(trace, "Routine name %s %x\n", RTN_Name(rtn).c_str(), RTN_Address(rtn)); fflush(trace); #endif RTN_Open(rtn); for (INS ins = RTN_InsHead(rtn); INS_Valid(ins); ins = INS_Next(ins)) { if( INS_HasMemoryRead2(ins) ) { INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(Mem), IARG_MEMORYREAD2_EA, IARG_MEMORYREAD_SIZE, IARG_END); } if( INS_IsMemoryRead(ins) ) { //fprintf(trace, "RSize %d %s\n",INS_MemoryReadSize(ins), INS_Disassemble(ins).c_str()); INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(Mem), IARG_MEMORYREAD_EA, IARG_MEMORYREAD_SIZE, IARG_END); } if( INS_IsMemoryWrite(ins) ) { //fprintf(trace, "WSize %d %x %s\n",INS_MemoryWriteSize(ins), INS_Address(ins), INS_Disassemble(ins).c_str()); INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(Mem), IARG_MEMORYWRITE_EA, IARG_MEMORYWRITE_SIZE, IARG_END); } } RTN_Close(rtn); } } if (DoneLoad(img)) { fprintf(trace,"Finished\n"); fclose(trace); exit(0); } } void Trace(TRACE trace, void * v) { static bool first = true; if (first) { ASSERTX(RTN_Valid(TRACE_Rtn(trace))); } first = false; } int main(INT32 argc, CHAR **argv) { // On Mac, ImageLoad() works only after we call PIN_InitSymbols(). // This is not necessary on Linux, but doing it doesn't hurt. PIN_InitSymbols(); trace = fopen("probe.out", "w"); if( PIN_Init(argc, argv) ) { PIN_ERROR("bad commandline\n"); } IMG_AddInstrumentFunction(ImageLoad, 0); TRACE_AddInstrumentFunction(Trace, 0); // Never returns PIN_StartProgram(); return 0; }
ultimoistante/eos-multimedia-scripting
src/eos.modules/eosmodule.g3d/EOSOdeCollisionObject.cpp
/* ----------------------------------------------------------------------------- This source file is part of EOS Multimedia Scripting System For the latest info, see https://github.com/ultimoistante/eos-multimedia-scripting The MIT License (MIT) Copyright (c) 2014-2019 of <NAME> aka ultimoistante of StartupSolutions (mailto: <EMAIL> | www.startupsolutions.it) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "EOSOdeCollisionObject.h" // ----------------------------------------------------------------------------- EOSOdeCollisionObject::EOSOdeCollisionObject() { this->collisionGeometry = 0; this->debugObject = NULL; this->size = Ogre::Vector3::ZERO; // this->vertices = NULL; this->verticesBackup = NULL; this->indices = NULL; this->vertexCount = 0; this->indexCount = 0; } // ----------------------------------------------------------------------------- EOSOdeCollisionObject::~EOSOdeCollisionObject() { if(this->collisionGeometry > 0) dGeomDestroy(this->collisionGeometry); if(this->debugObject != NULL) delete this->debugObject; if(this->vertices != NULL) delete[] this->vertices; if(this->verticesBackup != NULL) delete[] this->verticesBackup; if(this->indices != NULL) delete this->indices; } // ----------------------------------------------------------------------------- /*void EOSOdeCollisionObject::loadTrimeshData(const Ogre::Vector3* vertices, unsigned int vertex_count, const unsigned int* indices, unsigned int index_count) { this->vertexCount = vertex_count; this->indexCount = index_count; this->vertices = new dVector3[vertex_count]; this->indices = new unsigned int[index_count]; for(unsigned int i = 0;i < vertex_count;i++) { this->vertices[i][0] = (dReal)vertices[i].x; this->vertices[i][1] = (dReal)vertices[i].y; this->vertices[i][2] = (dReal)vertices[i].z; } memcpy(this->indices, indices, sizeof(unsigned int) * index_count); this->triMeshData = dGeomTriMeshDataCreate(); dGeomTriMeshDataBuildSimple(this->triMeshData, (const dReal*)this->vertices, (int)vertex_count, (int*)this->indices, (int)index_count); this->collisionGeometry = dCreateTriMesh(getSpaceID(space), this->triMeshData, 0, 0, 0); registerGeometry(); }*/ // ----------------------------------------------------------------------------- void EOSOdeCollisionObject::applyTransform(Ogre::Vector3& position, Ogre::Quaternion& rotation, Ogre::Vector3& scale) { dQuaternion odeQuaternion; odeQuaternion[0] = (dReal)rotation.w; odeQuaternion[1] = (dReal)rotation.x; odeQuaternion[2] = (dReal)rotation.y; odeQuaternion[3] = (dReal)rotation.z; // dGeomSetPosition(this->collisionGeometry, position.x, position.y, position.z); dGeomSetQuaternion(this->collisionGeometry, odeQuaternion); // /*switch(this->collisionGeomType) { case EOSOdeCollisionObject::BoxGeomType: case EOSOdeCollisionObject::SphereGeomType: dGeomSetPosition(this->collisionGeometry, position.x, position.y, position.z); dGeomSetQuaternion(this->collisionGeometry, odeQuaternion); break; case EOSOdeCollisionObject::TrimeshGeomType: // makes a backup of the initial status of the vertices if(this->verticesBackup == NULL) { this->verticesBackup = new dVector3[this->vertexCount]; memcpy(this->verticesBackup, this->vertices, sizeof(unsigned int) * this->vertexCount); } // for(unsigned int i = 0; i < this->vertexCount; i++) { Ogre::Vector3 pt; pt.x = this->verticesBackup[i][0]; pt.y = this->verticesBackup[i][1]; pt.z = this->verticesBackup[i][2]; // applies rotation, traslation and scale pt = (rotation * (pt * scale)) + position; // stores back the vertex this->vertices[i][0] = (dReal)pt.x; this->vertices[i][1] = (dReal)pt.y; this->vertices[i][2] = (dReal)pt.z; } dGeomTriMeshDataBuildSimple(this->triMeshData, (const dReal*)this->vertices, (int)this->vertexCount, (int*)this->indices, (int)this->indexCount); if(this->collisionGeometry) dGeomDestroy(this->collisionGeometry); this->collisionGeometry = dCreateTriMesh(0, this->triMeshData, 0, 0, 0); break; }*/ } // ----------------------------------------------------------------------------- void EOSOdeCollisionObject::setParentObject(void* parentObject) { if(parentObject != NULL && this->collisionGeometry != 0) dGeomSetData(this->collisionGeometry, parentObject); } // ----------------------------------------------------------------------------- void EOSOdeCollisionObject::setActive(bool activityStatus) { if(this->collisionGeometry != 0) { activityStatus ? dGeomEnable(this->collisionGeometry) : dGeomDisable(this->collisionGeometry); } } // ----------------------------------------------------------------------------- bool EOSOdeCollisionObject::isActive() { if(this->collisionGeometry != 0) { return dGeomIsEnabled(this->collisionGeometry); } return false; } // ----------------------------------------------------------------------------- void EOSOdeCollisionObject::showDebugObject(Ogre::SceneNode* parentSceneNode, bool visible) { EOSOdeTrimeshDebugObject* debugObj = NULL; switch(this->collisionGeomType) { case EOSOdeCollisionObject::BoxGeomType: this->debugObject = new EOSOdeBoxDebugObject(this->size); break; case EOSOdeCollisionObject::SphereGeomType: this->debugObject = new EOSOdeSphereDebugObject(this->size.x); break; case EOSOdeCollisionObject::TrimeshGeomType: debugObj = new EOSOdeTrimeshDebugObject((this->indexCount / 3) * 6); debugObj->beginDefinition(); for(unsigned int i = 0, j = 0; i < this->indexCount; i+=3, j+=6) { debugObj->setVertex(j, Ogre::Vector3((Ogre::Real)this->vertices[this->indices[i]][0], (Ogre::Real)this->vertices[this->indices[i]][1], (Ogre::Real)this->vertices[this->indices[i]][2])); debugObj->setVertex(j+1, Ogre::Vector3((Ogre::Real)this->vertices[this->indices[i+1]][0],(Ogre::Real)this->vertices[this->indices[i+1]][1],(Ogre::Real)this->vertices[this->indices[i+1]][2])); debugObj->setVertex(j+2, Ogre::Vector3((Ogre::Real)this->vertices[this->indices[i+1]][0],(Ogre::Real)this->vertices[this->indices[i+1]][1],(Ogre::Real)this->vertices[this->indices[i+1]][2])); debugObj->setVertex(j+3, Ogre::Vector3((Ogre::Real)this->vertices[this->indices[i+2]][0],(Ogre::Real)this->vertices[this->indices[i+2]][1],(Ogre::Real)this->vertices[this->indices[i+2]][2])); debugObj->setVertex(j+4, Ogre::Vector3((Ogre::Real)this->vertices[this->indices[i+2]][0],(Ogre::Real)this->vertices[this->indices[i+2]][1],(Ogre::Real)this->vertices[this->indices[i+2]][2])); debugObj->setVertex(j+5, Ogre::Vector3((Ogre::Real)this->vertices[this->indices[i]][0], (Ogre::Real)this->vertices[this->indices[i]][1], (Ogre::Real)this->vertices[this->indices[i]][2])); } debugObj->endDefinition(); this->debugObject = debugObj; break; case EOSOdeCollisionObject::RayGeomType: dVector3 start, direction; dGeomRayGet(this->collisionGeometry, start, direction); Ogre::Real length = dGeomRayGetLength(this->collisionGeometry); this->debugObject = new EOSOdeRayDebugObject(Ogre::Vector3(start[0], start[1], start[2]), Ogre::Vector3(direction[0], direction[1], direction[2]), length); break; } parentSceneNode->attachObject(this->debugObject); } // -----------------------------------------------------------------------------
UncleSniper/usson
src/org/unclesniper/json/j8/ShortIterator.java
package org.unclesniper.json.j8; public interface ShortIterator extends IteratorBase, IOShortIterator { @Override short nextShort(); }
mulberry-mail/mulberry4-client
MacOS/Sources/Application/General/CPostponeGURL.cp
<reponame>mulberry-mail/mulberry4-client<filename>MacOS/Sources/Application/General/CPostponeGURL.cp /* Copyright (c) 2007 <NAME>. 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. */ // CPostponeGURL.cp // Class to handle a postponed GURL Apple Event at Idle time // Created 24-9-96 #include "CPostponeGURL.h" #include "CCalendarStoreManager.h" #include "CErrorDialog.h" #include "CMailAccountManager.h" #include "CMulberryApp.h" // Static bool CPostponeGURL::sPause = false; // Methods CPostponeGURL::CPostponeGURL(char *text, EType type) { mText = text; mType = type; mFirstTime = true; } CPostponeGURL::~CPostponeGURL() { delete mText; } // Run GURL Event then remove void CPostponeGURL::SpendTime(const EventRecord &inMacEvent) { // Only do if not paused if (!sPause) { if (mType == eMailto) { // Do dialog if first time and not already started servers if (mFirstTime && !CMailAccountManager::sMailAccountManager) { // Do this first to stop re-entrancy since idler is called by alert mFirstTime = false; // Display error/notification CErrorDialog::PoseDialog(CErrorDialog::eErrDialog_Note, "ErrorDialog::Btn::OK", NULL, NULL, NULL, "Alerts::General::WaitGURL"); } // Run the GURL only if SMTP server exists if (CMailAccountManager::sMailAccountManager) { // Stop idling to prevent re-entrancy StopIdling(); // Handle GURL now CMulberryApp::ProcessMailto(mText); // Delete this since it is one-shot delete this; } } else if (mType == eWebcal) { // Run the GURL only if SMTP server exists if (calstore::CCalendarStoreManager::sCalendarStoreManager != NULL) { // Stop idling to prevent re-entrancy StopIdling(); // Handle GURL now CMulberryApp::ProcessWebcal(mText); // Delete this since it is one-shot delete this; } } } }
baweaver/gemsmith
spec/lib/gemsmith/generators/circle_ci_spec.rb
<reponame>baweaver/gemsmith # frozen_string_literal: true require "spec_helper" RSpec.describe Gemsmith::Generators::CircleCI, :temp_dir do let(:cli) { instance_spy Gemsmith::CLI, destination_root: temp_dir } let(:configuration) { {gem: {name: "tester"}, generate: {circle_ci: create_circle_ci}} } subject { described_class.new cli, configuration: configuration } describe "#run" do before { subject.run } context "when enabled" do let(:create_circle_ci) { true } it "creates Circle CI config" do expect(cli).to have_received(:template).with("%gem_name%/circle.yml.tt", configuration) end end context "when disabled" do let(:create_circle_ci) { false } it "does not create Circle CI config" do expect(cli).to_not have_received(:template) end end end end
GeoEngineers/RCOPublicLands
scripts/appClient/src/initializers/initVersionError.js
GeoAppBase.initializePage("VersionError", [], function(options){ MainApplication.views.versionErrorView = new VersionErrorView({}); MainApplication.mainRegion.show(MainApplication.views.versionErrorView); });
wrapper755/diirt
pvmanager/datasource-graphene/src/main/java/org/diirt/datasource/graphene/IntensityGraph2DFunction.java
<reponame>wrapper755/diirt /** * Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.diirt.datasource.graphene; import java.util.Arrays; import java.util.List; import org.diirt.graphene.*; import org.diirt.datasource.QueueCollector; import org.diirt.datasource.ReadFunction; import org.diirt.util.array.ArrayInt; import org.diirt.util.array.ListDouble; import org.diirt.util.array.ListMath; import org.diirt.vtype.ArrayDimensionDisplay; import org.diirt.vtype.VNumberArray; import org.diirt.vtype.ValueFactory; import org.diirt.vtype.ValueUtil; /** * * @author carcassi */ class IntensityGraph2DFunction implements ReadFunction<Graph2DResult> { private ReadFunction<VNumberArray> arrayData; private IntensityGraph2DRenderer renderer = new IntensityGraph2DRenderer(300, 200); private VNumberArray oldData; private Graph2DResult previousResult; private final QueueCollector<IntensityGraph2DRendererUpdate> rendererUpdateQueue = new QueueCollector<>(100); public IntensityGraph2DFunction(ReadFunction<?> arrayData) { this.arrayData = new CheckedReadFunction<VNumberArray>(arrayData, "Data", VNumberArray.class); } public QueueCollector<IntensityGraph2DRendererUpdate> getUpdateQueue() { return rendererUpdateQueue; } @Override public Graph2DResult readValue() { VNumberArray data = arrayData.readValue(); // Data must be available if (data == null) { return null; } List<IntensityGraph2DRendererUpdate> updates = getUpdateQueue().readValue(); // If data is old and no updates, return the previous result if (data == oldData && updates.isEmpty()) { return previousResult; } oldData = data; // TODO: check array is one dimensional Cell2DDataset dataset = DatasetConversions.cell2DDatasetsFromVNumberArray(data); // Process all renderer updates for (IntensityGraph2DRendererUpdate rendererUpdate : updates) { renderer.update(rendererUpdate); } // If no size is set, don't calculate anything if (renderer.getImageHeight() == 0 && renderer.getImageWidth() == 0) return null; GraphBuffer buffer = new GraphBuffer(renderer); renderer.draw(buffer, dataset); return new Graph2DResult(data, ValueUtil.toVImage(buffer.getImage()), new GraphDataRange(renderer.getXPlotRange(), dataset.getXRange(), dataset.getXRange()), new GraphDataRange(renderer.getYPlotRange(), dataset.getYRange(), dataset.getYRange()), -1, selectionData(data, renderer)); } private VNumberArray selectionData(VNumberArray data, IntensityGraph2DRenderer renderer) { if (renderer.getXIndexSelectionRange() == null || renderer.getYIndexSelectionRange() == null) { return null; } ArrayDimensionDisplay xDisplay = data.getDimensionDisplay().get(1); int leftIndex = (int) renderer.getXIndexSelectionRange().getMinimum(); int rightIndex = (int) renderer.getXIndexSelectionRange().getMaximum(); final int xSize = rightIndex - leftIndex + 1; if (xDisplay.isReversed()) { leftIndex = data.getSizes().getInt(1) - 1 - leftIndex; rightIndex = data.getSizes().getInt(1) - 1 - rightIndex; } ArrayDimensionDisplay yDisplay = data.getDimensionDisplay().get(0); int bottomIndex = (int) renderer.getYIndexSelectionRange().getMinimum(); int topIndex = (int) renderer.getYIndexSelectionRange().getMaximum(); if (yDisplay.isReversed()) { bottomIndex = data.getSizes().getInt(0) - 1 - bottomIndex; topIndex = data.getSizes().getInt(0) - 1 - topIndex; } final int ySize = topIndex - bottomIndex + 1; return ValueFactory.newVNumberArray(new ListDouble() { @Override public double getDouble(int index) { throw new UnsupportedOperationException("Not supported yet."); } @Override public int size() { return xSize * ySize; } }, new ArrayInt(ySize, xSize), Arrays.asList(ValueFactory.newDisplay(ListMath.limit(yDisplay.getCellBoundaries(), bottomIndex, topIndex + 1), yDisplay.getUnits()), ValueFactory.newDisplay(ListMath.limit(xDisplay.getCellBoundaries(), leftIndex, rightIndex + 1), yDisplay.getUnits())), data, data, data); } }
npocmaka/Windows-Server-2003
public/internal/net/inc/nameser.h
/*++ Copyright (c) Microsoft Corporation. All rights reserved. Module Name: nameser.h Abstract: Definitions for the DNS resolver and nameserver. Author: <NAME> (mikemas) Jan 31, 1992 Revision History: Who When What -------- -------- ---------------------------------------------- mikemas 01-31-92 created Notes: --*/ /****************************************************************** * * SpiderTCP BIND * * Copyright 1990 Spider Systems Limited * * NAMESER.H * ******************************************************************/ /* * /usr/projects/tcp/SCCS.rel3/rel/src/include/arpa/0/s.nameser.h * @(#)nameser.h 5.3 * * Last delta created 14:06:04 3/4/91 * This file extracted 11:19:28 3/8/91 * * Modifications: * * GSS 20 Jul 90 New File */ /* * Copyright (c) 1983, 1989 Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms are permitted * provided that: (1) source distributions retain this entire copyright * notice and comment, and (2) distributions including binaries display * the following acknowledgement: ``This product includes software * developed by the University of California, Berkeley and its contributors'' * in the documentation or other materials provided with the distribution * and in all advertising materials mentioning features or use of this * software. Neither the name of the University nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * @(#)nameser.h 5.24 (Berkeley) 6/1/90 */ #ifndef _NAMESER_INCLUDED #define _NAMESER_INCLUDED /* * Define constants based on rfc883 */ #define PACKETSZ 512 /* maximum packet size */ #define MAXDNAME 256 /* maximum domain name */ #define MAXCDNAME 255 /* maximum compressed domain name */ #define MAXLABEL 63 /* maximum length of domain label */ /* Number of bytes of fixed size data in query structure */ #define QFIXEDSZ 4 /* number of bytes of fixed size data in resource record */ #define RRFIXEDSZ 10 /* * Internet nameserver port number */ #define NAMESERVER_PORT 53 /* * Currently defined opcodes */ #define QUERY 0x0 /* standard query */ #define IQUERY 0x1 /* inverse query */ #define STATUS 0x2 /* nameserver status query */ /*#define xxx 0x3 /* 0x3 reserved */ /* non standard */ #define UPDATEA 0x9 /* add resource record */ #define UPDATED 0xa /* delete a specific resource record */ #define UPDATEDA 0xb /* delete all nemed resource record */ #define UPDATEM 0xc /* modify a specific resource record */ #define UPDATEMA 0xd /* modify all named resource record */ #define ZONEINIT 0xe /* initial zone transfer */ #define ZONEREF 0xf /* incremental zone referesh */ /* * Currently defined response codes */ #ifndef NOERROR #define NOERROR 0 /* no error */ #endif #define FORMERR 1 /* format error */ #define SERVFAIL 2 /* server failure */ #define NXDOMAIN 3 /* non existent domain */ #define NOTIMP 4 /* not implemented */ #define REFUSED 5 /* query refused */ /* non standard */ #define NOCHANGE 0xf /* update failed to change db */ /* * Type values for resources and queries */ #define T_A 1 /* host address */ #define T_NS 2 /* authoritative server */ #define T_MD 3 /* mail destination */ #define T_MF 4 /* mail forwarder */ #define T_CNAME 5 /* connonical name */ #define T_SOA 6 /* start of authority zone */ #define T_MB 7 /* mailbox domain name */ #define T_MG 8 /* mail group member */ #define T_MR 9 /* mail rename name */ #define T_NULL 10 /* null resource record */ #define T_WKS 11 /* well known service */ #define T_PTR 12 /* domain name pointer */ #define T_HINFO 13 /* host information */ #define T_MINFO 14 /* mailbox information */ #define T_MX 15 /* mail routing information */ #define T_TXT 16 /* text strings */ #define T_AFSDB 18 /* AFS database servers */ #define T_ATMA 34 /* ATM endpoint address */ /* non standard */ #define T_UINFO 100 /* user (finger) information */ #define T_UID 101 /* user ID */ #define T_GID 102 /* group ID */ #define T_UNSPEC 103 /* Unspecified format (binary data) */ /* Query type values which do not appear in resource records */ #define T_AXFR 252 /* transfer zone of authority */ #define T_MAILB 253 /* transfer mailbox records */ #define T_MAILA 254 /* transfer mail agent records */ #define T_ANY 255 /* wildcard match */ /* * Values for class field */ #define C_IN 1 /* the arpa internet */ #define C_CHAOS 3 /* for chaos net at MIT */ #define C_HS 4 /* for Hesiod name server at MIT */ /* Query class values which do not appear in resource records */ #define C_ANY 255 /* wildcard match */ /* * Status return codes for T_UNSPEC conversion routines */ #define CONV_SUCCESS 0 #define CONV_OVERFLOW -1 #define CONV_BADFMT -2 #define CONV_BADCKSUM -3 #define CONV_BADBUFLEN -4 #ifndef BYTE_ORDER #define LITTLE_ENDIAN 1234 /* least-significant byte first (vax) */ #define BIG_ENDIAN 4321 /* most-significant byte first (IBM, net) */ #define PDP_ENDIAN 3412 /* LSB first in word, MSW first in long (pdp) */ #if defined(vax) || defined(ns32000) || defined(sun386) || defined(MIPSEL) || \ defined(BIT_ZERO_ON_RIGHT) #define BYTE_ORDER LITTLE_ENDIAN #endif #if defined(sel) || defined(pyr) || defined(mc68000) || defined(sparc) || \ defined(is68k) || defined(tahoe) || defined(ibm032) || defined(ibm370) || \ defined(MIPSEB) || defined (BIT_ZERO_ON_LEFT) #define BYTE_ORDER BIG_ENDIAN #endif #ifndef BYTE_ORDER /* still not defined */ #if defined(u3b2) || defined(m68k) #define BYTE_ORDER BIG_ENDIAN #endif #if defined(i286) || defined(i386) || defined(_AMD64_) || defined(_IA64_) #define BYTE_ORDER LITTLE_ENDIAN #endif #endif /* ~BYTE_ORDER */ #endif /* BYTE_ORDER */ #ifndef BYTE_ORDER /* you must determine what the correct bit order is for your compiler */ UNDEFINED_BIT_ORDER; #endif /* * Structure for query header, the order of the fields is machine and * compiler dependent, in our case, the bits within a byte are assignd * least significant first, while the order of transmition is most * significant first. This requires a somewhat confusing rearrangement. */ typedef struct { unsigned short id; /* query identification number */ #if BYTE_ORDER == BIG_ENDIAN /* fields in third byte */ unsigned char qr:1; /* response flag */ unsigned char opcode:4; /* purpose of message */ unsigned char aa:1; /* authoritive answer */ unsigned char tc:1; /* truncated message */ unsigned char rd:1; /* recursion desired */ /* fields in fourth byte */ unsigned char ra:1; /* recursion available */ unsigned char pr:1; /* primary server required (non standard) */ unsigned char unused:2; /* unused bits */ unsigned char rcode:4; /* response code */ #endif #if BYTE_ORDER == LITTLE_ENDIAN || BYTE_ORDER == PDP_ENDIAN /* fields in third byte */ unsigned char rd:1; /* recursion desired */ unsigned char tc:1; /* truncated message */ unsigned char aa:1; /* authoritive answer */ unsigned char opcode:4; /* purpose of message */ unsigned char qr:1; /* response flag */ /* fields in fourth byte */ unsigned char rcode:4; /* response code */ unsigned char unused:2; /* unused bits */ unsigned char pr:1; /* primary server required (non standard) */ unsigned char ra:1; /* recursion available */ #endif /* remaining bytes */ unsigned short qdcount; /* number of question entries */ unsigned short ancount; /* number of answer entries */ unsigned short nscount; /* number of authority entries */ unsigned short arcount; /* number of resource entries */ } HEADER; /* * Defines for handling compressed domain names */ #define INDIR_MASK 0xc0 /* * Structure for passing resource records around. */ struct rrec { short r_zone; /* zone number */ short r_class; /* class number */ short r_type; /* type number */ unsigned long r_ttl; /* time to live */ int r_size; /* size of data area */ char *r_data; /* pointer to data */ }; extern unsigned short _getshort(); extern unsigned long _getlong(); /* * Inline versions of get/put short/long. * Pointer is advanced; we assume that both arguments * are lvalues and will already be in registers. * cp MUST be unsigned char *. */ #define GETSHORT(s, cp) { \ (s) = *(cp)++ << 8; \ (s) |= *(cp)++; \ } #define GETLONG(l, cp) { \ (l) = *(cp)++ << 8; \ (l) |= *(cp)++; (l) <<= 8; \ (l) |= *(cp)++; (l) <<= 8; \ (l) |= *(cp)++; \ } #define PUTSHORT(s, cp) { \ *(cp)++ = (s) >> 8; \ *(cp)++ = (s); \ } /* * Warning: PUTLONG destroys its first argument. */ #define PUTLONG(l, cp) { \ (cp)[3] = l; \ (cp)[2] = (l >>= 8); \ (cp)[1] = (l >>= 8); \ (cp)[0] = l >> 8; \ (cp) += sizeof(unsigned long); \ } #endif // _NAMESER_INCLUDED
zhangpf/fuchsia-rs
src/media/playback/mediaplayer/demux/reader_cache.cc
<reponame>zhangpf/fuchsia-rs<filename>src/media/playback/mediaplayer/demux/reader_cache.cc // Copyright 2016 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/media/playback/mediaplayer/demux/reader_cache.h" #include "lib/async/cpp/task.h" #include "lib/async/default.h" #include "src/lib/fxl/logging.h" namespace media_player { namespace { static constexpr size_t kDefaultChunkSize = 256 * 1024; // When calculating how much to read from the upstream reader before the demuxer // will miss the cache, we multiply by this factor to be conservative. static constexpr float kConservativeFactor = 0.8; static constexpr size_t kByteRateMaxSamples = 8; } // namespace // static std::shared_ptr<ReaderCache> ReaderCache::Create(std::shared_ptr<Reader> upstream_reader) { return std::make_shared<ReaderCache>(upstream_reader); } ReaderCache::ReaderCache(std::shared_ptr<Reader> upstream_reader) : upstream_reader_(upstream_reader), dispatcher_(async_get_default_dispatcher()), demux_byte_rate_(kByteRateMaxSamples), upstream_reader_byte_rate_(kByteRateMaxSamples) { upstream_reader_->Describe( [this, upstream_reader](zx_status_t status, size_t size, bool can_seek) { upstream_size_ = size; upstream_can_seek_ = can_seek; last_status_ = status; describe_is_complete_.Occur(); }); } ReaderCache::~ReaderCache() {} void ReaderCache::Describe(DescribeCallback callback) { describe_is_complete_.When([this, callback = std::move(callback)]() mutable { callback(last_status_, upstream_size_, upstream_can_seek_); }); } void ReaderCache::ReadAt(size_t position, uint8_t* buffer, size_t bytes_to_read, ReadAtCallback callback) { FXL_DCHECK(buffer); FXL_DCHECK(bytes_to_read > 0); describe_is_complete_.When( [this, position, buffer, bytes_to_read, callback = std::move(callback)]() mutable { if (demux_sampler_) { demux_byte_rate_.AddSample( ByteRateEstimator::ByteRateSampler::FinishSample(std::move(*demux_sampler_))); } if (!buffer_) { buffer_ = SlidingBuffer(capacity_); } ServeReadAtRequest({.callback = std::move(callback), .original_position = position, .total_bytes = bytes_to_read, .position = position, .bytes_to_read = bytes_to_read, .buffer = buffer}); }); } void ReaderCache::SetCacheOptions(size_t capacity, size_t max_backtrack) { FXL_DCHECK(!load_in_progress_) << "SetCacheOptions cannot be called while a load is" " in progress."; buffer_ = SlidingBuffer(capacity); capacity_ = capacity; max_backtrack_ = max_backtrack; } void ReaderCache::ServeReadAtRequest(ReaderCache::ReadAtRequest request) { FXL_DCHECK(buffer_); FXL_DCHECK(request.buffer); FXL_DCHECK(request.callback); FXL_DCHECK(request.position < upstream_size_); size_t bytes_read = buffer_->Read(request.position, request.buffer, request.bytes_to_read); size_t remaining_bytes = upstream_size_ - request.position; if ((bytes_read == request.bytes_to_read) || (bytes_read == remaining_bytes)) { demux_sampler_ = ByteRateEstimator::ByteRateSampler::StartSample(bytes_read); const size_t bytes_we_will_not_read = request.bytes_to_read - bytes_read; request.callback(ZX_OK, request.total_bytes - bytes_we_will_not_read); return; } StartLoadForPosition( request.position + bytes_read, [this, bytes_read, request = std::move(request)](zx_status_t status) mutable { if (status != ZX_OK) { request.callback(status, request.position + bytes_read - request.original_position); return; } ServeReadAtRequest({ .callback = std::move(request.callback), .original_position = request.original_position, .total_bytes = request.total_bytes, .position = request.position + bytes_read, .bytes_to_read = request.bytes_to_read - bytes_read, .buffer = request.buffer + bytes_read, }); }); } void ReaderCache::StartLoadForPosition(size_t position, fit::function<void(zx_status_t)> load_callback) { FXL_DCHECK(buffer_); FXL_DCHECK(!load_in_progress_); load_in_progress_ = true; auto load_range = CalculateLoadRange(position); FXL_DCHECK(load_range) << "The media is fully cached for the read, but a load was requested."; auto [load_start, load_size] = *load_range; auto holes = buffer_->Slide(load_start, std::min({load_size, upstream_size_ - load_start, buffer_->capacity() - max_backtrack_})); FillHoles(holes, [this, load_callback = std::move(load_callback)](zx_status_t status) mutable { load_in_progress_ = false; if (load_callback) { load_callback(status); } }); } std::optional<std::pair<size_t, size_t>> ReaderCache::CalculateLoadRange(size_t position) { FXL_DCHECK(buffer_); auto next_missing_byte = buffer_->NextMissingByte(position); if (next_missing_byte == upstream_size_) { // The media is buffered until the end. return std::nullopt; } size_t bytes_until_demux_misses = next_missing_byte - position; const std::pair<size_t, size_t> defaultRange = {position, kDefaultChunkSize}; std::optional<float> demux_byte_rate_estimate = demux_byte_rate_.Estimate(); std::optional<float> upstream_reader_byte_rate_estimate = upstream_reader_byte_rate_.Estimate(); if (!demux_byte_rate_estimate || !upstream_reader_byte_rate_estimate) { // We don't have enough information to make an informed estimation so we // defer to our configuration. return defaultRange; } float time_until_demux_misses = float(bytes_until_demux_misses) / (*demux_byte_rate_estimate); float bytes_we_can_read_before_demux_misses = time_until_demux_misses * (*upstream_reader_byte_rate_estimate) * kConservativeFactor; if (bytes_we_can_read_before_demux_misses < 1) { // Cache misses are inevitable. We fall back to our configuration in this // case to avoid many small waits. return defaultRange; } return std::make_pair(position, size_t(bytes_we_can_read_before_demux_misses)); } void ReaderCache::FillHoles(std::vector<SlidingBuffer::Block> holes, fit::function<void(zx_status_t)> callback) { upstream_reader_sampler_ = ByteRateEstimator::ByteRateSampler::StartSample(holes.back().size); upstream_reader_->ReadAt( holes.back().start, holes.back().buffer, holes.back().size, [this, holes, callback = std::move(callback)](zx_status_t status, size_t bytes_read) mutable { last_status_ = status; if (status == ZX_OK && upstream_reader_sampler_) { upstream_reader_byte_rate_.AddSample(ByteRateEstimator::ByteRateSampler::FinishSample( std::move(*upstream_reader_sampler_))); } upstream_reader_sampler_ = std::nullopt; holes.pop_back(); if (holes.empty()) { callback(status); return; } FillHoles(holes, std::move(callback)); }); } } // namespace media_player
ramkumarkoppu/NUCLEO-F767ZI-ESW
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Middlewares/ST/TouchGFX/touchgfx/framework/include/touchgfx/InternalFlashFont.hpp
/** ****************************************************************************** * This file is part of the TouchGFX 4.10.0 distribution. * * <h2><center>&copy; Copyright (c) 2018 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ #ifndef INTERNALFLASHFONT_HPP #define INTERNALFLASHFONT_HPP #include <touchgfx/ConstFont.hpp> namespace touchgfx { /** * @class InternalFlashFont InternalFlashFont.hpp touchgfx/InternalFlashFont.hpp * * @brief An InternalFlashFont has both glyph table and glyph data placed in a flash which supports * random access read (i.e. not a NAND flash). * * An InternalFlashFont has both glyph table and glyph data placed in a flash which * supports random access read (i.e. not a NAND flash) * * @see ConstFont */ class InternalFlashFont : public ConstFont { public: /** * @fn InternalFlashFont::InternalFlashFont(const GlyphNode* list, uint16_t size, uint16_t height, uint8_t pixBelowBase, uint8_t bitsPerPixel, uint8_t maxLeft, uint8_t maxRight, const uint8_t* glyphDataInternalFlash, const KerningNode* kerningList, const Unicode::UnicodeChar fallbackChar, const Unicode::UnicodeChar ellipsisChar); * * @brief Constructor. * * Construct the InternalFlashFont. * * @param list The array of glyphs known to this font. * @param size The number of glyphs in list. * @param height The height in pixels of the highest character in this font. * @param pixBelowBase The maximum number of pixels that can be drawn below the * baseline in this font. * @param bitsPerPixel The number of bits per pixel in this font. * @param maxLeft The maximum a character extends to the left. * @param maxRight The maximum a character extends to the right. * @param glyphDataInternalFlash Pointer to the glyph data for the font, placed in internal * flash. * @param kerningList pointer to the kerning data for the font, placed in internal * flash. * @param fallbackChar The fallback character for the typography in case no glyph is * available. * @param ellipsisChar The ellipsis character used for truncating long texts. */ InternalFlashFont(const GlyphNode* list, uint16_t size, uint16_t height, uint8_t pixBelowBase, uint8_t bitsPerPixel, uint8_t maxLeft, uint8_t maxRight, const uint8_t* glyphDataInternalFlash, const KerningNode* kerningList, const Unicode::UnicodeChar fallbackChar, const Unicode::UnicodeChar ellipsisChar); /** * @fn virtual const uint8_t* InternalFlashFont::getPixelData(const GlyphNode* glyph) const; * * @brief Obtains a RAM-based pointer to the pixel data for the specified glyph. * * Obtains a RAM-based pointer to the pixel data for the specified glyph. * * @param glyph The glyph to get the pixels data of. * * @return The pixel data of the glyph. */ virtual const uint8_t* getPixelData(const GlyphNode* glyph) const; /** * @fn virtual int8_t InternalFlashFont::getKerning(Unicode::UnicodeChar prevChar, const GlyphNode* glyph) const; * * @brief Gets the kerning distance between two characters. * * Gets the kerning distance between two characters. * * @param prevChar The unicode value of the previous character. * @param glyph the glyph object for the current character. * * @return The kerning distance between prevChar and glyph char. */ virtual int8_t getKerning(Unicode::UnicodeChar prevChar, const GlyphNode* glyph) const; private: InternalFlashFont() : ConstFont(0, 0, 0, 0, 0, 0, 0, 0, 0) { } const uint8_t* glyphData; ///< Information describing the glyph const KerningNode* kerningData; ///< Information describing the kerning }; } // namespace touchgfx #endif // INTERNALFLASHFONT_HPP
myArea51/binnavi
src/main/java/com/google/security/zynamics/binnavi/Importers/CImporterFactory.java
<reponame>myArea51/binnavi<gh_stars>10-100 /* Copyright 2011-2016 Google Inc. 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. */ package com.google.security.zynamics.binnavi.Importers; import com.google.common.base.Preconditions; import com.google.security.zynamics.binnavi.CUtilityFunctions; import com.google.security.zynamics.binnavi.Database.Interfaces.IDatabase; import com.google.security.zynamics.binnavi.Gui.IdaSelectionDialog.CIdaSelectionDialog; import com.google.security.zynamics.binnavi.Gui.IdbSelection.CIdbSelectionDialog; import com.google.security.zynamics.binnavi.config.ConfigManager; import com.google.security.zynamics.zylib.gui.CMessageBox; import com.google.security.zynamics.zylib.system.IdaException; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import javax.swing.JFrame; /** * Factory class for importing modules depending on a chosen exporter. */ public final class CImporterFactory { /** * You are not supposed to instantiate this class. */ private CImporterFactory() { } /** * Returns the location of the IDA Pro installation directory * * @param parent Parent frame of the file dialog. * @return The absolute path to the IDA Pro installation directory * @throws FileNotFoundException Thrown if IDA Pro can't be found. */ private static String getIdaDirectory(final JFrame parent) throws FileNotFoundException { final String idaLocation = ConfigManager.instance().getGeneralSettings().getIdaDirectory(); final File idaExec = new File(idaLocation); if (idaExec.exists()) { return idaExec.getAbsolutePath(); } do { final String newIdaLocation = promptForIdaDirectory(parent); if (newIdaLocation != null) { return newIdaLocation; } } while (true); } /** * Imports an IDB file while showing a progress dialog. * * @param idaDirectory Location of the IDA Pro installation directory * @param idbFile Location of the IDB file to import. * @param database Import target. * @param exporter * @throws ImportFailedException Thrown if some kind of problem occurred during the import * process. */ private static void importIdbFileInternal(final String idaDirectory, final String idbFile, final IDatabase database, final CBaseExporter exporter) throws ImportFailedException { try { exporter.importModule(idbFile, idaDirectory, database); } catch (final ConfigFileException exception) { throw new ImportFailedException(String.format( "Could not create the IDA2SQL temp file." + "\n" + "Importing project failed.")); } catch (final IdaException exception) { throw new ImportFailedException(String.format( "Could not start IDA Pro." + "\n" + "Importing project failed.")); } catch (final ExporterException exception) { throw new ImportFailedException(exception.getLocalizedMessage()); } } /** * Shows a dialog that asks the user for the location of the IDA Pro installation directory * * @param parent Parent window used for dialogs. * @return The location of the IDA Pro executable or null if the selected file does not exist. * @throws FileNotFoundException Thrown if no IDA Pro executable file was selected. */ private static String promptForIdaDirectory(final JFrame parent) throws FileNotFoundException { // If the IDA location is invalid, tell the user to select the location CMessageBox.showError( parent, "Could not locate IDA Pro. Please select the IDA Pro installation directory"); final CIdaSelectionDialog fileChooser = CIdaSelectionDialog.show( parent, ConfigManager.instance().getGeneralSettings().getIdaDirectory()); if (fileChooser.getSelectedFile() != null) { final File idaDirectory = fileChooser.getSelectedFile(); // The returned file path does not exist, keep asking... if (!idaDirectory.exists()) { return null; } ConfigManager.instance().getGeneralSettings().setIdaDirectory(idaDirectory.getAbsolutePath()); return idaDirectory.getAbsolutePath(); } throw new FileNotFoundException( "E00211: The IDA directory is invalid or not set, please configure the location of your IDA."); } /** * Updates the list of previous directories. * * @param lastDirectories The list to update. * @param selectedFiles The files selected by the user. */ private static void updatePreviousFiles( final List<String> lastDirectories, final List<File> selectedFiles) { final int MAXIMUM_LIST_SIZE = 5; final Set<String> selectedDirectories = new LinkedHashSet<String>(); for (final File file : selectedFiles) { selectedDirectories.add(file.getParent()); if (selectedDirectories.size() == MAXIMUM_LIST_SIZE) { break; } } for (final String lastDirectory : lastDirectories) { selectedDirectories.add(lastDirectory); if (selectedDirectories.size() == MAXIMUM_LIST_SIZE) { break; } } lastDirectories.clear(); lastDirectories.addAll(selectedDirectories); } /** * Imports IDB Files. Use this function if you want to import IDB files by showing a dialog to let * the user choose the IDB files. * * @param parent Parent frame of the file chooser. * @param database Import target. * @param failedImports The list will return the modules which failed to import. * @return The result of the import operation. * * @throws FileNotFoundException Thrown if the IDA Pro executable could not be found. * @throws ExecutionException Thrown if fetching the result from the background worker threads * failed because the thread itself threw an exception. * @throws InterruptedException Thrown if one of the background worker threads have been * interrupted during processing. */ public static boolean importModules(final JFrame parent, final IDatabase database, final List<CFailedImport> failedImports) throws FileNotFoundException, InterruptedException, ExecutionException { Preconditions.checkNotNull(parent, "IE02358: parent argument can not be null"); Preconditions.checkNotNull(database, "IE02359: database argument can not be null"); Preconditions.checkNotNull(failedImports, "IE02361: failedImports argument can not be null"); final List<String> lastDirectories = ConfigManager.instance().getGeneralSettings().getIdbDirectories(); // Try to reopen the directory of the last selected IDB file final CIdbSelectionDialog dialogIdb = CIdbSelectionDialog.show(parent, lastDirectories); final List<File> selectedFiles = dialogIdb == null ? new ArrayList<File>() : dialogIdb.getSelectedFiles(); if (selectedFiles.isEmpty()) { return false; } final CBaseExporter exporter = new CBinExportImporter(); ConfigManager.instance() .getGeneralSettings().setDefaultExporter(dialogIdb.getSelectedExporter().ordinal()); updatePreviousFiles(lastDirectories, selectedFiles); final ExecutorService executor = Executors.newFixedThreadPool( dialogIdb.getNumberOfParallelImports()); final List<Future<CFailedImport>> results = new ArrayList<Future<CFailedImport>>(); try { // To import from IDA, it's necessary to know where IDA is. final String idaDirectory = getIdaDirectory(parent); for (final File file : selectedFiles) { if (!file.exists()) { CMessageBox.showError(parent, String.format("The selected IDB file '%s' does not exist.", file.getAbsolutePath())); continue; } results.add(executor.submit(new Callable<CFailedImport>() { @Override public CFailedImport call() { try { importIdbFileInternal(idaDirectory, file.getAbsolutePath(), database, exporter); return null; } catch (final ImportFailedException exception) { CUtilityFunctions.logException(exception); return new CFailedImport(file.getAbsolutePath(), exception); } } })); } for (final Future<CFailedImport> future : results) { if (future.get() != null) { failedImports.add(future.get()); } } return true; } catch (final FileNotFoundException e) { CUtilityFunctions.logException(e); throw new FileNotFoundException(String.format( "Invalid IDA Pro executable file." + "\n" + "Importing project failed.")); } } }
Acidburn0zzz/bareos
src/filed/verify_vol.cc
/* BAREOS® - Backup Archiving REcovery Open Sourced Copyright (C) 2002-2010 Free Software Foundation Europe e.V. Copyright (C) 2016-2016 Bareos GmbH & Co. KG This program is Free Software; you can redistribute it and/or modify it under the terms of version three of the GNU Affero General Public License as published by the Free Software Foundation and included in the file LICENSE. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * <NAME>, <NAME> */ /** * @file * Verify files on a Volume * versus attributes in Catalog */ #include "bareos.h" #include "filed.h" /* Data received from Storage Daemon */ static char rec_header[] = "rechdr %ld %ld %ld %ld %ld"; /* Forward referenced functions */ /** * Verify attributes of the requested files on the Volume * */ void do_verify_volume(JCR *jcr) { BSOCK *sd, *dir; POOLMEM *fname; /* original file name */ POOLMEM *lname; /* link name */ int32_t stream; uint32_t size; uint32_t VolSessionId, VolSessionTime, file_index; uint32_t record_file_index; char digest[BASE64_SIZE(CRYPTO_DIGEST_MAX_SIZE)]; int type, status; sd = jcr->store_bsock; if (!sd) { Jmsg(jcr, M_FATAL, 0, _("Storage command not issued before Verify.\n")); jcr->setJobStatus(JS_FatalError); return; } dir = jcr->dir_bsock; jcr->setJobStatus(JS_Running); LockRes(); CLIENTRES *client = (CLIENTRES *)GetNextRes(R_CLIENT, NULL); UnlockRes(); uint32_t buf_size; if (client) { buf_size = client->max_network_buffer_size; } else { buf_size = 0; /* use default */ } if (!bnet_set_buffer_size(sd, buf_size, BNET_SETBUF_WRITE)) { jcr->setJobStatus(JS_FatalError); return; } jcr->buf_size = sd->msglen; fname = get_pool_memory(PM_FNAME); lname = get_pool_memory(PM_FNAME); /* * Get a record from the Storage daemon */ while (bget_msg(sd) >= 0 && !job_canceled(jcr)) { /* * First we expect a Stream Record Header */ if (sscanf(sd->msg, rec_header, &VolSessionId, &VolSessionTime, &file_index, &stream, &size) != 5) { Jmsg1(jcr, M_FATAL, 0, _("Record header scan error: %s\n"), sd->msg); goto bail_out; } Dmsg2(30, "Got hdr: FilInx=%d Stream=%d.\n", file_index, stream); /* * Now we expect the Stream Data */ if (bget_msg(sd) < 0) { Jmsg1(jcr, M_FATAL, 0, _("Data record error. ERR=%s\n"), bnet_strerror(sd)); goto bail_out; } if (size != ((uint32_t)sd->msglen)) { Jmsg2(jcr, M_FATAL, 0, _("Actual data size %d not same as header %d\n"), sd->msglen, size); goto bail_out; } Dmsg1(30, "Got stream data, len=%d\n", sd->msglen); /* File Attributes stream */ switch (stream) { case STREAM_UNIX_ATTRIBUTES: case STREAM_UNIX_ATTRIBUTES_EX: char *ap, *lp, *fp; Dmsg0(400, "Stream=Unix Attributes.\n"); if ((int)sizeof_pool_memory(fname) < sd->msglen) { fname = realloc_pool_memory(fname, sd->msglen + 1); } if ((int)sizeof_pool_memory(lname) < sd->msglen) { lname = realloc_pool_memory(lname, sd->msglen + 1); } *fname = 0; *lname = 0; /* * An Attributes record consists of: * File_index * Type (FT_types) * Filename * Attributes * Link name (if file linked i.e. FT_LNK) * Extended Attributes (if Win32) */ if (sscanf(sd->msg, "%d %d", &record_file_index, &type) != 2) { Jmsg(jcr, M_FATAL, 0, _("Error scanning record header: %s\n"), sd->msg); Dmsg0(0, "\nError scanning header\n"); goto bail_out; } Dmsg2(30, "Got Attr: FilInx=%d type=%d\n", record_file_index, type); ap = sd->msg; while (*ap++ != ' ') /* skip record file index */ ; while (*ap++ != ' ') /* skip type */ ; /* Save filename and position to attributes */ fp = fname; while (*ap != 0) { *fp++ = *ap++; /* copy filename to fname */ } *fp = *ap++; /* terminate filename & point to attribs */ Dmsg1(200, "Attr=%s\n", ap); /* Skip to Link name */ if (type == FT_LNK || type == FT_LNKSAVED) { lp = ap; while (*lp++ != 0) { ; } pm_strcat(lname, lp); /* "save" link name */ } else { *lname = 0; } jcr->lock(); jcr->JobFiles++; jcr->num_files_examined++; pm_strcpy(jcr->last_fname, fname); /* last file examined */ jcr->unlock(); /* * Send file attributes to Director * File_index * Stream * Verify Options * Filename (full path) * Encoded attributes * Link name (if type==FT_LNK) * For a directory, link is the same as fname, but with trailing * slash. For a linked file, link is the link. */ /* Send file attributes to Director */ Dmsg2(200, "send ATTR inx=%d fname=%s\n", jcr->JobFiles, fname); if (type == FT_LNK || type == FT_LNKSAVED) { status = dir->fsend("%d %d %s %s%c%s%c%s%c", jcr->JobFiles, STREAM_UNIX_ATTRIBUTES, "pinsug5", fname, 0, ap, 0, lname, 0); /* for a deleted record, we set fileindex=0 */ } else if (type == FT_DELETED) { status = dir->fsend("%d %d %s %s%c%s%c%c", 0, STREAM_UNIX_ATTRIBUTES, "pinsug5", fname, 0, ap, 0, 0); } else { status = dir->fsend("%d %d %s %s%c%s%c%c", jcr->JobFiles, STREAM_UNIX_ATTRIBUTES, "pinsug5", fname, 0, ap, 0, 0); } Dmsg2(200, "filed>dir: attribs len=%d: msg=%s\n", dir->msglen, dir->msg); if (!status) { Jmsg(jcr, M_FATAL, 0, _("Network error in send to Director: ERR=%s\n"), bnet_strerror(dir)); goto bail_out; } break; case STREAM_MD5_DIGEST: bin_to_base64(digest, sizeof(digest), (char *)sd->msg, CRYPTO_DIGEST_MD5_SIZE, true); Dmsg2(400, "send inx=%d MD5=%s\n", jcr->JobFiles, digest); dir->fsend("%d %d %s *MD5-%d*", jcr->JobFiles, STREAM_MD5_DIGEST, digest, jcr->JobFiles); Dmsg2(20, "filed>dir: MD5 len=%d: msg=%s\n", dir->msglen, dir->msg); break; case STREAM_SHA1_DIGEST: bin_to_base64(digest, sizeof(digest), (char *)sd->msg, CRYPTO_DIGEST_SHA1_SIZE, true); Dmsg2(400, "send inx=%d SHA1=%s\n", jcr->JobFiles, digest); dir->fsend("%d %d %s *SHA1-%d*", jcr->JobFiles, STREAM_SHA1_DIGEST, digest, jcr->JobFiles); Dmsg2(20, "filed>dir: SHA1 len=%d: msg=%s\n", dir->msglen, dir->msg); break; case STREAM_SHA256_DIGEST: bin_to_base64(digest, sizeof(digest), (char *)sd->msg, CRYPTO_DIGEST_SHA256_SIZE, true); Dmsg2(400, "send inx=%d SHA256=%s\n", jcr->JobFiles, digest); dir->fsend("%d %d %s *SHA256-%d*", jcr->JobFiles, STREAM_SHA256_DIGEST, digest, jcr->JobFiles); Dmsg2(20, "filed>dir: SHA256 len=%d: msg=%s\n", dir->msglen, dir->msg); break; case STREAM_SHA512_DIGEST: bin_to_base64(digest, sizeof(digest), (char *)sd->msg, CRYPTO_DIGEST_SHA512_SIZE, true); Dmsg2(400, "send inx=%d SHA512=%s\n", jcr->JobFiles, digest); dir->fsend("%d %d %s *SHA512-%d*", jcr->JobFiles, STREAM_SHA512_DIGEST, digest, jcr->JobFiles); Dmsg2(20, "filed>dir: SHA512 len=%d: msg=%s\n", dir->msglen, dir->msg); break; case STREAM_RESTORE_OBJECT: jcr->lock(); jcr->JobFiles++; jcr->num_files_examined++; jcr->unlock(); Dmsg2(400, "send inx=%d STREAM_RESTORE_OBJECT-%d\n", jcr->JobFiles, STREAM_RESTORE_OBJECT); dir->fsend("%d %d %s %s%c%c%c", jcr->JobFiles, STREAM_RESTORE_OBJECT, "ReStOrEObJeCt", fname, 0, 0, 0); break; /* Ignore everything else */ default: break; } /* end switch */ } /* end while bnet_get */ jcr->setJobStatus(JS_Terminated); goto ok_out; bail_out: jcr->setJobStatus(JS_ErrorTerminated); ok_out: cleanup_compression(jcr); free_pool_memory(fname); free_pool_memory(lname); Dmsg2(050, "End Verify-Vol. Files=%d Bytes=%" lld "\n", jcr->JobFiles, jcr->JobBytes); }
octoblu/beekeeper-util
test/services/travis/travis-rate-limit-spec.js
<filename>test/services/travis/travis-rate-limit-spec.js const { beforeEach, afterEach, describe, it } = global const { expect } = require("chai") const TravisService = require("../../../lib/services/travis-service") const TravisMocks = require("./travis-mocks") describe("Travis: is rate limited", function() { describe("when travis responds with a 403", function() { beforeEach("create service", function() { this.sut = new TravisService({ travisEnv: this.envVars, githubToken: "github-<PASSWORD>", travisEnabled: true, }) }) beforeEach("setup travis mocks", function() { this.travisMocks = new TravisMocks({ githubToken: "<PASSWORD>", isPrivate: false, }) }) afterEach("clean up travis mocks", function() { this.travisMocks.cleanup() }) beforeEach("setup travis endpoints", function() { this.travisMocks.authed.get("/repos/some-owner/example-repo-name").reply(403) }) it("should be rejected", function() { const options = { projectName: "example-repo-name", projectOwner: "some-owner", isPrivate: false, } expect(this.sut.configure(options)).to.be.rejected }) }) })
eclipseguru/p4eclipse
src/3.7/plugins/com.perforce.team.ui/src/com/perforce/team/ui/p4java/actions/AsyncEnablementAction.java
/** * Copyright (c) 2010 Perforce Software. All rights reserved. */ package com.perforce.team.ui.p4java.actions; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.jface.action.IAction; import org.eclipse.team.core.TeamException; import com.perforce.team.core.PerforceProviderPlugin; import com.perforce.team.core.p4java.IP4Connection; import com.perforce.team.core.p4java.IP4Resource; import com.perforce.team.core.p4java.P4Runnable; import com.perforce.team.core.p4java.P4Runner; import com.perforce.team.ui.P4ConnectionManager; import com.perforce.team.ui.PerforceUIPlugin; /** * @author <NAME> (<EMAIL>) */ public abstract class AsyncEnablementAction extends P4Action { private ISchedulingRule enablementRule = P4Runner.createRule(); /** * Determine if any elements in the selection are associated with a * connection that is non-offline and non-connection. This determines * whether the {@link #isEnabledEx()} should be run on the UI-thread. * * @return true to run {@link #isEnabledEx()} off the ui-thread, false to run * off UI-thread */ private boolean loadEnablementAsync() { boolean useAsync = false; if (PerforceUIPlugin.isUIThread() && this.getSelection() != null) { for (Object select : this.getSelection().toArray()) { IResource resource = getResource(select); if (resource != null) { IP4Connection connection = P4ConnectionManager.getManager() .getConnection(resource.getProject(), false); if (isConnected(connection)) { useAsync = true; break; } } else { IP4Resource p4Resource = getP4Resource(select); if (p4Resource != null && isConnected(p4Resource.getConnection())) { useAsync = true; break; } } } } return useAsync; } private boolean isConnected(IP4Connection connection) { return connection != null && !connection.isOffline() && connection.isConnected(); } /** * @see com.perforce.team.ui.actions.PerforceTeamAction#setActionEnablement(org.eclipse.jface.action.IAction) */ @Override protected void setActionEnablement(final IAction action) { if (!loadEnablementAsync()) { super.setActionEnablement(action); } else { action.setEnabled(false); P4Runner.schedule(new P4Runnable() { @Override public void run(IProgressMonitor monitor) { try { action.setEnabled(isEnabledEx()); } catch (TeamException te) { PerforceProviderPlugin.logError(te); } } }, enablementRule); } } }
diktat-static-analysis/juliet-benchmark-java
src/testcases/CWE400_Resource_Exhaustion/s02/CWE400_Resource_Exhaustion__Servlet_13.java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE400_Resource_Exhaustion__Servlet_13.java Label Definition File: CWE400_Resource_Exhaustion__Servlet.label.xml Template File: point-flaw-13.tmpl.java */ /* * @description * CWE: 400 Resource Exhaustion * Sinks: * GoodSink: Size of uploaded file restricted to 10 MB * BadSink : No restriction on upload size * Flow Variant: 13 Control flow: if(IO.STATIC_FINAL_FIVE==5) and if(IO.STATIC_FINAL_FIVE!=5) * * */ package testcases.CWE400_Resource_Exhaustion.s02; import testcasesupport.*; import javax.servlet.http.*; import java.io.FileOutputStream; import java.io.InputStream; import java.io.IOException; import java.util.logging.Level; public class CWE400_Resource_Exhaustion__Servlet_13 extends AbstractTestCaseServlet { public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable { if (IO.STATIC_FINAL_FIVE == 5) { /** * Inspiration from: * http://forums.codecharge.com/posts.php?post_id=44078 * and * http://commons.apache.org/downloads/download_fileupload.cgi * class FileUploadBase, method parseRequest() * class Streams, method copy() * * We don't actually parse out the filename or any of the other data since it really * doesn't matter for this test. (We don't care if part of the HTTP request ends up in * the file. * * Note that if you try to run this file, you'll always get an exception from the bad method. * This is because you've already read the full httprequest stream and stored it into a file. * So, expect the bad method to always fail if you directly run this file from eclipse. */ if (request.getContentType() == null || !request.getContentType().contains("multipart/form-data")) { return; } FileOutputStream streamFileOutput = null; InputStream streamInput = null; try { streamFileOutput = new FileOutputStream("output_bad.dat"); streamInput = request.getInputStream(); for (;;) { byte[] inputBytes = new byte[1024]; int bytesRead = streamInput.read(inputBytes); /* FLAW: no restriction on file size */ if (bytesRead == -1) { break; } streamFileOutput.write(inputBytes); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error!", exceptIO); } finally { try { if (streamInput != null) { streamInput.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing InputStream", exceptIO); } try { if (streamFileOutput != null) { streamFileOutput.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing FileOutputStream", exceptIO); } } response.getWriter().write("Uploaded file!"); } } /* good1() changes IO.STATIC_FINAL_FIVE==5 to IO.STATIC_FINAL_FIVE!=5 */ private void good1(HttpServletRequest request, HttpServletResponse response) throws Throwable { if (IO.STATIC_FINAL_FIVE != 5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Benign, fixed string"); } else { if (request.getContentType() == null || !request.getContentType().contains("multipart/form-data")) { return; } FileOutputStream streamFileOutput = null; InputStream streamInput = null; try { streamFileOutput = new FileOutputStream("output_good.dat"); streamInput = request.getInputStream(); /* set max filesize to 10 MB */ final int MAXSIZE = 10485760; int bytesReadCount = 0; for (;;) { /* FIX: max file size check */ if (bytesReadCount >= MAXSIZE) { response.getWriter().write("File exceeds MAXSIZE!"); break; } byte[] inputBytes = new byte[1024]; int bytesRead = streamInput.read(inputBytes); if (bytesRead == -1) { break; } bytesReadCount += bytesRead; streamFileOutput.write(inputBytes); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error!", exceptIO); } finally { try { if (streamInput != null) { streamInput.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing InputStream", exceptIO); } try { if (streamFileOutput != null) { streamFileOutput.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing FileOutputStream", exceptIO); } } response.getWriter().write("Uploaded file!"); } } /* good2() reverses the bodies in the if statement */ private void good2(HttpServletRequest request, HttpServletResponse response) throws Throwable { if (IO.STATIC_FINAL_FIVE == 5) { if (request.getContentType() == null || !request.getContentType().contains("multipart/form-data")) { return; } FileOutputStream streamFileOutput = null; InputStream streamInput = null; try { streamFileOutput = new FileOutputStream("output_good.dat"); streamInput = request.getInputStream(); /* set max filesize to 10 MB */ final int MAXSIZE = 10485760; int bytesReadCount = 0; for (;;) { /* FIX: max file size check */ if (bytesReadCount >= MAXSIZE) { response.getWriter().write("File exceeds MAXSIZE!"); break; } byte[] inputBytes = new byte[1024]; int bytesRead = streamInput.read(inputBytes); if (bytesRead == -1) { break; } bytesReadCount += bytesRead; streamFileOutput.write(inputBytes); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error!", exceptIO); } finally { try { if (streamInput != null) { streamInput.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing InputStream", exceptIO); } try { if (streamFileOutput != null) { streamFileOutput.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing FileOutputStream", exceptIO); } } response.getWriter().write("Uploaded file!"); } } public void good(HttpServletRequest request, HttpServletResponse response) throws Throwable { good1(request, response); good2(request, response); } /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { mainFromParent(args); } }
amruth2211/Spring-Projects
springBootJdbc/src/test/java/com/springboot/workers/jdbcexample/SpringBootJdbcApplicationTests.java
<filename>springBootJdbc/src/test/java/com/springboot/workers/jdbcexample/SpringBootJdbcApplicationTests.java<gh_stars>0 package com.springboot.workers.jdbcexample; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class SpringBootJdbcApplicationTests { @Test void contextLoads() { } }
midorlo/k12
src/main/java/com/midorlo/k12/configuration/database/FixedH2Dialect.java
package com.midorlo.k12.configuration.database; import java.sql.Types; import org.hibernate.dialect.H2Dialect; /** * <p>FixedH2Dialect class.</p> */ public class FixedH2Dialect extends H2Dialect { /** * <p>Constructor for FixedH2Dialect.</p> */ public FixedH2Dialect() { super(); registerColumnType(Types.FLOAT, "real"); } }
manavshrivastavagit/django-restapi
homeworks/migrations/0002_homework_topic.py
<reponame>manavshrivastavagit/django-restapi # -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-08-09 09:28 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('homeworks', '0001_initial'), ] operations = [ migrations.AddField( model_name='homework', name='topic', field=models.CharField(default='Homework', max_length=50), ), ]
wl4g/dopaas-infra
xcloud-component-integration/backup/xcloud-component-rpc-codec/backup/simple-codec/main/codec/internal/FinalEncodeQueue.java
<reponame>wl4g/dopaas-infra /* * Copyright (C) 2017 ~ 2025 the original author or authors. * <<EMAIL>, <EMAIL>> Technology CO.LTD. * 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. * * Reference to website: http://wl4g.com */ package com.wl4g.component.integration.codec.internal; import java.util.LinkedList; import com.wl4g.component.integration.codec.CodecParameter; import com.wl4g.component.integration.codec.Encoder; import com.wl4g.component.integration.codec.stream.BytesOutputStream; import com.wl4g.component.integration.codec.wrap.Wrapper; /** * Final encode queue will be called in final encode handle. * * FinalEncodeQueue.java * * @version 1.0.0 * @author Wanglsir */ public class FinalEncodeQueue { LinkedList<FinalPair> pairs = new LinkedList<FinalEncodeQueue.FinalPair>(); /** * Add final called wrapper. * * @param wrap * {@linkplain com.wl4g.component.integration.codec.wrap.Wrapper Wrapper} * object. * @param extern * Additional data. */ public void addWrap(Wrapper wrap, Object extern) { pairs.add(new FinalPair(wrap, extern)); } /** * Call final wrapper to encoding final bytes. * * @param encoder * {@linkplain com.wl4g.component.integration.codec.Encoder Encoder} * object. * @param out * Encoding IO stream * @param param * parameters * @throws Exception * exception. */ public void doFinal(Encoder encoder, BytesOutputStream out, CodecParameter param) throws Exception { FinalPair pair = null; while ((pair = pairs.poll()) != null) { pair.wrap.finalEncode(encoder, out, param, pair.extern); } } static class FinalPair { Wrapper wrap; Object extern; public FinalPair(Wrapper wrap, Object extern) { super(); this.wrap = wrap; this.extern = extern; } } }
ScalablyTyped/SlinkyTyped
a/auth0/src/main/scala/typingsSlinky/auth0/mod/BaseImportUsersOptions.scala
package typingsSlinky.auth0.mod import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait BaseImportUsersOptions extends StObject { var connection_id: String = js.native var external_id: js.UndefOr[String] = js.native var send_completion_email: js.UndefOr[Boolean] = js.native var upsert: js.UndefOr[Boolean] = js.native } object BaseImportUsersOptions { @scala.inline def apply(connection_id: String): BaseImportUsersOptions = { val __obj = js.Dynamic.literal(connection_id = connection_id.asInstanceOf[js.Any]) __obj.asInstanceOf[BaseImportUsersOptions] } @scala.inline implicit class BaseImportUsersOptionsMutableBuilder[Self <: BaseImportUsersOptions] (val x: Self) extends AnyVal { @scala.inline def setConnection_id(value: String): Self = StObject.set(x, "connection_id", value.asInstanceOf[js.Any]) @scala.inline def setExternal_id(value: String): Self = StObject.set(x, "external_id", value.asInstanceOf[js.Any]) @scala.inline def setExternal_idUndefined: Self = StObject.set(x, "external_id", js.undefined) @scala.inline def setSend_completion_email(value: Boolean): Self = StObject.set(x, "send_completion_email", value.asInstanceOf[js.Any]) @scala.inline def setSend_completion_emailUndefined: Self = StObject.set(x, "send_completion_email", js.undefined) @scala.inline def setUpsert(value: Boolean): Self = StObject.set(x, "upsert", value.asInstanceOf[js.Any]) @scala.inline def setUpsertUndefined: Self = StObject.set(x, "upsert", js.undefined) } }
DocSpencer77/freesewing
packages/components/src/Draft/index.js
import React from 'react' import Svg from './Svg' import Defs from './Defs' import Part from './Part' const Draft = (props) => ( <Svg embed={props.settings.embed} width={props.width} height={props.height} language={props.settings.locale} id={props.settings.idPrefix + 'svg'} design={props.design || false} style={props.style || {}} viewBox={props.viewBox} className={props.className || 'freesewing draft'} > <Defs units={props.settings.units} parts={props.parts} paperless={props.settings.paperless} design={props.design || false} extraDefs={props.extraDefs} /> <g> {Object.keys(props.parts).map((name) => ( <Part part={props.parts[name]} language={props.settings.locale} paperless={props.settings.paperless} units={props.settings.units} key={name} name={name} focus={props.focus || false} design={props.design || false} raiseEvent={props.raiseEvent} /> ))} </g> </Svg> ) export default Draft
zhongliang001/sysmanage
sys-parent/sys-sequence/sys-sequence-service/src/main/java/com/zl/syssequence/format/SequceFormat.java
<reponame>zhongliang001/sysmanage package com.zl.syssequence.format; import com.zl.common.error.ErrDict; import com.zl.common.exception.ZlException; import com.zl.syssequence.service.SequenceService; import org.springframework.util.StringUtils; import java.util.regex.Pattern; /** * @author zhongliang */ public class SequceFormat implements FormatInterface { /** * 序列的默认占位符 */ private static final String DEFUALT_PLACEHOLDER = "0"; /** * 格式化seq片段 * @param format 片段模板 * @return seq片段 */ @Override public String format(String format,SequenceService sequenceService) { String seq = ""; if(format == null){ throw new ZlException(ErrDict.SEQUENCE_NAME_NULL_CODE); } int i = format.indexOf("["); if (i == -1) { seq = sequenceService.getSeqence(format).toString(); sequenceService.updateSeq(format); return seq; } String seqTemp = format.substring(0,i); String range = format.substring(i + 1, format.lastIndexOf("]")); if(StringUtils.isEmpty(range)){ seq = sequenceService.getSeqence(format).toString(); sequenceService.updateSeq(seqTemp); return seq; } String[] ranges = range.split(","); if (StringUtils.isEmpty(ranges[0])) { return sequenceService.getSeqence(seqTemp).toString(); }else { String regex = "^[0-9]*[1-9][0-9]*$"; Pattern pattern = Pattern.compile(regex); if (!pattern.matcher(ranges[0]).matches()) { throw new ZlException("序列长度必须是数字"); } int length = Integer.parseInt(ranges[0]); seq = sequenceService.getSeqence(seqTemp).toString(); sequenceService.updateSeq(seqTemp); if(seq.length() > length){ sequenceService.resetSeq(seqTemp); seq = sequenceService.getSeqence(seqTemp).toString(); sequenceService.updateSeq(seqTemp); } String placeholder = DEFUALT_PLACEHOLDER; int rl = 2; if(ranges.length == rl){ placeholder = ranges[1]; } while (seq.length() < length){ seq = placeholder + seq; } return seq; } } }
walthill/Rocket3D
src/RocketEngine/render/Color.cpp
<reponame>walthill/Rocket3D<gh_stars>0 #include "Color.h" const float Color::RGB01_CONVERSION = 0.00392156863f; Color Color::black(0, 0, 0); Color Color::white(255, 255, 255); Color Color::grey(127.5f, 127.5f, 127.5f); Color Color::red(255, 0, 0); Color Color::green(0, 255, 0); Color Color::blue(0, 0, 255); Color Color::clear(0, 0, 0, 0); Color::Color() { mColorValue = rkm::Vector4(0,0,0,255); } Color::Color(float r, float g, float b, float a) { mColorValue = rkm::Vector4(r, g, b, a); } Color::~Color() { } void Color::setColor(rkm::Vector3 rgb, float a) { mColorValue = rkm::Vector4(rgb, a); } void Color::setColor(rkm::Vector4 color) { mColorValue = color; } void Color::setColor(float r, float g, float b, float a) { mColorValue = rkm::Vector4(r, g, b, a); } void Color::setColor(float setRGB) { mColorValue = rkm::Vector4(setRGB, setRGB, setRGB, setRGB); }
RedRock-2017-Summer/freshmanspecial
app/src/main/java/com/mredrock/freshmanspecial/CQUPTElegant/Presenter/StudentsPresenter.java
package com.mredrock.freshmanspecial.CQUPTElegant.Presenter; import android.content.Context; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.mredrock.freshmanspecial.CQUPTElegant.Interface.IOrganizationFrg; import com.mredrock.freshmanspecial.CQUPTElegant.Interface.IOrganizationPre; import com.mredrock.freshmanspecial.CQUPTElegant.Model.Organization; import com.mredrock.freshmanspecial.CQUPTElegant.View.StudentsView.OrganizationsFragment; import com.mredrock.freshmanspecial.R; import com.mredrock.freshmanspecial.Utils.NetUtil; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.ResponseBody; /** * Created by Anriku on 2017/8/10. */ public class StudentsPresenter implements IOrganizationPre { private IOrganizationFrg iOrganizationFrg; public StudentsPresenter(IOrganizationFrg iOrganizationFrg) { this.iOrganizationFrg = iOrganizationFrg; } @Override public void setTabLayout(final Context context, FragmentManager manager, final TabLayout tabLayout) { final List<Fragment> fragments = new ArrayList<>(); NetUtil.getGetData("http://yangruixin.com/", "organizations", NetUtil.TEXT_GET, new NetUtil.HttpCallBackListener() { @Override public void onFinish(ResponseBody responseBody) { Gson gson = new Gson(); try { Organization organization = gson.fromJson(responseBody.string(), new TypeToken<Organization>() { }.getType()); for (int i = 0; i < organization.getData().size(); i++) { tabLayout.addTab(tabLayout.newTab().setText(organization.getData().get(i).getName())); fragments.add(new OrganizationsFragment(organization.getData().get(i))); } replaceFragment(fragments.get(0)); tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { replaceFragment(fragments.get(tab.getPosition())); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } catch (IOException e) { e.printStackTrace(); } } }); } private void replaceFragment(Fragment fragment) { FragmentManager fragmentManager = iOrganizationFrg.getTheFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.special_2017_frg_organization_fl, fragment); transaction.commit(); } }
ramkumarkoppu/NUCLEO-F767ZI-ESW
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/src/main_menu_screen/MainMenuView.cpp
<reponame>ramkumarkoppu/NUCLEO-F767ZI-ESW /** ****************************************************************************** * This file is part of the TouchGFX 4.10.0 distribution. * * @attention * * Copyright (c) 2018 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ #include <gui/main_menu_screen/MainMenuView.hpp> #include <BitmapDatabase.hpp> MainMenuView::MainMenuView() : selectedDemoScreen(Defines::GAME2048), onMenuButtonPressed(this, &MainMenuView::menuButtonPressedHandler) { // GotoSTMenuButton must be added by the specialized menu view (to get correct z-order) gotoSTMenuButton.setBitmaps(Bitmap(BITMAP_ST_MENU_BUTTON_ID), Bitmap(BITMAP_ST_MENU_BUTTON_PRESSED_ID)); gotoSTMenuButton.setXY(35, 26); gotoSTMenuButton.setAction(onMenuButtonPressed); // ToggleMenuButton must be added by the specialized menu view (to get correct z-order) toggleMenuButton.setBitmaps(Bitmap(BITMAP_MENU_ICON_ID), Bitmap(BITMAP_MENU_ICON_PRESSED_ID)); toggleMenuButton.setXY(21, 14); toggleMenuButton.setAction(onMenuButtonPressed); // MCULoad must be added by the specialized menu view (to get correct z-order) mcuLoadTxt.setXY(620, 25); mcuLoadTxt.setColor(Color::getColorFrom24BitRGB(0xFF, 0xFF, 0xFF)); mcuLoadValueTxt.setPosition(mcuLoadTxt.getRect().right() - 6, mcuLoadTxt.getY(), 50, 30); mcuLoadValueTxt.setColor(mcuLoadTxt.getColor()); } MainMenuView::~MainMenuView() { } void MainMenuView::setSelectedDemoScreen(Defines::DemoID demoId) { selectedDemoScreen = demoId; } void MainMenuView::gotoSelectedDemoScreen() { presenter->setSelectedDemoScreen(selectedDemoScreen); switch (selectedDemoScreen) { case Defines::GAME2048: static_cast<FrontendApplication*>(Application::getInstance())->gotoGame2048Screen(); break; case Defines::GAME2D: static_cast<FrontendApplication*>(Application::getInstance())->gotoGame2DScreen(); break; case Defines::CONTROLS: static_cast<FrontendApplication*>(Application::getInstance())->gotoControlsScreen(); break; case Defines::AUDIO_PLAYER: static_cast<FrontendApplication*>(Application::getInstance())->gotoAudioPlayerScreen(); break; case Defines::HOME_AUTOMATION: static_cast<FrontendApplication*>(Application::getInstance())->gotoHomeAutomationScreen(); break; case Defines::SETTINGS: static_cast<FrontendApplication*>(Application::getInstance())->gotoSettingsScreen(); break; case Defines::VIDEO_PLAYER: static_cast<FrontendApplication*>(Application::getInstance())->gotoVideoPlayerScreen(); break; case Defines::NUMBER_OF_DEMO_SCREENS: case Defines::NO_DEMO_SCREEN: default: break; } } void MainMenuView::menuButtonPressedHandler(const AbstractButton& button) { if (&button == &toggleMenuButton) { // Clear the previous selected menu that is used for returning from // a demo screen to the menu. But when toggling between menus this // is not needed. presenter->setPreviousSelectedMenuType(Defines::NO_MENU); presenter->setSelectedDemoScreen(demoIDs[0]); toggleMenu(); } else if (&button == &gotoSTMenuButton) { presenter->gotoSTMenu(); } }
elkshrek/ELKHippoLite
ELKHippoLite/ELKMantleLite/NSString/NSString+ELKTimeFormet.h
<reponame>elkshrek/ELKHippoLite // // NSString+ELKTimeFormet.h // ELKParallel // // Created by wing on 2019/12/30. // Copyright © 2019 wing. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /// 时间格式枚举 typedef NS_OPTIONS(NSUInteger, ELKDateFormatStyle) { /// yyyy-MM-dd HH:mm ELKDateFmtNormal1 = 1, /// yyyy-MM-dd HH:mm:ss ELKDateFmtExplicit1 = 2, /// yyyy年MM月dd日 HH:mm ELKDateFmtNormal2 = 3, /// yyyy年MM月dd日 HH:mm:ss ELKDateFmtExplicit2 = 4, /// yyyy-M-d ELKDateFmtNormal3 = 5, /// yyyy-MM-dd ELKDateFmtExplicit3 = 6, /// yyyy年M月d日 ELKDateFmtNormal4 = 7, /// yyyy年MM月dd日 ELKDateFmtExplicit4 = 8, }; @interface NSString (ELKTimeFormet) /// 时间戳=>时间:时间格式字符串+时间戳->格式化时间 /// @param format 时间格式 /// @param timestamp 毫秒级时间戳字符串 + (NSString *)elk_timeWithFormat:(NSString *)format timestamp:(nonnull NSString *)timestamp; /// 时间转换,根据传入的时间格式转换时间戳 /// @param dateStyle ELKDateFormatStyle /// @param timestamp 毫秒级时间戳字符串 + (NSString *)elk_timeWithDateStyle:(ELKDateFormatStyle)dateStyle timestamp:(NSString *)timestamp; /// 时间戳=>yyyy-MM-dd HH:mm格式时间 /// @param timestamp 时间戳字符串 + (NSString *)elk_timeForNormal:(NSString *)timestamp; /// 获取当前时间戳(毫秒级时间戳) + (NSString*)elk_getNowTimestamp; /// 格式化时间=>时间戳(毫秒级):时间格式字符串+格式化时间->时间戳 /// @param format 时间格式 /// @param time 符合上面格式的时间字符串 + (NSString *)elk_timestampWithFormat:(NSString *)format time:(NSString *)time; /// NSDate=>时间戳(毫秒级时间戳长13位) /// @param date 日期 + (NSString *)elk_timestampOfDate:(NSDate *)date; /// 日期时间戳=>计算生日 /// @param birthStamp 生日时间戳 + (NSString *)elk_ageOfBirthStamp:(NSString *)birthStamp; @end NS_ASSUME_NONNULL_END
Metuz/NewZiber
app/controllers/pages_controller.rb
<reponame>Metuz/NewZiber<gh_stars>0 class PagesController < ApplicationController before_action :set_page, only: [:show, :edit, :update, :destroy] respond_to :html def index @pages = Page.all respond_with(@pages) end def show respond_with(@page) end def new @page = Page.new respond_with(@page) end def edit end def create @page = Page.new(page_params) @page.save respond_with(@page) end def update @page = Page.find(params[:id]) respond_to do |format| if @page.update_attributes(page_params) format.html { redirect_to root_path } format.json { respond_with_bip(@page) } else format.html { render :action => "edit" } format.json { respond_with_bip(@page) } end end end def destroy @page.destroy respond_with(@page) end private def set_page @page = Page.find(params[:id]) end def page_params params.require(:page).permit(:text1, :text2, :text3, :text4, :text5, :text6, :text7, :text8, :text9, :text10, :text11, :text12, :text13, :text14, :text15, :text16, :text17, :text18, :text19, :text20, :text21, :text22, :text23, :text24, :text25, :text26, :text27, :text28, :text29, :text30, :text31, :text32, :text33, :text34) end end
codetriage-readme-bot/dropwizard
dropwizard-auth/src/main/java/io/dropwizard/auth/OptionalPrincipalContainerRequestValueFactory.java
package io.dropwizard.auth; import org.glassfish.jersey.server.ContainerRequest; import org.glassfish.jersey.server.internal.inject.AbstractContainerRequestValueFactory; import java.util.Optional; import java.security.Principal; /** * A value factory which extracts an {@link Optional optional} {@link * Principal} from the current {@link ContainerRequest} instance. */ class OptionalPrincipalContainerRequestValueFactory extends AbstractContainerRequestValueFactory<Optional<Principal>> { /** * @return {@link Optional}{@code <}{@link Principal}{@code >} * stored on the request, or {@code Optional.empty()} if * no object was found. */ @Override public Optional<Principal> provide() { return Optional.ofNullable(getContainerRequest().getSecurityContext().getUserPrincipal()); } }
leitstand/leitstand-security
leitstand-crypto/src/main/java/io/leitstand/security/crypto/package-info.java
<filename>leitstand-crypto/src/main/java/io/leitstand/security/crypto/package-info.java /* * Copyright 2020 RtBrick 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. */ /** * Contains the master secret to encrypt and decrypt confidential information such as the secret to sign access tokens as an example. * <p> * The {@link MasterSecret} leverages the <a href="http://en.wikipedia.org">Advanced Encryption Standard (AES)</a> to encrypt sensitive information. * The <code>master.secret</code> and the <code>master.iv</code> properties set the AES secret and initialization vector (IV). * Both properties can be either specified as system properties or in the <code>/etc/rbms/master.secret</code> file, * with system properties having precedence over the configuration file. The specified values must be Base64 encoded. * <p> * AES requires a key and IV length of 16 bytes. This is accomplished by computing the MD5 hash values from the specified properties and * using the 16 MD5 bytes as key and IV respectively. If no IV is specified, the IV defaults to the 16 bytes of the MD5 of the secret MD5 hash value. * <p> * If no secret is specified, the master secret key defaults to <i>changeit</i>. */ package io.leitstand.security.crypto;
delchev/xsk
modules/engines/engine-hdb/src/test/java/com/sap/xsk/hdb/ds/test/handlers/HDBTableAlterHandlerTest.java
/* * Copyright (c) 2022 SAP SE or an SAP affiliate company and XSK contributors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, v2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/LICENSE-2.0 * * SPDX-FileCopyrightText: 2022 SAP SE or an SAP affiliate company and XSK contributors * SPDX-License-Identifier: Apache-2.0 */ package com.sap.xsk.hdb.ds.test.handlers; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import com.sap.xsk.hdb.ds.model.hdbtable.XSKDataStructureHDBTableColumnModel; import com.sap.xsk.hdb.ds.model.hdbtable.XSKDataStructureHDBTableConstraintPrimaryKeyModel; import com.sap.xsk.hdb.ds.model.hdbtable.XSKDataStructureHDBTableConstraintsModel; import com.sap.xsk.hdb.ds.model.hdbtable.XSKDataStructureHDBTableModel; import com.sap.xsk.hdb.ds.processors.table.XSKTableAlterHandler; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.eclipse.dirigible.api.v3.problems.ProblemsFacade; import org.eclipse.dirigible.commons.config.Configuration; import org.eclipse.dirigible.database.ds.model.IDataStructureModel; import org.eclipse.dirigible.database.sql.SqlFactory; import org.eclipse.dirigible.database.sql.builders.AlterBranchingBuilder; import org.eclipse.dirigible.database.sql.builders.table.AlterTableBuilder; import org.eclipse.dirigible.database.sql.dialects.hana.HanaSqlDialect; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Answers; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; @RunWith(MockitoJUnitRunner.class) public class HDBTableAlterHandlerTest { @Mock(answer = Answers.RETURNS_DEEP_STUBS) private Connection mockConnection; @Mock(answer = Answers.RETURNS_DEEP_STUBS) private SqlFactory mockSqlFactory; @Mock private AlterBranchingBuilder alter; @Mock private AlterTableBuilder alterTableBuilder; @Mock private DatabaseMetaData databaseMetaData; @Mock private ResultSet resultSet; private XSKDataStructureHDBTableConstraintPrimaryKeyModel primaryKey = new XSKDataStructureHDBTableConstraintPrimaryKeyModel(); private XSKDataStructureHDBTableConstraintsModel constraintsModel = new XSKDataStructureHDBTableConstraintsModel(); private XSKDataStructureHDBTableModel tableModel = new XSKDataStructureHDBTableModel(); @Before public void openMocks() { MockitoAnnotations.openMocks(this); } @Ignore("Missing verifyPrivate() in Mockito, test needs to be refactored") @Test public void addColumnsSuccessfully() throws Exception { try (MockedStatic<SqlFactory> sqlFactory = Mockito.mockStatic(SqlFactory.class); MockedStatic<Configuration> configuration = Mockito.mockStatic(Configuration.class)) { configuration.when(() -> Configuration.get(IDataStructureModel.DIRIGIBLE_DATABASE_NAMES_CASE_SENSITIVE, "false")).thenReturn("true"); sqlFactory.when(() -> SqlFactory.getNative(mockConnection)).thenReturn(mockSqlFactory); sqlFactory.when(() -> SqlFactory.deriveDialect(mockConnection)).thenReturn(new HanaSqlDialect()); List<XSKDataStructureHDBTableColumnModel> columns = new ArrayList<>(); columns.add(new XSKDataStructureHDBTableColumnModel("Id", "NVARCHAR", "32", true, false, null, false, null, null, true, null)); columns.add(new XSKDataStructureHDBTableColumnModel("Name", "NVARCHAR", "32", true, false, null, false, null, null, false, null)); tableModel.setColumns(columns); tableModel.setConstraints(constraintsModel); tableModel.setName("hdb_table::SampleHdbdd"); tableModel.setSchema("MYSCHEMA"); XSKTableAlterHandler tableAlterHandler = new XSKTableAlterHandler(mockConnection, tableModel); XSKTableAlterHandler handlerSpy = spy(tableAlterHandler); sqlFactory.when(() -> SqlFactory.getNative(mockConnection).alter()).thenReturn(alter); sqlFactory.when(() -> SqlFactory.getNative(mockConnection).alter().table(any())).thenReturn(alterTableBuilder); sqlFactory.when(() -> SqlFactory.getNative(mockConnection).alter().table(any()).add()).thenReturn(alterTableBuilder); when(alterTableBuilder.build()).thenReturn("sql"); handlerSpy.addColumns(mockConnection); // verifyPrivate(handlerSpy, times(2)).invoke("executeAlterBuilder", mockConnection, alterTableBuilder); } } @Test(expected = SQLException.class) public void addColumnsFailedWhenPrimaryKey() throws Exception { try (MockedStatic<SqlFactory> sqlFactory = Mockito.mockStatic(SqlFactory.class); MockedStatic<Configuration> configuration = Mockito.mockStatic(Configuration.class); MockedStatic<ProblemsFacade> problemsFacade = Mockito.mockStatic(ProblemsFacade.class)) { configuration.when(() -> Configuration.get(IDataStructureModel.DIRIGIBLE_DATABASE_NAMES_CASE_SENSITIVE, "false")).thenReturn("true"); sqlFactory.when(() -> SqlFactory.getNative(mockConnection)).thenReturn(mockSqlFactory); sqlFactory.when(() -> SqlFactory.deriveDialect(mockConnection)).thenReturn(new HanaSqlDialect()); List<XSKDataStructureHDBTableColumnModel> columns = new ArrayList<>(); columns.add(new XSKDataStructureHDBTableColumnModel("Age", "INTEGER", "32", true, true, null, false, null, null, true, null)); tableModel.setColumns(columns); tableModel.setConstraints(constraintsModel); tableModel.setName("hdb_table::SampleHdbdd"); tableModel.setSchema("MYSCHEMA"); XSKTableAlterHandler tableAlterHandler = new XSKTableAlterHandler(mockConnection, tableModel); XSKTableAlterHandler handlerSpy = spy(tableAlterHandler); sqlFactory.when(() -> SqlFactory.getNative(mockConnection).alter()).thenReturn(alter); sqlFactory.when(() -> SqlFactory.getNative(mockConnection).alter().table(any())).thenReturn(alterTableBuilder); sqlFactory.when(() -> SqlFactory.getNative(mockConnection).alter().table(any()).add()).thenReturn(alterTableBuilder); problemsFacade.when(() -> ProblemsFacade.save(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenAnswer((Answer<Void>) invocation -> null); handlerSpy.addColumns(mockConnection); } } @Ignore("Missing verifyPrivate() in Mockito, test needs to be refactored") @Test public void removeColumnsSuccessfully() throws Exception { try (MockedStatic<SqlFactory> sqlFactory = Mockito.mockStatic(SqlFactory.class); MockedStatic<Configuration> configuration = Mockito.mockStatic(Configuration.class)) { configuration.when(() -> Configuration.get(IDataStructureModel.DIRIGIBLE_DATABASE_NAMES_CASE_SENSITIVE, "false")).thenReturn("true"); sqlFactory.when(() -> SqlFactory.getNative(mockConnection)).thenReturn(mockSqlFactory); sqlFactory.when(() -> SqlFactory.deriveDialect(mockConnection)).thenReturn(new HanaSqlDialect()); List<XSKDataStructureHDBTableColumnModel> columns = new ArrayList<>(); columns.add(new XSKDataStructureHDBTableColumnModel("Id", "NVARCHAR", "32", true, false, null, false, null, null, true, null)); columns.add(new XSKDataStructureHDBTableColumnModel("Name", "NVARCHAR", "32", true, false, null, false, null, null, false, null)); tableModel.setColumns(columns); tableModel.setConstraints(constraintsModel); tableModel.setName("hdb_table::SampleHdbdd"); tableModel.setSchema("MYSCHEMA"); when(mockConnection.getMetaData()).thenReturn(databaseMetaData); when(databaseMetaData.getColumns(any(), any(), any(), any())).thenReturn(resultSet); when(resultSet.next()).thenReturn(true).thenReturn(false); when(resultSet.getString("COLUMN_NAME")).thenReturn("Test"); when(resultSet.getString("TYPE_NAME")).thenReturn("NVARCHAR"); XSKTableAlterHandler tableAlterHandler = new XSKTableAlterHandler(mockConnection, tableModel); XSKTableAlterHandler handlerSpy = spy(tableAlterHandler); sqlFactory.when(() -> SqlFactory.getNative(mockConnection).alter()).thenReturn(alter); sqlFactory.when(() -> SqlFactory.getNative(mockConnection).alter().table(any())).thenReturn(alterTableBuilder); sqlFactory.when(() -> SqlFactory.getNative(mockConnection).alter().table(any()).drop()).thenReturn(alterTableBuilder); when(alterTableBuilder.build()).thenReturn("sql"); handlerSpy.removeColumns(mockConnection); // TODO: Refactor -> Mockito doesn't have support for verifyPrivate() // verifyPrivate(handlerSpy, times(1)).invoke("executeAlterBuilder", mockConnection, alterTableBuilder); } } @Ignore("Missing verifyPrivate() in Mockito, test needs to be refactored") @Test public void updateColumnsSuccessfully() throws Exception { try (MockedStatic<SqlFactory> sqlFactory = Mockito.mockStatic(SqlFactory.class); MockedStatic<Configuration> configuration = Mockito.mockStatic(Configuration.class)) { configuration.when(() -> Configuration.get(IDataStructureModel.DIRIGIBLE_DATABASE_NAMES_CASE_SENSITIVE, "false")).thenReturn("true"); sqlFactory.when(() -> SqlFactory.getNative(mockConnection)).thenReturn(mockSqlFactory); sqlFactory.when(() -> SqlFactory.deriveDialect(mockConnection)).thenReturn(new HanaSqlDialect()); List<XSKDataStructureHDBTableColumnModel> columns = new ArrayList<>(); columns.add(new XSKDataStructureHDBTableColumnModel("Id", "NVARCHAR", "32", true, false, null, false, null, null, true, null)); columns.add(new XSKDataStructureHDBTableColumnModel("Name", "NVARCHAR", "32", true, false, null, false, null, null, false, null)); tableModel.setColumns(columns); tableModel.setConstraints(constraintsModel); tableModel.setName("hdb_table::SampleHdbdd"); tableModel.setSchema("MYSCHEMA"); when(mockConnection.getMetaData()).thenReturn(databaseMetaData); when(databaseMetaData.getColumns(any(), any(), any(), any())).thenReturn(resultSet); when(resultSet.next()).thenReturn(true).thenReturn(false); when(resultSet.getString("COLUMN_NAME")).thenReturn("Name"); when(resultSet.getString("TYPE_NAME")).thenReturn("NVARCHAR"); XSKTableAlterHandler tableAlterHandler = new XSKTableAlterHandler(mockConnection, tableModel); XSKTableAlterHandler handlerSpy = spy(tableAlterHandler); sqlFactory.when(() -> SqlFactory.getNative(mockConnection).alter()).thenReturn(alter); sqlFactory.when(() -> SqlFactory.getNative(mockConnection).alter().table(any())).thenReturn(alterTableBuilder); sqlFactory.when(() -> SqlFactory.getNative(mockConnection).alter().table(any()).alter()).thenReturn(alterTableBuilder); when(alterTableBuilder.build()).thenReturn("sql"); handlerSpy.updateColumns(mockConnection); // TODO: Refactor -> Mockito doesn't have support for verifyPrivate() // verifyPrivate(handlerSpy, times(1)).invoke("executeAlterBuilder", mockConnection, alterTableBuilder); } } @Ignore("Missing verifyPrivate() in Mockito, test needs to be refactored") @Test public void rebuildIndecesSuccessfully() throws Exception { try (MockedStatic<SqlFactory> sqlFactory = Mockito.mockStatic(SqlFactory.class); MockedStatic<Configuration> configuration = Mockito.mockStatic(Configuration.class)) { configuration.when(() -> Configuration.get(IDataStructureModel.DIRIGIBLE_DATABASE_NAMES_CASE_SENSITIVE, "false")).thenReturn("true"); sqlFactory.when(() -> SqlFactory.getNative(mockConnection)).thenReturn(mockSqlFactory); sqlFactory.when(() -> SqlFactory.deriveDialect(mockConnection)).thenReturn(new HanaSqlDialect()); List<XSKDataStructureHDBTableColumnModel> columns = new ArrayList<>(); columns.add(new XSKDataStructureHDBTableColumnModel("Id", "NVARCHAR", "32", true, false, null, false, null, null, true, null)); columns.add(new XSKDataStructureHDBTableColumnModel("Name", "NVARCHAR", "32", true, false, null, false, null, null, false, null)); tableModel.setColumns(columns); tableModel.setConstraints(constraintsModel); tableModel.setName("hdb_table::SampleHdbdd"); tableModel.setSchema("MYSCHEMA"); sqlFactory.when(() -> SqlFactory.getNative(mockConnection).alter()).thenReturn(alter); sqlFactory.when(() -> SqlFactory.getNative(mockConnection).alter().table(any())).thenReturn(alterTableBuilder); when(alterTableBuilder.build()).thenReturn("sql"); XSKTableAlterHandler tableAlterHandler = new XSKTableAlterHandler(mockConnection, tableModel); XSKTableAlterHandler handlerSpy = spy(tableAlterHandler); handlerSpy.rebuildIndeces(mockConnection); // TODO: Refactor -> Mockito doesn't have support for verifyPrivate() // verifyPrivate(handlerSpy, times(1)).invoke("executeAlterBuilder", mockConnection, alterTableBuilder); } } @Test(expected = SQLException.class) public void ensurePrimaryKeyIsUnchangedSuccessfully() throws Exception { try (MockedStatic<SqlFactory> sqlFactory = Mockito.mockStatic(SqlFactory.class); MockedStatic<Configuration> configuration = Mockito.mockStatic(Configuration.class); MockedStatic<ProblemsFacade> problemsFacade = Mockito.mockStatic(ProblemsFacade.class)) { configuration.when(() -> Configuration.get(IDataStructureModel.DIRIGIBLE_DATABASE_NAMES_CASE_SENSITIVE, "false")).thenReturn("true"); sqlFactory.when(() -> SqlFactory.getNative(mockConnection)).thenReturn(mockSqlFactory); sqlFactory.when(() -> SqlFactory.deriveDialect(mockConnection)).thenReturn(new HanaSqlDialect()); List<XSKDataStructureHDBTableColumnModel> columns = new ArrayList<>(); columns.add(new XSKDataStructureHDBTableColumnModel("Id", "NVARCHAR", "32", true, true, null, false, null, null, true, null)); columns.add(new XSKDataStructureHDBTableColumnModel("Name", "NVARCHAR", "32", true, false, null, false, null, null, false, null)); tableModel.setColumns(columns); tableModel.setConstraints(constraintsModel); primaryKey.setColumns(new String[]{"Id"}); constraintsModel.setPrimaryKey(primaryKey); tableModel.setName("hdb_table::SampleHdbdd"); tableModel.setSchema("MYSCHEMA"); sqlFactory.when(() -> SqlFactory.getNative(mockConnection).alter()).thenReturn(alter); problemsFacade.when(() -> ProblemsFacade.save(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) .thenAnswer((Answer<Void>) invocation -> null); XSKTableAlterHandler tableAlterHandler = new XSKTableAlterHandler(mockConnection, tableModel); XSKTableAlterHandler handlerSpy = spy(tableAlterHandler); handlerSpy.ensurePrimaryKeyIsUnchanged(mockConnection); } } }
SnowOnion/maple
src/race/detector.h
// Copyright 2011 The University of Michigan // // 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. // // Authors - <NAME> (<EMAIL>) // File: race/detector.h - Define the abstract data race dectector. #ifndef RACE_DETECTOR_H_ #define RACE_DETECTOR_H_ #include <tr1/unordered_map> #include "core/basictypes.h" #include "core/analyzer.h" #include "core/vector_clock.h" #include "core/filter.h" #include "race/race.h" namespace race { class Detector : public Analyzer { public: Detector(); virtual ~Detector(); virtual void Register(); virtual bool Enabled() = 0; virtual void Setup(Mutex *lock, RaceDB *race_db); virtual void ImageLoad(Image *image, address_t low_addr, address_t high_addr, address_t data_start, size_t data_size, address_t bss_start, size_t bss_size); virtual void ImageUnload(Image *image, address_t low_addr, address_t high_addr, address_t data_start, size_t data_size, address_t bss_start, size_t bss_size); virtual void ThreadStart(thread_id_t curr_thd_id, thread_id_t parent_thd_id); virtual void BeforeMemRead(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, address_t addr, size_t size); virtual void BeforeMemWrite(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, address_t addr, size_t size); virtual void BeforeAtomicInst(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, std::string type, address_t addr); virtual void AfterAtomicInst(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, std::string type, address_t addr); virtual void AfterPthreadJoin(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, thread_id_t child_thd_id); virtual void AfterPthreadMutexLock(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, address_t addr); virtual void BeforePthreadMutexUnlock(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, address_t addr); virtual void BeforePthreadCondSignal(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, address_t addr); virtual void BeforePthreadCondBroadcast(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, address_t addr); virtual void BeforePthreadCondWait(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, address_t cond_addr, address_t mutex_addr); virtual void AfterPthreadCondWait(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, address_t cond_addr, address_t mutex_addr); virtual void BeforePthreadCondTimedwait(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, address_t cond_addr, address_t mutex_addr); virtual void AfterPthreadCondTimedwait(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, address_t cond_addr, address_t mutex_addr); virtual void BeforePthreadBarrierWait(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, address_t addr); virtual void AfterPthreadBarrierWait(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, address_t addr); virtual void AfterMalloc(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, size_t size, address_t addr); virtual void AfterCalloc(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, size_t nmemb, size_t size, address_t addr); virtual void BeforeRealloc(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, address_t ori_addr, size_t size); virtual void AfterRealloc(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, address_t ori_addr, size_t size, address_t new_addr); virtual void BeforeFree(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, address_t addr); virtual void AfterValloc(thread_id_t curr_thd_id, timestamp_t curr_thd_clk, Inst *inst, size_t size, address_t addr); protected: // the abstract meta data for the memory access class Meta { public: typedef std::tr1::unordered_map<address_t, Meta *> Table; explicit Meta(address_t a) : addr(a) {} virtual ~Meta() {} address_t addr; }; // the meta data for mutex variables to track vector clock class MutexMeta { public: typedef std::tr1::unordered_map<address_t, MutexMeta *> Table; MutexMeta() {} ~MutexMeta() {} VectorClock vc; }; // the meta data for conditional variables to track vector clock class CondMeta { public: typedef std::map<thread_id_t, VectorClock> VectorClockMap; typedef std::tr1::unordered_map<address_t, CondMeta *> Table; CondMeta() {} ~CondMeta() {} VectorClockMap wait_table; VectorClockMap signal_table; }; // the meta data for barrier variables to track vector clock class BarrierMeta { public: typedef std::map<thread_id_t, std::pair<VectorClock, bool> > VectorClockMap; typedef std::tr1::unordered_map<address_t, BarrierMeta *> Table; BarrierMeta() : pre_using_table1(true), post_using_table1(true) {} ~BarrierMeta() {} bool pre_using_table1; bool post_using_table1; VectorClockMap barrier_wait_table1; VectorClockMap barrier_wait_table2; }; // helper functions void AllocAddrRegion(address_t addr, size_t size); void FreeAddrRegion(address_t addr); bool FilterAccess(address_t addr) { return filter_->Filter(addr, false); } MutexMeta *GetMutexMeta(address_t iaddr); CondMeta *GetCondMeta(address_t iaddr); BarrierMeta *GetBarrierMeta(address_t iaddr); void ReportRace(Meta *meta, thread_id_t t0, Inst *i0, RaceEventType p0, thread_id_t t1, Inst *i1, RaceEventType p1); // main processing functions void ProcessLock(thread_id_t curr_thd_id, MutexMeta *meta); void ProcessUnlock(thread_id_t curr_thd_id, MutexMeta *meta); void ProcessNotify(thread_id_t curr_thd_id, CondMeta *meta); void ProcessPreWait(thread_id_t curr_thd_id, CondMeta *meta); void ProcessPostWait(thread_id_t curr_thd_id, CondMeta *meta); void ProcessPreBarrier(thread_id_t curr_thd_id, BarrierMeta *meta); void ProcessPostBarrier(thread_id_t curr_thd_id, BarrierMeta *meta); void ProcessFree(MutexMeta *meta); void ProcessFree(CondMeta *meta); void ProcessFree(BarrierMeta *meta); // virtual functions to override virtual Meta *GetMeta(address_t iaddr) = 0; virtual void ProcessRead(thread_id_t curr_thd_id, Meta *meta, Inst *inst) = 0; virtual void ProcessWrite(thread_id_t curr_thd_id, Meta *meta, Inst *inst)= 0; virtual void ProcessFree(Meta *meta) = 0; // common databases Mutex *internal_lock_; RaceDB *race_db_; // settings and flasg address_t unit_size_; RegionFilter *filter_; // meta data MutexMeta::Table mutex_meta_table_; CondMeta::Table cond_meta_table_; BarrierMeta::Table barrier_meta_table_; Meta::Table meta_table_; // global analysis state std::map<thread_id_t, VectorClock *> curr_vc_map_; std::map<thread_id_t, bool> atomic_map_; // whether executing atomic inst. private: DISALLOW_COPY_CONSTRUCTORS(Detector); }; } // namespace race #endif
BBarisKilic/JavaCamp
day05_nLayeredDemo/src/com/example/day5_nLayeredDemo/entities/abstracts/Entity.java
package com.example.day5_nLayeredDemo.entities.abstracts; public interface Entity { }
sunabove/ws_map_01
PR200_GOODMAP_ENGINE/src_ygis_engine/com/ynhenc/gis/model/shape/ShapePointPoi.java
package com.ynhenc.gis.model.shape; import java.awt.image.BufferedImage; import com.ynhenc.gis.ui.resource.IconImage; public class ShapePointPoi extends ShapePoint implements PoiInterface { public Poi getPoi() { if (this.poi == null) { this.poi = new Poi(); } return poi; } public void setPoi(Poi poi) { this.poi = poi; } public boolean isContains(Projection projection, MousePnt mouse) { ShapePointPoi shapePoi = this; GeoPoint centroid = shapePoi.getCentroid(); PntShort pixelPnt = projection.toGraphics(centroid); Poi poi = shapePoi.getPoi(); IconImage iconImage = poi.getIconImage(); if (iconImage != null) { BufferedImage bfrImage = iconImage.getBfrImage(); if (bfrImage != null) { double imageWidth = bfrImage.getWidth(); double imageHeight = bfrImage.getHeight(); double dx = Math.abs( pixelPnt.getX() - mouse.getX() ); double dy = Math.abs( pixelPnt.getY() - mouse.getY() ); if( dx <= imageWidth/2.0 && dy <= imageHeight/2.0 ) { return true; } } } return false; } public ShapePointPoi(int id, int recordNo, double x, double y) { super(id, recordNo, x, y); } public ShapePointPoi(int id, int recordNo, GeoPoint point) { super(id, recordNo, point); } private Poi poi; }
nextbreakpoint/event-sourcing-cqrs-example
platform/services/designs-processor/src/main/java/com/nextbreakpoint/shop/designs/common/ViewSuccessConsumer.java
<filename>platform/services/designs-processor/src/main/java/com/nextbreakpoint/shop/designs/common/ViewSuccessConsumer.java package com.nextbreakpoint.shop.designs.common; import com.nextbreakpoint.shop.common.model.events.DesignChangedEvent; import com.nextbreakpoint.shop.designs.model.RecordAndMessage; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.rxjava.kafka.client.consumer.KafkaConsumer; import java.util.Objects; import java.util.function.BiConsumer; public class ViewSuccessConsumer implements BiConsumer<RecordAndMessage, DesignChangedEvent> { private final Logger logger = LoggerFactory.getLogger(ViewSuccessConsumer.class.getName()); private final KafkaConsumer<String, String> consumer; public ViewSuccessConsumer(KafkaConsumer<String, String> consumer) { this.consumer = Objects.requireNonNull(consumer); } @Override public void accept(RecordAndMessage input, DesignChangedEvent event) { consumer.commit(); logger.info("Design changed: id=" + event.getUuid()); } }