code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * 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.apache.olingo.fit.base; import static org.junit.Assert.assertEquals; import org.apache.olingo.client.api.communication.request.retrieve.ODataEntitySetRequest; import org.apache.olingo.client.api.domain.ClientEntity; import org.apache.olingo.client.api.domain.ClientEntitySet; import org.apache.olingo.client.api.uri.FilterArgFactory; import org.apache.olingo.client.api.uri.FilterFactory; import org.apache.olingo.client.api.uri.URIBuilder; import org.apache.olingo.client.api.uri.URIFilter; import org.apache.olingo.commons.api.format.ContentType; import org.junit.Test; public class FilterFactoryTestITCase extends AbstractTestITCase { private FilterFactory getFilterFactory() { return getClient().getFilterFactory(); } private FilterArgFactory getFilterArgFactory() { return getFilterFactory().getArgFactory(); } @Test public void crossjoin() { final URIFilter filter = getFilterFactory().eq( getFilterArgFactory().property("Orders/OrderID"), getFilterArgFactory().property("Customers/Order")); final URIBuilder uriBuilder = client.newURIBuilder(testStaticServiceRootURL).appendCrossjoinSegment("Customers", "Orders").filter(filter); final ODataEntitySetRequest<ClientEntitySet> req = client.getRetrieveRequestFactory().getEntitySetRequest(uriBuilder.build()); req.setFormat(ContentType.JSON_FULL_METADATA); final ClientEntitySet feed = req.execute().getBody(); assertEquals(3, feed.getEntities().size()); for (ClientEntity entity : feed.getEntities()) { assertEquals(2, entity.getNavigationLinks().size()); } } }
rareddy/olingo-odata4
fit/src/test/java/org/apache/olingo/fit/base/FilterFactoryTestITCase.java
Java
apache-2.0
2,425
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.protocols.channels; import com.google.common.collect.Multimap; import com.google.common.collect.MultimapBuilder; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import org.bitcoinj.core.*; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigInteger; import java.util.Arrays; import java.util.Locale; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; /** * Version 2 of the payment channel state machine - uses CLTV opcode transactions * instead of multisig transactions. */ public class PaymentChannelV2ServerState extends PaymentChannelServerState { private static final Logger log = LoggerFactory.getLogger(PaymentChannelV1ServerState.class); // The total value locked into the CLTV output and the value to us in the last signature the client provided private Coin feePaidForPayment; // The client key for the multi-sig contract // We currently also use the serverKey for payouts, but this is not required protected ECKey clientKey; PaymentChannelV2ServerState(StoredServerChannel storedServerChannel, Wallet wallet, TransactionBroadcaster broadcaster) throws VerificationException { super(storedServerChannel, wallet, broadcaster); synchronized (storedServerChannel) { this.clientKey = storedServerChannel.clientKey; stateMachine.transition(State.READY); } } public PaymentChannelV2ServerState(TransactionBroadcaster broadcaster, Wallet wallet, ECKey serverKey, long minExpireTime) { super(broadcaster, wallet, serverKey, minExpireTime); stateMachine.transition(State.WAITING_FOR_MULTISIG_CONTRACT); } @Override public Multimap<State, State> getStateTransitions() { Multimap<State, State> result = MultimapBuilder.enumKeys(State.class).arrayListValues().build(); result.put(State.UNINITIALISED, State.READY); result.put(State.UNINITIALISED, State.WAITING_FOR_MULTISIG_CONTRACT); result.put(State.WAITING_FOR_MULTISIG_CONTRACT, State.WAITING_FOR_MULTISIG_ACCEPTANCE); result.put(State.WAITING_FOR_MULTISIG_ACCEPTANCE, State.READY); result.put(State.READY, State.CLOSING); result.put(State.CLOSING, State.CLOSED); for (State state : State.values()) { result.put(state, State.ERROR); } return result; } @Override public int getMajorVersion() { return 2; } @Override public TransactionOutput getClientOutput() { return null; } public void provideClientKey(byte[] clientKey) { this.clientKey = ECKey.fromPublicOnly(clientKey); } @Override public synchronized Coin getFeePaid() { stateMachine.checkState(State.CLOSED, State.CLOSING); return feePaidForPayment; } @Override protected Script getSignedScript() { return createP2SHRedeemScript(); } @Override protected void verifyContract(final Transaction contract) { super.verifyContract(contract); // Check contract matches P2SH hash byte[] expected = getContractScript().getPubKeyHash(); byte[] actual = Utils.sha256hash160(createP2SHRedeemScript().getProgram()); if (!Arrays.equals(actual, expected)) { throw new VerificationException( "P2SH hash didn't match required contract - contract should be a CLTV micropayment channel to client and server in that order."); } } /** * Creates a P2SH script outputting to the client and server pubkeys * @return */ @Override protected Script createOutputScript() { return ScriptBuilder.createP2SHOutputScript(createP2SHRedeemScript()); } private Script createP2SHRedeemScript() { return ScriptBuilder.createCLTVPaymentChannelOutput(BigInteger.valueOf(getExpiryTime()), clientKey, serverKey); } protected ECKey getClientKey() { return clientKey; } // Signs the first input of the transaction which must spend the multisig contract. private void signP2SHInput(Transaction tx, Transaction.SigHash hashType, boolean anyoneCanPay) { TransactionSignature signature = tx.calculateSignature(0, serverKey, createP2SHRedeemScript(), hashType, anyoneCanPay); byte[] mySig = signature.encodeToBitcoin(); Script scriptSig = ScriptBuilder.createCLTVPaymentChannelP2SHInput(bestValueSignature, mySig, createP2SHRedeemScript()); tx.getInput(0).setScriptSig(scriptSig); } final SettableFuture<Transaction> closedFuture = SettableFuture.create(); @Override public synchronized ListenableFuture<Transaction> close() throws InsufficientMoneyException { if (storedServerChannel != null) { StoredServerChannel temp = storedServerChannel; storedServerChannel = null; StoredPaymentChannelServerStates channels = (StoredPaymentChannelServerStates) wallet.getExtensions().get(StoredPaymentChannelServerStates.EXTENSION_ID); channels.closeChannel(temp); // May call this method again for us (if it wasn't the original caller) if (getState().compareTo(State.CLOSING) >= 0) return closedFuture; } if (getState().ordinal() < State.READY.ordinal()) { log.error("Attempt to settle channel in state " + getState()); stateMachine.transition(State.CLOSED); closedFuture.set(null); return closedFuture; } if (getState() != State.READY) { // TODO: What is this codepath for? log.warn("Failed attempt to settle a channel in state " + getState()); return closedFuture; } Transaction tx = null; try { Wallet.SendRequest req = makeUnsignedChannelContract(bestValueToMe); tx = req.tx; // Provide a throwaway signature so that completeTx won't complain out about unsigned inputs it doesn't // know how to sign. Note that this signature does actually have to be valid, so we can't use a dummy // signature to save time, because otherwise completeTx will try to re-sign it to make it valid and then // die. We could probably add features to the SendRequest API to make this a bit more efficient. signP2SHInput(tx, Transaction.SigHash.NONE, true); // Let wallet handle adding additional inputs/fee as necessary. req.shuffleOutputs = false; req.missingSigsMode = Wallet.MissingSigsMode.USE_DUMMY_SIG; wallet.completeTx(req); // TODO: Fix things so shuffling is usable. feePaidForPayment = req.tx.getFee(); log.info("Calculated fee is {}", feePaidForPayment); if (feePaidForPayment.compareTo(bestValueToMe) > 0) { final String msg = String.format(Locale.US, "Had to pay more in fees (%s) than the channel was worth (%s)", feePaidForPayment, bestValueToMe); throw new InsufficientMoneyException(feePaidForPayment.subtract(bestValueToMe), msg); } // Now really sign the multisig input. signP2SHInput(tx, Transaction.SigHash.ALL, false); // Some checks that shouldn't be necessary but it can't hurt to check. tx.verify(); // Sanity check syntax. for (TransactionInput input : tx.getInputs()) input.verify(); // Run scripts and ensure it is valid. } catch (InsufficientMoneyException e) { throw e; // Don't fall through. } catch (Exception e) { log.error("Could not verify self-built tx\nMULTISIG {}\nCLOSE {}", contract, tx != null ? tx : ""); throw new RuntimeException(e); // Should never happen. } stateMachine.transition(State.CLOSING); log.info("Closing channel, broadcasting tx {}", tx); // The act of broadcasting the transaction will add it to the wallet. ListenableFuture<Transaction> future = broadcaster.broadcastTransaction(tx).future(); Futures.addCallback(future, new FutureCallback<Transaction>() { @Override public void onSuccess(Transaction transaction) { log.info("TX {} propagated, channel successfully closed.", transaction.getHash()); stateMachine.transition(State.CLOSED); closedFuture.set(transaction); } @Override public void onFailure(Throwable throwable) { log.error("Failed to settle channel, could not broadcast: {}", throwable); stateMachine.transition(State.ERROR); closedFuture.setException(throwable); } }); return closedFuture; } }
rnicoll/bitcoinj
core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelV2ServerState.java
Java
apache-2.0
9,869
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1LogoRecognitionAnnotation extends Google_Collection { protected $collection_key = 'tracks'; protected $entityType = 'Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1Entity'; protected $entityDataType = ''; protected $segmentsType = 'Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1VideoSegment'; protected $segmentsDataType = 'array'; protected $tracksType = 'Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1Track'; protected $tracksDataType = 'array'; /** * @param Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1Entity */ public function setEntity(Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1Entity $entity) { $this->entity = $entity; } /** * @return Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1Entity */ public function getEntity() { return $this->entity; } /** * @param Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1VideoSegment[] */ public function setSegments($segments) { $this->segments = $segments; } /** * @return Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1VideoSegment[] */ public function getSegments() { return $this->segments; } /** * @param Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1Track[] */ public function setTracks($tracks) { $this->tracks = $tracks; } /** * @return Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1Track[] */ public function getTracks() { return $this->tracks; } }
tsugiproject/tsugi
vendor/google/apiclient-services/src/Google/Service/CloudVideoIntelligence/GoogleCloudVideointelligenceV1LogoRecognitionAnnotation.php
PHP
apache-2.0
2,318
/* * 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.apache.geode.internal.cache.execute; import static org.apache.geode.cache.Region.SEPARATOR; import java.util.Map; import java.util.Set; import org.apache.geode.cache.Region; import org.apache.geode.cache.execute.FunctionAdapter; import org.apache.geode.cache.execute.FunctionContext; import org.apache.geode.cache.execute.RegionFunctionContext; import org.apache.geode.cache.partition.PartitionRegionHelper; import org.apache.geode.internal.Assert; import org.apache.geode.internal.cache.LocalDataSet; public class LocalDataSetFunction extends FunctionAdapter { private volatile boolean optimizeForWrite; public LocalDataSetFunction(boolean optimizeForWrite) { this.optimizeForWrite = optimizeForWrite; } @Override public void execute(FunctionContext context) { RegionFunctionContext rContext = (RegionFunctionContext) context; Region cust = rContext.getDataSet(); LocalDataSet localCust = (LocalDataSet) PartitionRegionHelper.getLocalDataForContext(rContext); Map<String, Region<?, ?>> localColocatedRegions = PartitionRegionHelper.getLocalColocatedRegions(rContext); Map<String, Region<?, ?>> colocatedRegions = PartitionRegionHelper.getColocatedRegions(cust); Assert.assertTrue(colocatedRegions.size() == 2); Set custKeySet = cust.keySet(); Set localCustKeySet = localCust.keySet(); Region ord = colocatedRegions.get(SEPARATOR + "OrderPR"); Region localOrd = localColocatedRegions.get(SEPARATOR + "OrderPR"); Set ordKeySet = ord.keySet(); Set localOrdKeySet = localOrd.keySet(); Region ship = colocatedRegions.get(SEPARATOR + "ShipmentPR"); Region localShip = localColocatedRegions.get(SEPARATOR + "ShipmentPR"); Set shipKeySet = ship.keySet(); Set localShipKeySet = localShip.keySet(); Assert.assertTrue( localCust.getBucketSet().size() == ((LocalDataSet) localOrd).getBucketSet().size()); Assert.assertTrue( localCust.getBucketSet().size() == ((LocalDataSet) localShip).getBucketSet().size()); Assert.assertTrue(custKeySet.size() == 120); Assert.assertTrue(ordKeySet.size() == 120); Assert.assertTrue(shipKeySet.size() == 120); Assert.assertTrue(localCustKeySet.size() == localOrdKeySet.size()); Assert.assertTrue(localCustKeySet.size() == localShipKeySet.size()); context.getResultSender().lastResult(null); } @Override public String getId() { return "LocalDataSetFunction" + optimizeForWrite; } @Override public boolean hasResult() { return true; } @Override public boolean optimizeForWrite() { return optimizeForWrite; } @Override public boolean isHA() { return false; } }
smgoller/geode
geode-core/src/test/java/org/apache/geode/internal/cache/execute/LocalDataSetFunction.java
Java
apache-2.0
3,480
""" Helper module that will enable lazy imports of Cocoa wrapper items. This should improve startup times and memory usage, at the cost of not being able to use 'from Cocoa import *' """ __all__ = ('ObjCLazyModule',) import sys import re import struct from objc import lookUpClass, getClassList, nosuchclass_error, loadBundle import objc ModuleType = type(sys) def _loadBundle(frameworkName, frameworkIdentifier, frameworkPath): if frameworkIdentifier is None: bundle = loadBundle( frameworkName, {}, bundle_path=frameworkPath, scan_classes=False) else: try: bundle = loadBundle( frameworkName, {}, bundle_identifier=frameworkIdentifier, scan_classes=False) except ImportError: bundle = loadBundle( frameworkName, {}, bundle_path=frameworkPath, scan_classes=False) return bundle class GetAttrMap (object): __slots__ = ('_container',) def __init__(self, container): self._container = container def __getitem__(self, key): try: return getattr(self._container, key) except AttributeError: raise KeyError(key) class ObjCLazyModule (ModuleType): # Define slots for all attributes, that way they don't end up it __dict__. __slots__ = ( '_ObjCLazyModule__bundle', '_ObjCLazyModule__enummap', '_ObjCLazyModule__funcmap', '_ObjCLazyModule__parents', '_ObjCLazyModule__varmap', '_ObjCLazyModule__inlinelist', '_ObjCLazyModule__aliases', ) def __init__(self, name, frameworkIdentifier, frameworkPath, metadict, inline_list=None, initialdict={}, parents=()): super(ObjCLazyModule, self).__init__(name) if frameworkIdentifier is not None or frameworkPath is not None: self.__bundle = self.__dict__['__bundle__'] = _loadBundle(name, frameworkIdentifier, frameworkPath) pfx = name + '.' for nm in sys.modules: if nm.startswith(pfx): rest = nm[len(pfx):] if '.' in rest: continue if sys.modules[nm] is not None: self.__dict__[rest] = sys.modules[nm] self.__dict__.update(initialdict) self.__dict__.update(metadict.get('misc', {})) self.__parents = parents self.__varmap = metadict.get('constants') self.__varmap_dct = metadict.get('constants_dict', {}) self.__enummap = metadict.get('enums') self.__funcmap = metadict.get('functions') self.__aliases = metadict.get('aliases') self.__inlinelist = inline_list self.__expressions = metadict.get('expressions') self.__expressions_mapping = GetAttrMap(self) self.__load_cftypes(metadict.get('cftypes')) if metadict.get('protocols') is not None: self.__dict__['protocols'] = ModuleType('%s.protocols'%(name,)) self.__dict__['protocols'].__dict__.update( metadict['protocols']) for p in objc.protocolsForProcess(): setattr(self.__dict__['protocols'], p.__name__, p) def __dir__(self): return self.__all__ def __getattr__(self, name): if name == "__all__": # Load everything immediately value = self.__calc_all() self.__dict__[name] = value return value # First try parent module, as we had done # 'from parents import *' for p in self.__parents: try: value = getattr(p, name) except AttributeError: pass else: self.__dict__[name] = value return value # Check if the name is a constant from # the metadata files try: value = self.__get_constant(name) except AttributeError: pass else: self.__dict__[name] = value return value # Then check if the name is class try: value = lookUpClass(name) except nosuchclass_error: pass else: self.__dict__[name] = value return value # Finally give up and raise AttributeError raise AttributeError(name) def __calc_all(self): all = set() # Ensure that all dynamic entries get loaded if self.__varmap_dct: for nm in self.__varmap_dct: try: getattr(self, nm) except AttributeError: pass if self.__varmap: for nm in re.findall(r"\$([A-Z0-9a-z_]*)(?:@[^$]*)?(?=\$)", self.__varmap): try: getattr(self, nm) except AttributeError: pass if self.__enummap: for nm in re.findall(r"\$([A-Z0-9a-z_]*)@[^$]*(?=\$)", self.__enummap): try: getattr(self, nm) except AttributeError: pass if self.__funcmap: for nm in self.__funcmap: try: getattr(self, nm) except AttributeError: pass if self.__expressions: for nm in self.__expressions: try: getattr(self, nm) except AttributeError: pass if self.__aliases: for nm in self.__aliases: try: getattr(self, nm) except AttributeError: pass # Add all names that are already in our __dict__ all.update(self.__dict__) # Merge __all__of parents ('from parent import *') for p in self.__parents: all.update(getattr(p, '__all__', ())) # Add all class names all.update(cls.__name__ for cls in getClassList()) return [ v for v in all if not v.startswith('_') ] return list(all) def __get_constant(self, name): # FIXME: Loading variables and functions requires too much # code at the moment, the objc API can be adjusted for # this later on. if self.__varmap_dct: if name in self.__varmap_dct: tp = self.__varmap_dct[name] return objc._loadConstant(name, tp, False) if self.__varmap: m = re.search(r"\$%s(@[^$]*)?\$"%(name,), self.__varmap) if m is not None: tp = m.group(1) if tp is None: tp = '@' else: tp = tp[1:] d = {} if tp.startswith('='): tp = tp[1:] magic = True else: magic = False #try: return objc._loadConstant(name, tp, magic) #except Exception as exc: # print "LOAD %r %r %r -> raise %s"%(name, tp, magic, exc) # raise if self.__enummap: m = re.search(r"\$%s@([^$]*)\$"%(name,), self.__enummap) if m is not None: val = m.group(1) if val.startswith("'"): if isinstance(val, bytes): # Python 2.x val, = struct.unpack('>l', val[1:-1]) else: # Python 3.x val, = struct.unpack('>l', val[1:-1].encode('latin1')) elif '.' in val: val = float(val) else: val = int(val) return val if self.__funcmap: if name in self.__funcmap: info = self.__funcmap[name] func_list = [ (name,) + info ] d = {} objc.loadBundleFunctions(self.__bundle, d, func_list) if name in d: return d[name] if self.__inlinelist is not None: try: objc.loadFunctionList( self.__inlinelist, d, func_list, skip_undefined=False) except objc.error: pass else: if name in d: return d[name] if self.__expressions: if name in self.__expressions: info = self.__expressions[name] try: return eval(info, {}, self.__expressions_mapping) except NameError: pass if self.__aliases: if name in self.__aliases: alias = self.__aliases[name] if alias == 'ULONG_MAX': return (sys.maxsize * 2) + 1 elif alias == 'LONG_MAX': return sys.maxsize elif alias == 'LONG_MIN': return -sys.maxsize-1 return getattr(self, alias) raise AttributeError(name) def __load_cftypes(self, cftypes): if not cftypes: return for name, type, gettypeid_func, tollfree in cftypes: if tollfree: for nm in tollfree.split(','): try: objc.lookUpClass(nm) except objc.error: pass else: tollfree = nm break try: v = objc.registerCFSignature(name, type, None, tollfree) if v is not None: self.__dict__[name] = v continue except objc.nosuchclass_error: pass try: func = getattr(self, gettypeid_func) except AttributeError: # GetTypeID function not found, this is either # a CFType that isn't present on the current # platform, or a CFType without a public GetTypeID # function. Proxy using the generic CFType if tollfree is None: v = objc.registerCFSignature(name, type, None, 'NSCFType') if v is not None: self.__dict__[name] = v continue v = objc.registerCFSignature(name, type, func()) if v is not None: self.__dict__[name] = v
albertz/music-player
mac/pyobjc-core/Lib/objc/_lazyimport.py
Python
bsd-2-clause
10,756
/* * #%L * Simmetrics Core * %% * Copyright (C) 2014 - 2016 Simmetrics Authors * %% * 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. * #L% */ package org.simmetrics.builders; import java.util.List; import java.util.Set; import org.simmetrics.Metric; import org.simmetrics.StringMetric; import org.simmetrics.simplifiers.Simplifier; import org.simmetrics.tokenizers.Tokenizer; import com.google.common.collect.Multiset; @SuppressWarnings("deprecation") // Implementation of StringMetrics will migrate into this class final class StringMetrics { public static StringMetric create(Metric<String> metric) { return org.simmetrics.metrics.StringMetrics.create(metric); } public static StringMetric create(Metric<String> metric, Simplifier simplifier) { return org.simmetrics.metrics.StringMetrics.create(metric,simplifier); } public static StringMetric createForListMetric(Metric<List<String>> metric, Simplifier simplifier, Tokenizer tokenizer) { return org.simmetrics.metrics.StringMetrics.createForListMetric(metric,simplifier, tokenizer); } public static StringMetric createForListMetric(Metric<List<String>> metric, Tokenizer tokenizer) { return org.simmetrics.metrics.StringMetrics.createForListMetric(metric, tokenizer); } public static StringMetric createForSetMetric(Metric<Set<String>> metric, Simplifier simplifier, Tokenizer tokenizer) { return org.simmetrics.metrics.StringMetrics.createForSetMetric(metric,simplifier, tokenizer); } public static StringMetric createForSetMetric(Metric<Set<String>> metric, Tokenizer tokenizer) { return org.simmetrics.metrics.StringMetrics.createForSetMetric(metric, tokenizer); } public static StringMetric createForMultisetMetric(Metric<Multiset<String>> metric, Simplifier simplifier, Tokenizer tokenizer) { return org.simmetrics.metrics.StringMetrics.createForMultisetMetric(metric,simplifier, tokenizer); } public static StringMetric createForMultisetMetric(Metric<Multiset<String>> metric, Tokenizer tokenizer) { return org.simmetrics.metrics.StringMetrics.createForMultisetMetric(metric, tokenizer); } private StringMetrics() { // Utility class. } }
janmotl/linkifier
src/org/simmetrics/builders/StringMetrics.java
Java
bsd-2-clause
2,692
goog.provide('ol.test.format.WFS'); describe('ol.format.WFS', function() { describe('when parsing TOPP states GML from WFS', function() { var features, feature, xml; var config = { 'featureNS': 'http://www.openplans.org/topp', 'featureType': 'states' }; before(function(done) { proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326')); afterLoadText('spec/ol/format/wfs/topp-states-wfs.xml', function(data) { try { xml = data; features = new ol.format.WFS(config).readFeatures(xml); } catch (e) { done(e); } done(); }); }); it('creates 3 features', function() { expect(features).to.have.length(3); }); it('creates a polygon for Illinois', function() { feature = features[0]; expect(feature.getId()).to.equal('states.1'); expect(feature.get('STATE_NAME')).to.equal('Illinois'); expect(feature.getGeometry()).to.be.an(ol.geom.MultiPolygon); }); it('transforms and creates a polygon for Illinois', function() { features = new ol.format.WFS(config).readFeatures(xml, { featureProjection: 'EPSG:3857' }); feature = features[0]; expect(feature.getId()).to.equal('states.1'); expect(feature.get('STATE_NAME')).to.equal('Illinois'); var geom = feature.getGeometry(); expect(geom).to.be.an(ol.geom.MultiPolygon); var p = ol.proj.transform([-88.071, 37.511], 'EPSG:4326', 'EPSG:3857'); p.push(0); expect(geom.getFirstCoordinate()).to.eql(p); }); }); describe('when parsing mapserver GML2 polygon', function() { var features, feature, xml; var config = { 'featureNS': 'http://mapserver.gis.umn.edu/mapserver', 'featureType': 'polygon', 'gmlFormat': new ol.format.GML2() }; before(function(done) { proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326')); afterLoadText('spec/ol/format/wfs/polygonv2.xml', function(data) { try { xml = data; features = new ol.format.WFS(config).readFeatures(xml); } catch (e) { done(e); } done(); }); }); it('creates 3 features', function() { expect(features).to.have.length(3); }); it('creates a polygon for My Polygon with hole', function() { feature = features[0]; expect(feature.getId()).to.equal('1'); expect(feature.get('name')).to.equal('My Polygon with hole'); expect(feature.get('boundedBy')).to.eql( [47.003018, -0.768746, 47.925567, 0.532597]); expect(feature.getGeometry()).to.be.an(ol.geom.MultiPolygon); expect(feature.getGeometry().getFlatCoordinates()). to.have.length(60); }); }); describe('when parsing FeatureCollection', function() { var xml; before(function(done) { afterLoadText('spec/ol/format/wfs/EmptyFeatureCollection.xml', function(_xml) { xml = _xml; done(); }); }); it('returns an empty array of features when none exist', function() { var result = new ol.format.WFS().readFeatures(xml); expect(result).to.have.length(0); }); }); describe('when parsing FeatureCollection', function() { var response; before(function(done) { afterLoadText('spec/ol/format/wfs/NumberOfFeatures.xml', function(xml) { try { response = new ol.format.WFS().readFeatureCollectionMetadata(xml); } catch (e) { done(e); } done(); }); }); it('returns the correct number of features', function() { expect(response.numberOfFeatures).to.equal(625); }); }); describe('when parsing FeatureCollection', function() { var response; before(function(done) { proj4.defs('EPSG:28992', '+proj=sterea +lat_0=52.15616055555555 ' + '+lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 ' + '+ellps=bessel +towgs84=565.417,50.3319,465.552,-0.398957,0.343988,' + '-1.8774,4.0725 +units=m +no_defs'); afterLoadText('spec/ol/format/wfs/boundedBy.xml', function(xml) { try { response = new ol.format.WFS().readFeatureCollectionMetadata(xml); } catch (e) { done(e); } done(); }); }); it('returns the correct bounds', function() { expect(response.bounds).to.eql([3197.88, 306457.313, 280339.156, 613850.438]); }); }); describe('when parsing TransactionResponse', function() { var response; before(function(done) { afterLoadText('spec/ol/format/wfs/TransactionResponse.xml', function(xml) { try { response = new ol.format.WFS().readTransactionResponse(xml); } catch (e) { done(e); } done(); }); }); it('returns the correct TransactionResponse object', function() { expect(response.transactionSummary.totalDeleted).to.equal(0); expect(response.transactionSummary.totalInserted).to.equal(0); expect(response.transactionSummary.totalUpdated).to.equal(1); expect(response.insertIds).to.have.length(2); expect(response.insertIds[0]).to.equal('parcelle.40'); }); }); describe('when writing out a GetFeature request', function() { it('creates the expected output', function() { var text = '<wfs:GetFeature service="WFS" version="1.1.0" resultType="hits" ' + ' xmlns:topp="http://www.openplans.org/topp"' + ' xmlns:wfs="http://www.opengis.net/wfs"' + ' xmlns:ogc="http://www.opengis.net/ogc"' + ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' + ' xsi:schemaLocation="http://www.opengis.net/wfs ' + 'http://schemas.opengis.net/wfs/1.1.0/wfs.xsd">' + ' <wfs:Query xmlns:wfs="http://www.opengis.net/wfs" ' + ' typeName="topp:states" srsName="urn:ogc:def:crs:EPSG::4326" ' + ' xmlns:topp="http://www.openplans.org/topp">' + ' <wfs:PropertyName>STATE_NAME</wfs:PropertyName>' + ' <wfs:PropertyName>STATE_FIPS</wfs:PropertyName>' + ' <wfs:PropertyName>STATE_ABBR</wfs:PropertyName>' + ' </wfs:Query>' + '</wfs:GetFeature>'; var serialized = new ol.format.WFS().writeGetFeature({ resultType: 'hits', featureTypes: ['states'], featureNS: 'http://www.openplans.org/topp', featurePrefix: 'topp', srsName: 'urn:ogc:def:crs:EPSG::4326', propertyNames: ['STATE_NAME', 'STATE_FIPS', 'STATE_ABBR'] }); expect(serialized).to.xmleql(ol.xml.parse(text)); }); it('creates paging headers', function() { var text = '<wfs:GetFeature service="WFS" version="1.1.0" startIndex="20" ' + ' count="10" xmlns:topp="http://www.openplans.org/topp"' + ' xmlns:wfs="http://www.opengis.net/wfs"' + ' xmlns:ogc="http://www.opengis.net/ogc"' + ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' + ' xsi:schemaLocation="http://www.opengis.net/wfs ' + 'http://schemas.opengis.net/wfs/1.1.0/wfs.xsd">' + ' <wfs:Query xmlns:wfs="http://www.opengis.net/wfs" ' + ' typeName="topp:states" srsName="urn:ogc:def:crs:EPSG::4326"' + ' xmlns:topp="http://www.openplans.org/topp">' + ' </wfs:Query>' + '</wfs:GetFeature>'; var serialized = new ol.format.WFS().writeGetFeature({ count: 10, startIndex: 20, srsName: 'urn:ogc:def:crs:EPSG::4326', featureNS: 'http://www.openplans.org/topp', featurePrefix: 'topp', featureTypes: ['states'] }); expect(serialized).to.xmleql(ol.xml.parse(text)); }); it('creates a BBOX filter', function() { var text = '<wfs:Query xmlns:wfs="http://www.opengis.net/wfs" ' + ' typeName="topp:states" srsName="urn:ogc:def:crs:EPSG::4326" ' + ' xmlns:topp="http://www.openplans.org/topp">' + ' <ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">' + ' <ogc:BBOX>' + ' <ogc:PropertyName>the_geom</ogc:PropertyName>' + ' <gml:Envelope xmlns:gml="http://www.opengis.net/gml" ' + ' srsName="urn:ogc:def:crs:EPSG::4326">' + ' <gml:lowerCorner>1 2</gml:lowerCorner>' + ' <gml:upperCorner>3 4</gml:upperCorner>' + ' </gml:Envelope>' + ' </ogc:BBOX>' + ' </ogc:Filter>' + '</wfs:Query>'; var serialized = new ol.format.WFS().writeGetFeature({ srsName: 'urn:ogc:def:crs:EPSG::4326', featureNS: 'http://www.openplans.org/topp', featurePrefix: 'topp', featureTypes: ['states'], geometryName: 'the_geom', bbox: [1, 2, 3, 4] }); expect(serialized.firstElementChild).to.xmleql(ol.xml.parse(text)); }); }); describe('when writing out a Transaction request', function() { it('creates a handle', function() { var text = '<wfs:Transaction xmlns:wfs="http://www.opengis.net/wfs" ' + 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' + 'service="WFS" version="1.1.0" handle="handle_t" ' + 'xsi:schemaLocation="http://www.opengis.net/wfs ' + 'http://schemas.opengis.net/wfs/1.1.0/wfs.xsd"/>'; var serialized = new ol.format.WFS().writeTransaction(null, null, null, {handle: 'handle_t'}); expect(serialized).to.xmleql(ol.xml.parse(text)); }); }); describe('when writing out a Transaction request', function() { var text; before(function(done) { afterLoadText('spec/ol/format/wfs/TransactionSrs.xml', function(xml) { text = xml; done(); }); }); it('creates the correct srsName', function() { var format = new ol.format.WFS(); var insertFeature = new ol.Feature({ the_geom: new ol.geom.MultiLineString([[ [-5178372.1885436, 1992365.7775042], [-4434792.7774889, 1601008.1927386], [-4043435.1927233, 2148908.8114105] ]]), TYPE: 'xyz' }); insertFeature.setGeometryName('the_geom'); var inserts = [insertFeature]; var serialized = format.writeTransaction(inserts, null, null, { featureNS: 'http://foo', featureType: 'FAULTS', featurePrefix: 'feature', gmlOptions: {multiCurve: true, srsName: 'EPSG:900913'} }); expect(serialized).to.xmleql(ol.xml.parse(text)); }); }); describe('when writing out a Transaction request', function() { var text; before(function(done) { afterLoadText('spec/ol/format/wfs/TransactionUpdate.xml', function(xml) { text = xml; done(); }); }); it('creates the correct update', function() { var format = new ol.format.WFS(); var updateFeature = new ol.Feature(); updateFeature.setGeometryName('the_geom'); updateFeature.setGeometry(new ol.geom.MultiLineString([[ [-12279454, 6741885], [-12064207, 6732101], [-11941908, 6595126], [-12240318, 6507071], [-12416429, 6604910] ]])); updateFeature.setId('FAULTS.4455'); var serialized = format.writeTransaction(null, [updateFeature], null, { featureNS: 'http://foo', featureType: 'FAULTS', featurePrefix: 'foo', gmlOptions: {srsName: 'EPSG:900913'} }); expect(serialized).to.xmleql(ol.xml.parse(text)); }); }); describe('when writing out a Transaction request', function() { it('does not create an update if no fid', function() { var format = new ol.format.WFS(); var updateFeature = new ol.Feature(); updateFeature.setGeometryName('the_geom'); updateFeature.setGeometry(new ol.geom.MultiLineString([[ [-12279454, 6741885], [-12064207, 6732101], [-11941908, 6595126], [-12240318, 6507071], [-12416429, 6604910] ]])); var error = false; try { format.writeTransaction(null, [updateFeature], null, { featureNS: 'http://foo', featureType: 'FAULTS', featurePrefix: 'foo', gmlOptions: {srsName: 'EPSG:900913'} }); } catch (e) { error = true; } expect(error).to.be(true); }); }); describe('when writing out a Transaction request', function() { var text, filename = 'spec/ol/format/wfs/TransactionUpdateMultiGeoms.xml'; before(function(done) { afterLoadText(filename, function(xml) { text = xml; done(); } ); }); it('handles multiple geometries', function() { var format = new ol.format.WFS(); var updateFeature = new ol.Feature(); updateFeature.setGeometryName('the_geom'); updateFeature.setGeometry(new ol.geom.MultiLineString([[ [-12279454, 6741885], [-12064207, 6732101], [-11941908, 6595126], [-12240318, 6507071], [-12416429, 6604910] ]])); updateFeature.set('geom2', new ol.geom.MultiLineString([[ [-12000000, 6700000], [-12000001, 6700001], [-12000002, 6700002] ]])); var serialized = format.writeTransaction([updateFeature], [], null, { featureNS: 'http://foo', featureType: 'FAULTS', featurePrefix: 'foo', gmlOptions: {srsName: 'EPSG:900913'} }); expect(serialized).to.xmleql(ol.xml.parse(text)); }); }); describe('when writing out a Transaction request', function() { var text; before(function(done) { afterLoadText('spec/ol/format/wfs/TransactionMulti.xml', function(xml) { text = xml; done(); }); }); it('creates the correct transaction body', function() { var format = new ol.format.WFS(); var insertFeature = new ol.Feature({ the_geom: new ol.geom.MultiPoint([[1, 2]]), foo: 'bar', nul: null }); insertFeature.setGeometryName('the_geom'); var inserts = [insertFeature]; var updateFeature = new ol.Feature({ the_geom: new ol.geom.MultiPoint([[1, 2]]), foo: 'bar', // null value gets Property element with no Value nul: null, // undefined value means don't create a Property element unwritten: undefined }); updateFeature.setId('fid.42'); var updates = [updateFeature]; var deleteFeature = new ol.Feature(); deleteFeature.setId('fid.37'); var deletes = [deleteFeature]; var serialized = format.writeTransaction(inserts, updates, deletes, { featureNS: 'http://www.openplans.org/topp', featureType: 'states', featurePrefix: 'topp' }); expect(serialized).to.xmleql(ol.xml.parse(text)); }); }); describe('when writing out a Transaction request', function() { var text; before(function(done) { afterLoadText('spec/ol/format/wfs/Native.xml', function(xml) { text = xml; done(); }); }); it('handles writing out Native', function() { var format = new ol.format.WFS(); var serialized = format.writeTransaction(null, null, null, { nativeElements: [{ vendorId: 'ORACLE', safeToIgnore: true, value: 'ALTER SESSION ENABLE PARALLEL DML' }, { vendorId: 'ORACLE', safeToIgnore: false, value: 'Another native line goes here' }] }); expect(serialized).to.xmleql(ol.xml.parse(text)); }); }); describe('when writing out a GetFeature request', function() { var text; before(function(done) { afterLoadText('spec/ol/format/wfs/GetFeatureMultiple.xml', function(xml) { text = xml; done(); }); }); it('handles writing multiple Query elements', function() { var format = new ol.format.WFS(); var serialized = format.writeGetFeature({ featureNS: 'http://www.openplans.org/topp', featureTypes: ['states', 'cities'], featurePrefix: 'topp' }); expect(serialized).to.xmleql(ol.xml.parse(text)); }); }); describe('when parsing GML from MapServer', function() { var features, feature; before(function(done) { afterLoadText('spec/ol/format/wfs/mapserver.xml', function(xml) { try { var config = { 'featureNS': 'http://mapserver.gis.umn.edu/mapserver', 'featureType': 'Historische_Messtischblaetter_WFS' }; features = new ol.format.WFS(config).readFeatures(xml); } catch (e) { done(e); } done(); }); }); it('creates 7 features', function() { expect(features).to.have.length(7); }); it('creates a polygon for Arnstadt', function() { feature = features[0]; var fid = 'Historische_Messtischblaetter_WFS.71055885'; expect(feature.getId()).to.equal(fid); expect(feature.get('titel')).to.equal('Arnstadt'); expect(feature.getGeometry()).to.be.an(ol.geom.Polygon); }); }); describe('when parsing multiple feature types', function() { var features; before(function(done) { afterLoadText('spec/ol/format/gml/multiple-typenames.xml', function(xml) { try { features = new ol.format.WFS({ featureNS: 'http://localhost:8080/official', featureType: ['planet_osm_polygon', 'planet_osm_line'] }).readFeatures(xml); } catch (e) { done(e); } done(); }); }); it('reads all features', function() { expect(features.length).to.be(12); }); }); describe('when parsing multiple feature types', function() { var features; before(function(done) { afterLoadText('spec/ol/format/gml/multiple-typenames.xml', function(xml) { try { features = new ol.format.WFS().readFeatures(xml); } catch (e) { done(e); } done(); }); }); it('reads all features with autoconfigure', function() { expect(features.length).to.be(12); }); }); }); goog.require('ol.xml'); goog.require('ol.Feature'); goog.require('ol.geom.MultiLineString'); goog.require('ol.geom.MultiPoint'); goog.require('ol.geom.MultiPolygon'); goog.require('ol.geom.Polygon'); goog.require('ol.format.GML2'); goog.require('ol.format.WFS'); goog.require('ol.proj');
NOAA-ORR-ERD/ol3
test/spec/ol/format/wfsformat.test.js
JavaScript
bsd-2-clause
18,764
#include <SFGUI/ResourceManager.hpp> #include <SFGUI/FileResourceLoader.hpp> #if defined( SFGUI_INCLUDE_FONT ) #include <SFGUI/DejaVuSansFont.hpp> #endif #include <SFML/Graphics/Font.hpp> namespace sfg { ResourceManager::ResourceManager( bool use_default_font ) : m_use_default_font( use_default_font ) { // Add file resource loader as fallback. CreateLoader<FileResourceLoader>(); } std::shared_ptr<const ResourceLoader> ResourceManager::GetLoader( const std::string& id ) { auto loader_iter = m_loaders.find( id ); return loader_iter == m_loaders.end() ? std::shared_ptr<const ResourceLoader>() : loader_iter->second; } std::shared_ptr<const sf::Font> ResourceManager::GetFont( const std::string& path ) { { auto font_iter = m_fonts.find( path ); if( font_iter != m_fonts.end() ) { return font_iter->second; } } if( path == "Default" ) { if( m_use_default_font ) { #if defined( SFGUI_INCLUDE_FONT ) auto font = std::make_shared<sf::Font>( LoadDejaVuSansFont() ); #else #if defined( SFGUI_DEBUG ) std::cerr << "SFGUI warning: No default font available. (SFGUI_INCLUDE_FONT = FALSE)\n"; #endif auto font = std::make_shared<sf::Font>(); #endif m_fonts[path] = font; return font; } return std::shared_ptr<const sf::Font>(); } // Try to load. auto loader = GetMatchingLoader( path ); if( !loader ) { std::shared_ptr<const sf::Font> font; if( m_use_default_font ) { auto font_iter = m_fonts.find( path ); if( font_iter == m_fonts.end() ) { #if defined( SFGUI_INCLUDE_FONT ) font = std::make_shared<sf::Font>( LoadDejaVuSansFont() ); #else #if defined( SFGUI_DEBUG ) std::cerr << "SFGUI warning: No default font available. (SFGUI_INCLUDE_FONT = FALSE)\n"; #endif font = std::make_shared<sf::Font>(); #endif m_fonts[path] = font; } else { font = font_iter->second; } } return font; } auto font = loader->LoadFont( GetFilename( path, *loader ) ); if( !font ) { if( m_use_default_font ) { auto font_iter = m_fonts.find( path ); if( font_iter == m_fonts.end() ) { #if defined( SFGUI_INCLUDE_FONT ) font = std::make_shared<sf::Font>( LoadDejaVuSansFont() ); #else #if defined( SFGUI_DEBUG ) std::cerr << "SFGUI warning: No default font available. (SFGUI_INCLUDE_FONT = FALSE)\n"; #endif font = std::make_shared<sf::Font>(); #endif m_fonts[path] = font; } else { font = font_iter->second; } } return font; } // Cache. m_fonts[path] = font; return font; } std::shared_ptr<const sf::Image> ResourceManager::GetImage( const std::string& path ) { auto image_iter = m_images.find( path ); if( image_iter != m_images.end() ) { return image_iter->second; } // Try to load. auto loader = GetMatchingLoader( path ); if( !loader ) { return std::shared_ptr<const sf::Image>(); } auto image = loader->LoadImage( GetFilename( path, *loader ) ); if( !image ) { return std::shared_ptr<const sf::Image>(); } // Cache. m_images[path] = image; return image; } std::shared_ptr<const ResourceLoader> ResourceManager::GetMatchingLoader( const std::string& path ) { if( path.empty() || ( path == "Default" ) ) { return std::shared_ptr<const ResourceLoader>(); } // Extract prefix. auto colon_pos = path.find( ':' ); std::shared_ptr<const ResourceLoader> loader; if( colon_pos != std::string::npos ) { auto ident = path.substr( 0, colon_pos ); auto loader_iter = m_loaders.find( ident ); if( loader_iter != m_loaders.end() ) { loader = loader_iter->second; } } // Use file loader as fallback. if( !loader ) { loader = m_loaders["file"]; } return loader; } void ResourceManager::Clear() { m_loaders.clear(); m_fonts.clear(); m_images.clear(); } std::string ResourceManager::GetFilename( const std::string& path, const ResourceLoader& loader ) { auto ident = loader.GetIdentifier() + ":"; auto ident_pos = path.find( ident ); if( ident_pos == std::string::npos || ident_pos != 0 ) { return path; } return path.substr( ident.size() ); } void ResourceManager::AddFont( const std::string& path, std::shared_ptr<const sf::Font> font ) { m_fonts[path] = font; } void ResourceManager::AddImage( const std::string& path, std::shared_ptr<const sf::Image> image ) { m_images[path] = image; } void ResourceManager::SetDefaultFont( std::shared_ptr<const sf::Font> font ) { AddFont( "", font ); } }
Krozark/SFML-book
extlibs/SFGUI/src/SFGUI/ResourceManager.cpp
C++
bsd-2-clause
4,383
#ifndef Rice__Module_defn__hpp_ #define Rice__Module_defn__hpp_ #include "Object_defn.hpp" #include "Module_impl.hpp" #include "to_from_ruby_defn.hpp" #include <memory> namespace Rice { class Array; class Class; class String; //! A helper for defining a Module and its methods. /*! This class provides a C++-style interface to ruby's Module class and * for defining methods on that module. * * Many of the methods are defined in Module_impl.hpp so that they can * return a reference to the most derived type. */ class Module // TODO: we can't inherit from Builtin_Object, because Class needs // type T_CLASS and Module needs type T_MODULE : public Module_impl<Module_base, Module> { public: //! Default construct a Module and initialize it to rb_cObject. Module(); //! Construct a Module from an existing Module object. Module(VALUE v); //! Return the name of the module. String name() const; //! Swap with another Module. void swap(Module & other); //! Return an array containing the Module's ancestors. /*! You will need to include Array.hpp to use this function. */ Array ancestors() const; //! Return the module's singleton class. /*! You will need to include Class.hpp to use this function. */ Class singleton_class() const; }; //! Define a new module in the namespace given by module. /*! \param module the module in which to define the new module. * \param name the name of the new module. */ Module define_module_under( Object module, char const * name); //! Define a new module in the default namespace. /*! \param name the name of the new module. */ Module define_module( char const * name); //! Create a new anonymous module. /*! \return the new module. */ Module anonymous_module(); } // namespace Rice template<> inline Rice::Module from_ruby<Rice::Module>(Rice::Object x) { return Rice::Module(x); } template<> inline Rice::Object to_ruby<Rice::Module>(Rice::Module const & x) { return x; } #endif // Rice__Module_defn__hpp_
cout/rice
rice/Module_defn.hpp
C++
bsd-2-clause
2,025
cask "freetube" do version "0.13.2" sha256 "104b5718b54a0015453b934a58b333cb1336c6d5ec87148abb4722ada870b682" url "https://github.com/FreeTubeApp/FreeTube/releases/download/v#{version}-beta/freetube-#{version}-mac.dmg" name "FreeTube" desc "YouTube player focusing on privacy" homepage "https://github.com/FreeTubeApp/FreeTube" livecheck do url :url regex(/^v?(\d+(?:\.\d+)+)/i) end app "FreeTube.app" zap trash: [ "~/Library/Application Support/FreeTube", "~/Library/Preferences/io.freetubeapp.freetube.plist", "~/Library/Saved Application State/io.freetubeapp.freetube.savedState", ] end
tjnycum/homebrew-cask
Casks/freetube.rb
Ruby
bsd-2-clause
636
cask 'docker' do version '1.12.0.10871' sha256 'f170610d95c188dee8433eff33c84696c1c8a39421de548a71a1258a458e1b21' url "https://download.docker.com/mac/stable/#{version}/Docker.dmg" appcast 'https://download.docker.com/mac/stable/appcast.xml', checkpoint: 'ee03f7c36b4192a64ba30e49a0fa1f8358cc3fe4a8a3af3def066c80f36b18bf' name 'Docker for Mac' homepage 'https://www.docker.com/products/docker' license :mit auto_updates true app 'Docker.app' end
MoOx/homebrew-cask
Casks/docker.rb
Ruby
bsd-2-clause
477
# this: every_hour.py # by: Poul Staugaard (poul(dot)staugaard(at)gmail...) # URL: http://code.google.com/p/giewiki # ver.: 1.13 import cgi import codecs import datetime import difflib import glob import hashlib import logging import os import re import urllib import urlparse import uuid import xml.dom.minidom from new import instance, classobj from os import path from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db from google.appengine.api import memcache from google.appengine.api import urlfetch from google.appengine.api import mail from google.appengine.api import namespace_manager from giewikidb import Tiddler,SiteInfo,ShadowTiddler,EditLock,Page,PageTemplate,DeletionLog,Comment,Include,Note,Message,Group,GroupMember,UrlImport,UploadedFile,UserProfile,PenName,SubDomain,LogEntry,CronJob from giewikidb import truncateModel, truncateAllData, HasGroupAccess, ReadAccessToPage, AccessToPage, IsSoleOwner, Upgrade, CopyIntoNamespace, dropCronJob class EveryHour(webapp.RequestHandler): def get(self): for cj in CronJob.all(): if cj.when < datetime.datetime.now(): tdlr = Tiddler.all().filter('id',cj.tiddler).filter('current',True).get() if tdlr is None: logging.warning("Tiddler not found") else: if cj.action == 'promote': logging.info("CJob:promote " + cj.tiddler) if hasattr(tdlr,'deprecated'): delattr(tdlr,'deprecated') tdlr.tags = tdlr.tags.replace('@promote@','@promoted@') tdlr.put() dts = Tiddler.all().filter('page', tdlr.page).filter('title','DefaultTiddlers').filter('current', True).get() if dts is None: logging.warning("DefaultTiddlers not found for page " + tdlr.page) else: dtparts = dts.text.split('\n') dtparts.insert(cj.position,'[[' + tdlr.title + ']]') dts.text = '\n'.join(dtparts) dts.put() logging.info("Tiddler " + tdlr.title + " added to DefaultTiddlers") if cj.action == 'announce': logging.info("CJob/announce " + cj.tiddler) if hasattr(tdlr,'deprecated'): delattr(tdlr,'deprecated') tdlr.tags = tdlr.tags.replace('@announce@','@announced@') tdlr.put() dts = Tiddler.all().filter('page', tdlr.page).filter('title','MainMenu').filter('current', True).get() if dts is None: logging.warning("MainMenu not found for page " + tdlr.page) else: dtparts = dts.text.split('\n') dtparts.insert(cj.position,'[[' + tdlr.title + ']]') dts.text = '\n'.join(dtparts) dts.put() logging.info("Tiddler " + tdlr.title + " added to MainMenu") if cj.action == 'demote' or cj.action == 'deprecate': logging.info("CJob:demote " + cj.tiddler) dts = Tiddler.all().filter('page', tdlr.page).filter('title','DefaultTiddlers').filter('current', True).get() if not dts is None: ss = '[[' + tdlr.title + ']]\n' dts.text = dts.text.replace(ss,'') dts.put() dts = Tiddler.all().filter('page', tdlr.page).filter('title','MainMenu').filter('current', True).get() if not dts is None: ss = '[[' + tdlr.title + ']]\n' dts.text = dts.text.replace(ss,'') dts.put() if cj.action == 'deprecate': logging.info("CJob:deprecate " + cj.tiddler) setattr(tdlr,'deprecated',True) tdlr.put() if cj.action == 'revert': logging.info("CJob: revert " + str(cj.tiddler) + " to V#" + str(cj.position)) rvn = cj.position if cj.position > 0 else tdlr.version - 1 tdlrvr = Tiddler.all().filter('id',cj.tiddler).filter('version',rvn).get() if tdlrvr is None: logging.warning("Version " + str(rvn) + " of tiddler " + tdlr.page + "#" + tdlr.title + " not found!") else: tdlr.current = False tdlr.put() tdlrvr.current = True tdlrvr.vercnt = tdlr.vercnt tdlrvr.reverted = datetime.datetime.now() tdlrvr.reverted_by = None tdlrvr.put() cj.delete() application = webapp.WSGIApplication( [('/every_1_hours', EveryHour)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
wangjun/giewiki
every_hour.py
Python
bsd-2-clause
4,271
class Mediaconch < Formula desc "Conformance checker and technical metadata reporter" homepage "https://mediaarea.net/MediaConch" url "https://mediaarea.net/download/binary/mediaconch/18.03.2/MediaConch_CLI_18.03.2_GNU_FromSource.tar.bz2" sha256 "8f8f31f1c3eb55449799ebb2031ef373934a0a9826ce6c2b2bdd32dacbf5ec4c" revision 1 livecheck do url "https://mediaarea.net/MediaConch/Download/Source" regex(/href=.*?MediaConch[._-]CLI[._-]v?(\d+(?:\.\d+)+)[._-]GNU[._-]FromSource\.t/i) end bottle do sha256 cellar: :any, arm64_big_sur: "2bc516280f29cda43dcda638a0a5dd586a34fc52beb724bd97f382825d347d7a" sha256 cellar: :any, big_sur: "1ab9e887a8787b4b3655df4f9b01214da00ef466da186db7dca1ae646bb09b3d" sha256 cellar: :any, catalina: "41a49bbafbffc220f140d8e466f1507757cbe552f8de4ca306217affbf1e6dd5" sha256 cellar: :any, mojave: "9d59b85fecc5d5caba622fe57358caab23c8ea904954a137b99e66dd4f7fedec" sha256 cellar: :any, high_sierra: "d59cfb9ac07ffb7eacc4c7970c38676a3909f0966481b99c745735bf87db7b8e" sha256 cellar: :any, sierra: "fdb3934174a68121357c21d4f0800e8bbbaa6a296f3386ab52e5298fde96a6b6" sha256 cellar: :any_skip_relocation, x86_64_linux: "87ccb6aac84590c501a35ea7ce511f21d1f902a7d37dbdcef722a7c6149dee0f" end depends_on "pkg-config" => :build depends_on "jansson" depends_on "libevent" depends_on "sqlite" uses_from_macos "curl" uses_from_macos "libxslt" def install cd "ZenLib/Project/GNU/Library" do args = ["--disable-debug", "--disable-dependency-tracking", "--enable-shared", "--enable-static", "--prefix=#{prefix}", # mediaconch installs libs/headers at the same paths as mediainfo "--libdir=#{lib}/mediaconch", "--includedir=#{include}/mediaconch"] system "./configure", *args system "make", "install" end cd "MediaInfoLib/Project/GNU/Library" do args = ["--disable-debug", "--disable-dependency-tracking", "--enable-static", "--enable-shared", "--with-libcurl", "--prefix=#{prefix}", "--libdir=#{lib}/mediaconch", "--includedir=#{include}/mediaconch"] system "./configure", *args system "make", "install" end cd "MediaConch/Project/GNU/CLI" do system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end end test do pipe_output("#{bin}/mediaconch", test_fixtures("test.mp3")) end end
zyedidia/homebrew-core
Formula/mediaconch.rb
Ruby
bsd-2-clause
2,757
from lino.api import dd class Persons(dd.Table): model = 'app.Person' column_names = 'name *' detail_layout = """ id name owned_places managed_places VisitsByPerson MealsByPerson """ class Places(dd.Table): model = 'app.Place' detail_layout = """ id name ceo owners VisitsByPlace """ class Restaurants(dd.Table): model = 'app.Restaurant' detail_layout = """ id place serves_hot_dogs cooks MealsByRestaurant """ class VisitsByPlace(dd.Table): model = 'app.Visit' master_key = 'place' column_names = 'person purpose' class VisitsByPerson(dd.Table): model = 'app.Visit' master_key = 'person' column_names = 'place purpose' class MealsByRestaurant(dd.Table): model = 'app.Meal' master_key = 'restaurant' column_names = 'person what' class MealsByPerson(dd.Table): model = 'app.Meal' master_key = 'person' column_names = 'restaurant what'
lino-framework/book
lino_book/projects/nomti/app/desktop.py
Python
bsd-2-clause
979
/* * 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 com.evernote.thrift.protocol; /** * Helper class that encapsulates list metadata. * */ public final class TList { public TList() { this(TType.STOP, 0); } public TList(byte t, int s) { elemType = t; size = s; } public final byte elemType; public final int size; }
alexchenzl/evernote-sdk-java
src/main/java/com/evernote/thrift/protocol/TList.java
Java
bsd-2-clause
1,107
"""Test module for wiring with invalid type of marker for attribute injection.""" from dependency_injector.wiring import Closing service = Closing["service"]
rmk135/dependency_injector
tests/unit/samples/wiringstringids/module_invalid_attr_injection.py
Python
bsd-3-clause
161
from datadog import initialize, api options = { 'api_key': '9775a026f1ca7d1c6c5af9d94d9595a4', 'app_key': '87ce4a24b5553d2e482ea8a8500e71b8ad4554ff' } initialize(**options) # Get a downtime api.Downtime.get(2910)
jhotta/documentation
code_snippets/api-monitor-get-downtime.py
Python
bsd-3-clause
224
/* This file is part of the Vc library. {{{ Copyright © 2011-2015 Matthias Kretz <kretz@kde.org> 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 names of contributing organizations 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 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. }}}*/ #include <avx/vector.h> #include <avx/debug.h> #include <avx/macros.h> namespace Vc_VERSIONED_NAMESPACE { namespace Detail { #ifdef Vc_IMPL_AVX2 template <> Vc_CONST AVX2::short_v sorted<CurrentImplementation::current()>(AVX2::short_v x_) { // ab cd ef gh ij kl mn op // ↓↑ ↓↑ ↓↑ ↓↑ ↓↑ ↓↑ ↓↑ ↓↑ // ⎮⎝ ⎠⎮ ⎮⎝ ⎠⎮ ⎮⎝ ⎠⎮ ⎮⎝ ⎠⎮ // ⎮ ╳ ⎮ ⎮ ╳ ⎮ ⎮ ╳ ⎮ ⎮ ╳ ⎮ // ⎮⎛ ⎞⎮ ⎮⎛ ⎞⎮ ⎮⎛ ⎞⎮ ⎮⎛ ⎞⎮ // <> <> <> <> <> <> <> <> // ↓↑ ↓↑ ↓↑ ↓↑ ↓↑ ↓↑ ↓↑ ↓↑ // ⎮⎝ ⎠⎮ ⎮⎝ ⎠⎮ ⎮⎝ ⎠⎮ ⎮⎝ ⎠⎮ // ⎮ o ⎮ ⎮ o ⎮ ⎮ o ⎮ ⎮ o ⎮ // ⎮↓ ↑⎮ ⎮↓ ↑⎮ ⎮↓ ↑⎮ ⎮↓ ↑⎮ // 01 23 01 23 01 23 01 23 // ⎮⎮ ⎮⎮ ╳ ⎮⎮ ⎮⎮ ╳ // 01 23 32 10 01 23 32 10 // ⎮⎝ ⎮⎝ ⎠⎮ ⎠⎮ ⎮⎝ ⎮⎝ ⎠⎮ ⎠⎮ // ⎮ ╲⎮ ╳ ⎮╱ ⎮ ⎮ ╲⎮ ╳ ⎮╱ ⎮ // ⎮ ╲╱ ╲╱ ⎮ ⎮ ╲╱ ╲╱ ⎮ // ⎮ ╱╲ ╱╲ ⎮ ⎮ ╱╲ ╱╲ ⎮ // ⎮ ╱⎮ ╳ ⎮╲ ⎮ ⎮ ╱⎮ ╳ ⎮╲ ⎮ // ⎮⎛ ⎮⎛ ⎞⎮ ⎞⎮ ⎮⎛ ⎮⎛ ⎞⎮ ⎞⎮ // <> <> <> <> <> <> <> <> // ↓↑ ↓↑ ↓↑ ↓↑ ↓↑ ↓↑ ↓↑ ↓↑ // ⎮⎝ ⎠⎮ ⎮⎝ ⎠⎮ ⎮⎝ ⎠⎮ ⎮⎝ ⎠⎮ // ⎮ ╳ ⎮ ⎮ ╳ ⎮ ⎮ ╳ ⎮ ⎮ ╳ ⎮ // ⎮⎛ ⎞⎮ ⎮⎛ ⎞⎮ ⎮⎛ ⎞⎮ ⎮⎛ ⎞⎮ // <> <> <> <> <> <> <> <> // ↓↑ ↓↑ ↓↑ ↓↑ ↓↑ ↓↑ ↓↑ ↓↑ // ⎮⎝ ⎠⎮ ⎮⎝ ⎠⎮ ⎮⎝ ⎠⎮ ⎮⎝ ⎠⎮ // ⎮ o ⎮ ⎮ o ⎮ ⎮ o ⎮ ⎮ o ⎮ // ⎮↓ ↑⎮ ⎮↓ ↑⎮ ⎮↓ ↑⎮ ⎮↓ ↑⎮ // 01 23 01 23 01 23 01 23 // sort pairs (one min/max) auto x = AVX::lo128(x_.data()); auto y = AVX::hi128(x_.data()); Vc_DEBUG << "xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); auto l = _mm_min_epi16(x, y); auto h = _mm_max_epi16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); // merge left & right quads (two min/max) x = _mm_unpacklo_epi16(l, h); y = _mm_unpackhi_epi16(h, l); Vc_DEBUG << "8x2 sorted xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epi16(x, y); h = _mm_max_epi16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); x = Mem::permuteLo<X1, X0, X3, X2>(Mem::blend<X0, Y1, X2, Y3, X4, Y5, X6, Y7>(l, h)); y = Mem::permuteHi<X5, X4, X7, X6>(Mem::blend<X0, Y1, X2, Y3, X4, Y5, X6, Y7>(h, l)); Vc_DEBUG << "xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epi16(x, y); h = _mm_max_epi16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); // merge quads into octs (three min/max) x = _mm_unpacklo_epi16(h, l); y = _mm_unpackhi_epi16(l, h); Vc_DEBUG << "4x4 sorted xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epi16(x, y); h = _mm_max_epi16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); x = Mem::permuteLo<X2, X3, X0, X1>(Mem::blend<X0, X1, Y2, Y3, X4, X5, Y6, Y7>(h, l)); y = Mem::permuteHi<X6, X7, X4, X5>(Mem::blend<X0, X1, Y2, Y3, X4, X5, Y6, Y7>(l, h)); Vc_DEBUG << "xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epi16(x, y); h = _mm_max_epi16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); x = Mem::permuteHi<X5, X4, X7, X6>(Mem::blend<X0, Y1, X2, Y3, X4, Y5, X6, Y7>(l, h)); y = Mem::permuteLo<X1, X0, X3, X2>(Mem::blend<X0, Y1, X2, Y3, X4, Y5, X6, Y7>(h, l)); Vc_DEBUG << "xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epi16(x, y); h = _mm_max_epi16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h) << " done?"; // merge octs into hexa (four min/max) x = _mm_unpacklo_epi16(l, h); y = _mm_unpackhi_epi16(h, l); Vc_DEBUG << "2x8 sorted xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epi16(x, y); h = _mm_max_epi16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); x = _mm_unpacklo_epi64(l, h); y = _mm_unpackhi_epi64(l, h); Vc_DEBUG << "xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epi16(x, y); h = _mm_max_epi16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); x = _mm_castps_si128(Mem::permute<X1, X0, X3, X2>(Mem::blend<X0, Y1, X2, Y3>(_mm_castsi128_ps(h), _mm_castsi128_ps(l)))); y = _mm_castps_si128(Mem::blend<X0, Y1, X2, Y3>(_mm_castsi128_ps(l), _mm_castsi128_ps(h))); Vc_DEBUG << "xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epi16(x, y); h = _mm_max_epi16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); x = Mem::blend<X0, Y1, X2, Y3, X4, Y5, X6, Y7>(l, h); y = Mem::permuteLo<X1, X0, X3, X2>( Mem::permuteHi<X5, X4, X7, X6>(Mem::blend<X0, Y1, X2, Y3, X4, Y5, X6, Y7>(h, l))); Vc_DEBUG << "xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epi16(x, y); h = _mm_max_epi16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); x = _mm_unpacklo_epi16(l, h); y = _mm_unpackhi_epi16(l, h); return AVX::concat(x, y); } template <> Vc_CONST AVX2::ushort_v sorted<CurrentImplementation::current()>(AVX2::ushort_v x_) { // sort pairs (one min/max) auto x = AVX::lo128(x_.data()); auto y = AVX::hi128(x_.data()); Vc_DEBUG << "xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); auto l = _mm_min_epu16(x, y); auto h = _mm_max_epu16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); // merge left & right quads (two min/max) x = _mm_unpacklo_epi16(l, h); y = _mm_unpackhi_epi16(h, l); Vc_DEBUG << "8x2 sorted xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epu16(x, y); h = _mm_max_epu16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); x = Mem::permuteLo<X1, X0, X3, X2>(Mem::blend<X0, Y1, X2, Y3, X4, Y5, X6, Y7>(l, h)); y = Mem::permuteHi<X5, X4, X7, X6>(Mem::blend<X0, Y1, X2, Y3, X4, Y5, X6, Y7>(h, l)); Vc_DEBUG << "xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epu16(x, y); h = _mm_max_epu16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); // merge quads into octs (three min/max) x = _mm_unpacklo_epi16(h, l); y = _mm_unpackhi_epi16(l, h); Vc_DEBUG << "4x4 sorted xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epu16(x, y); h = _mm_max_epu16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); x = Mem::permuteLo<X2, X3, X0, X1>(Mem::blend<X0, X1, Y2, Y3, X4, X5, Y6, Y7>(h, l)); y = Mem::permuteHi<X6, X7, X4, X5>(Mem::blend<X0, X1, Y2, Y3, X4, X5, Y6, Y7>(l, h)); Vc_DEBUG << "xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epu16(x, y); h = _mm_max_epu16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); x = Mem::permuteHi<X5, X4, X7, X6>(Mem::blend<X0, Y1, X2, Y3, X4, Y5, X6, Y7>(l, h)); y = Mem::permuteLo<X1, X0, X3, X2>(Mem::blend<X0, Y1, X2, Y3, X4, Y5, X6, Y7>(h, l)); Vc_DEBUG << "xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epu16(x, y); h = _mm_max_epu16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h) << " done?"; // merge octs into hexa (four min/max) x = _mm_unpacklo_epi16(l, h); y = _mm_unpackhi_epi16(h, l); Vc_DEBUG << "2x8 sorted xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epu16(x, y); h = _mm_max_epu16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); x = _mm_unpacklo_epi64(l, h); y = _mm_unpackhi_epi64(l, h); Vc_DEBUG << "xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epu16(x, y); h = _mm_max_epu16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); x = _mm_castps_si128(Mem::permute<X1, X0, X3, X2>(Mem::blend<X0, Y1, X2, Y3>(_mm_castsi128_ps(h), _mm_castsi128_ps(l)))); y = _mm_castps_si128(Mem::blend<X0, Y1, X2, Y3>(_mm_castsi128_ps(l), _mm_castsi128_ps(h))); Vc_DEBUG << "xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epu16(x, y); h = _mm_max_epu16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); x = Mem::blend<X0, Y1, X2, Y3, X4, Y5, X6, Y7>(l, h); y = Mem::permuteLo<X1, X0, X3, X2>( Mem::permuteHi<X5, X4, X7, X6>(Mem::blend<X0, Y1, X2, Y3, X4, Y5, X6, Y7>(h, l))); Vc_DEBUG << "xy: " << AVX::addType<short>(x) << AVX::addType<short>(y); l = _mm_min_epu16(x, y); h = _mm_max_epu16(x, y); Vc_DEBUG << "lh: " << AVX::addType<short>(l) << AVX::addType<short>(h); x = _mm_unpacklo_epi16(l, h); y = _mm_unpackhi_epi16(l, h); return AVX::concat(x, y); } template <> Vc_CONST AVX2::int_v sorted<CurrentImplementation::current()>(AVX2::int_v x_) { using namespace AVX; const __m256i hgfedcba = x_.data(); const __m128i hgfe = hi128(hgfedcba); const __m128i dcba = lo128(hgfedcba); __m128i l = _mm_min_epi32(hgfe, dcba); // ↓hd ↓gc ↓fb ↓ea __m128i h = _mm_max_epi32(hgfe, dcba); // ↑hd ↑gc ↑fb ↑ea __m128i x = _mm_unpacklo_epi32(l, h); // ↑fb ↓fb ↑ea ↓ea __m128i y = _mm_unpackhi_epi32(l, h); // ↑hd ↓hd ↑gc ↓gc l = _mm_min_epi32(x, y); // ↓(↑fb,↑hd) ↓hfdb ↓(↑ea,↑gc) ↓geca h = _mm_max_epi32(x, y); // ↑hfdb ↑(↓fb,↓hd) ↑geca ↑(↓ea,↓gc) x = _mm_min_epi32(l, Reg::permute<X2, X2, X0, X0>(h)); // 2(hfdb) 1(hfdb) 2(geca) 1(geca) y = _mm_max_epi32(h, Reg::permute<X3, X3, X1, X1>(l)); // 4(hfdb) 3(hfdb) 4(geca) 3(geca) __m128i b = Reg::shuffle<Y0, Y1, X0, X1>(y, x); // b3 <= b2 <= b1 <= b0 __m128i a = _mm_unpackhi_epi64(x, y); // a3 >= a2 >= a1 >= a0 // _mm_extract_epi32 may return an unsigned int, breaking these comparisons. if (Vc_IS_UNLIKELY(static_cast<int>(_mm_extract_epi32(x, 2)) >= static_cast<int>(_mm_extract_epi32(y, 1)))) { return concat(Reg::permute<X0, X1, X2, X3>(b), a); } else if (Vc_IS_UNLIKELY(static_cast<int>(_mm_extract_epi32(x, 0)) >= static_cast<int>(_mm_extract_epi32(y, 3)))) { return concat(a, Reg::permute<X0, X1, X2, X3>(b)); } // merge l = _mm_min_epi32(a, b); // ↓a3b3 ↓a2b2 ↓a1b1 ↓a0b0 h = _mm_max_epi32(a, b); // ↑a3b3 ↑a2b2 ↑a1b1 ↑a0b0 a = _mm_unpacklo_epi32(l, h); // ↑a1b1 ↓a1b1 ↑a0b0 ↓a0b0 b = _mm_unpackhi_epi32(l, h); // ↑a3b3 ↓a3b3 ↑a2b2 ↓a2b2 l = _mm_min_epi32(a, b); // ↓(↑a1b1,↑a3b3) ↓a1b3 ↓(↑a0b0,↑a2b2) ↓a0b2 h = _mm_max_epi32(a, b); // ↑a3b1 ↑(↓a1b1,↓a3b3) ↑a2b0 ↑(↓a0b0,↓a2b2) a = _mm_unpacklo_epi32(l, h); // ↑a2b0 ↓(↑a0b0,↑a2b2) ↑(↓a0b0,↓a2b2) ↓a0b2 b = _mm_unpackhi_epi32(l, h); // ↑a3b1 ↓(↑a1b1,↑a3b3) ↑(↓a1b1,↓a3b3) ↓a1b3 l = _mm_min_epi32(a, b); // ↓(↑a2b0,↑a3b1) ↓(↑a0b0,↑a2b2,↑a1b1,↑a3b3) ↓(↑(↓a0b0,↓a2b2) ↑(↓a1b1,↓a3b3)) ↓a0b3 h = _mm_max_epi32(a, b); // ↑a3b0 ↑(↓(↑a0b0,↑a2b2) ↓(↑a1b1,↑a3b3)) ↑(↓a0b0,↓a2b2,↓a1b1,↓a3b3) ↑(↓a0b2,↓a1b3) return concat(_mm_unpacklo_epi32(l, h), _mm_unpackhi_epi32(l, h)); } template <> Vc_CONST AVX2::uint_v sorted<CurrentImplementation::current()>(AVX2::uint_v x_) { using namespace AVX; const __m256i hgfedcba = x_.data(); const __m128i hgfe = hi128(hgfedcba); const __m128i dcba = lo128(hgfedcba); __m128i l = _mm_min_epu32(hgfe, dcba); // ↓hd ↓gc ↓fb ↓ea __m128i h = _mm_max_epu32(hgfe, dcba); // ↑hd ↑gc ↑fb ↑ea __m128i x = _mm_unpacklo_epi32(l, h); // ↑fb ↓fb ↑ea ↓ea __m128i y = _mm_unpackhi_epi32(l, h); // ↑hd ↓hd ↑gc ↓gc l = _mm_min_epu32(x, y); // ↓(↑fb,↑hd) ↓hfdb ↓(↑ea,↑gc) ↓geca h = _mm_max_epu32(x, y); // ↑hfdb ↑(↓fb,↓hd) ↑geca ↑(↓ea,↓gc) x = _mm_min_epu32(l, Reg::permute<X2, X2, X0, X0>(h)); // 2(hfdb) 1(hfdb) 2(geca) 1(geca) y = _mm_max_epu32(h, Reg::permute<X3, X3, X1, X1>(l)); // 4(hfdb) 3(hfdb) 4(geca) 3(geca) __m128i b = Reg::shuffle<Y0, Y1, X0, X1>(y, x); // b3 <= b2 <= b1 <= b0 __m128i a = _mm_unpackhi_epi64(x, y); // a3 >= a2 >= a1 >= a0 if (Vc_IS_UNLIKELY(extract_epu32<2>(x) >= extract_epu32<1>(y))) { return concat(Reg::permute<X0, X1, X2, X3>(b), a); } else if (Vc_IS_UNLIKELY(extract_epu32<0>(x) >= extract_epu32<3>(y))) { return concat(a, Reg::permute<X0, X1, X2, X3>(b)); } // merge l = _mm_min_epu32(a, b); // ↓a3b3 ↓a2b2 ↓a1b1 ↓a0b0 h = _mm_max_epu32(a, b); // ↑a3b3 ↑a2b2 ↑a1b1 ↑a0b0 a = _mm_unpacklo_epi32(l, h); // ↑a1b1 ↓a1b1 ↑a0b0 ↓a0b0 b = _mm_unpackhi_epi32(l, h); // ↑a3b3 ↓a3b3 ↑a2b2 ↓a2b2 l = _mm_min_epu32(a, b); // ↓(↑a1b1,↑a3b3) ↓a1b3 ↓(↑a0b0,↑a2b2) ↓a0b2 h = _mm_max_epu32(a, b); // ↑a3b1 ↑(↓a1b1,↓a3b3) ↑a2b0 ↑(↓a0b0,↓a2b2) a = _mm_unpacklo_epi32(l, h); // ↑a2b0 ↓(↑a0b0,↑a2b2) ↑(↓a0b0,↓a2b2) ↓a0b2 b = _mm_unpackhi_epi32(l, h); // ↑a3b1 ↓(↑a1b1,↑a3b3) ↑(↓a1b1,↓a3b3) ↓a1b3 l = _mm_min_epu32(a, b); // ↓(↑a2b0,↑a3b1) ↓(↑a0b0,↑a2b2,↑a1b1,↑a3b3) ↓(↑(↓a0b0,↓a2b2) ↑(↓a1b1,↓a3b3)) ↓a0b3 h = _mm_max_epu32(a, b); // ↑a3b0 ↑(↓(↑a0b0,↑a2b2) ↓(↑a1b1,↑a3b3)) ↑(↓a0b0,↓a2b2,↓a1b1,↓a3b3) ↑(↓a0b2,↓a1b3) return concat(_mm_unpacklo_epi32(l, h), _mm_unpackhi_epi32(l, h)); } #endif // AVX2 template <> Vc_CONST AVX2::float_v sorted<CurrentImplementation::current()>(AVX2::float_v x_) { __m256 hgfedcba = x_.data(); const __m128 hgfe = AVX::hi128(hgfedcba); const __m128 dcba = AVX::lo128(hgfedcba); __m128 l = _mm_min_ps(hgfe, dcba); // ↓hd ↓gc ↓fb ↓ea __m128 h = _mm_max_ps(hgfe, dcba); // ↑hd ↑gc ↑fb ↑ea __m128 x = _mm_unpacklo_ps(l, h); // ↑fb ↓fb ↑ea ↓ea __m128 y = _mm_unpackhi_ps(l, h); // ↑hd ↓hd ↑gc ↓gc l = _mm_min_ps(x, y); // ↓(↑fb,↑hd) ↓hfdb ↓(↑ea,↑gc) ↓geca h = _mm_max_ps(x, y); // ↑hfdb ↑(↓fb,↓hd) ↑geca ↑(↓ea,↓gc) x = _mm_min_ps(l, Reg::permute<X2, X2, X0, X0>(h)); // 2(hfdb) 1(hfdb) 2(geca) 1(geca) y = _mm_max_ps(h, Reg::permute<X3, X3, X1, X1>(l)); // 4(hfdb) 3(hfdb) 4(geca) 3(geca) __m128 a = _mm_castpd_ps(_mm_unpackhi_pd(_mm_castps_pd(x), _mm_castps_pd(y))); // a3 >= a2 >= a1 >= a0 __m128 b = Reg::shuffle<Y0, Y1, X0, X1>(y, x); // b3 <= b2 <= b1 <= b0 // merge l = _mm_min_ps(a, b); // ↓a3b3 ↓a2b2 ↓a1b1 ↓a0b0 h = _mm_max_ps(a, b); // ↑a3b3 ↑a2b2 ↑a1b1 ↑a0b0 a = _mm_unpacklo_ps(l, h); // ↑a1b1 ↓a1b1 ↑a0b0 ↓a0b0 b = _mm_unpackhi_ps(l, h); // ↑a3b3 ↓a3b3 ↑a2b2 ↓a2b2 l = _mm_min_ps(a, b); // ↓(↑a1b1,↑a3b3) ↓a1b3 ↓(↑a0b0,↑a2b2) ↓a0b2 h = _mm_max_ps(a, b); // ↑a3b1 ↑(↓a1b1,↓a3b3) ↑a2b0 ↑(↓a0b0,↓a2b2) a = _mm_unpacklo_ps(l, h); // ↑a2b0 ↓(↑a0b0,↑a2b2) ↑(↓a0b0,↓a2b2) ↓a0b2 b = _mm_unpackhi_ps(l, h); // ↑a3b1 ↓(↑a1b1,↑a3b3) ↑(↓a1b1,↓a3b3) ↓a1b3 l = _mm_min_ps(a, b); // ↓(↑a2b0,↑a3b1) ↓(↑a0b0,↑a2b2,↑a1b1,↑a3b3) ↓(↑(↓a0b0,↓a2b2),↑(↓a1b1,↓a3b3)) ↓a0b3 h = _mm_max_ps(a, b); // ↑a3b0 ↑(↓(↑a0b0,↑a2b2),↓(↑a1b1,↑a3b3)) ↑(↓a0b0,↓a2b2,↓a1b1,↓a3b3) ↑(↓a0b2,↓a1b3) return AVX::concat(_mm_unpacklo_ps(l, h), _mm_unpackhi_ps(l, h)); } #if 0 template<> void SortHelper<double>::sort(__m256d &Vc_RESTRICT x, __m256d &Vc_RESTRICT y) { __m256d l = _mm256_min_pd(x, y); // ↓x3y3 ↓x2y2 ↓x1y1 ↓x0y0 __m256d h = _mm256_max_pd(x, y); // ↑x3y3 ↑x2y2 ↑x1y1 ↑x0y0 x = _mm256_unpacklo_pd(l, h); // ↑x2y2 ↓x2y2 ↑x0y0 ↓x0y0 y = _mm256_unpackhi_pd(l, h); // ↑x3y3 ↓x3y3 ↑x1y1 ↓x1y1 l = _mm256_min_pd(x, y); // ↓(↑x2y2,↑x3y3) ↓x3x2y3y2 ↓(↑x0y0,↑x1y1) ↓x1x0y1y0 h = _mm256_max_pd(x, y); // ↑x3x2y3y2 ↑(↓x2y2,↓x3y3) ↑x1x0y1y0 ↑(↓x0y0,↓x1y1) x = _mm256_unpacklo_pd(l, h); // ↑(↓x2y2,↓x3y3) ↓x3x2y3y2 ↑(↓x0y0,↓x1y1) ↓x1x0y1y0 y = _mm256_unpackhi_pd(h, l); // ↓(↑x2y2,↑x3y3) ↑x3x2y3y2 ↓(↑x0y0,↑x1y1) ↑x1x0y1y0 l = _mm256_min_pd(x, y); // ↓(↑(↓x2y2,↓x3y3) ↓(↑x2y2,↑x3y3)) ↓x3x2y3y2 ↓(↑(↓x0y0,↓x1y1) ↓(↑x0y0,↑x1y1)) ↓x1x0y1y0 h = _mm256_max_pd(x, y); // ↑(↑(↓x2y2,↓x3y3) ↓(↑x2y2,↑x3y3)) ↑x3x2y3y2 ↑(↑(↓x0y0,↓x1y1) ↓(↑x0y0,↑x1y1)) ↑x1x0y1y0 __m256d a = Reg::permute<X2, X3, X1, X0>(Reg::permute128<X0, X1>(h, h)); // h0 h1 h3 h2 __m256d b = Reg::permute<X2, X3, X1, X0>(l); // l2 l3 l1 l0 // a3 >= a2 >= b1 >= b0 // b3 <= b2 <= a1 <= a0 // merge l = _mm256_min_pd(a, b); // ↓a3b3 ↓a2b2 ↓a1b1 ↓a0b0 h = _mm256_min_pd(a, b); // ↑a3b3 ↑a2b2 ↑a1b1 ↑a0b0 x = _mm256_unpacklo_pd(l, h); // ↑a2b2 ↓a2b2 ↑a0b0 ↓a0b0 y = _mm256_unpackhi_pd(l, h); // ↑a3b3 ↓a3b3 ↑a1b1 ↓a1b1 l = _mm256_min_pd(x, y); // ↓(↑a2b2,↑a3b3) ↓a2b3 ↓(↑a0b0,↑a1b1) ↓a1b0 h = _mm256_min_pd(x, y); // ↑a3b2 ↑(↓a2b2,↓a3b3) ↑a0b1 ↑(↓a0b0,↓a1b1) x = Reg::permute128<Y0, X0>(l, h); // ↑a0b1 ↑(↓a0b0,↓a1b1) ↓(↑a0b0,↑a1b1) ↓a1b0 y = Reg::permute128<Y1, X1>(l, h); // ↑a3b2 ↑(↓a2b2,↓a3b3) ↓(↑a2b2,↑a3b3) ↓a2b3 l = _mm256_min_pd(x, y); // ↓(↑a0b1,↑a3b2) ↓(↑(↓a0b0,↓a1b1) ↑(↓a2b2,↓a3b3)) ↓(↑a0b0,↑a1b1,↑a2b2,↑a3b3) ↓b0b3 h = _mm256_min_pd(x, y); // ↑a0a3 ↑(↓a0b0,↓a1b1,↓a2b2,↓a3b3) ↑(↓(↑a0b0,↑a1b1) ↓(↑a2b2,↑a3b3)) ↑(↓a1b0,↓a2b3) x = _mm256_unpacklo_pd(l, h); // h2 l2 h0 l0 y = _mm256_unpackhi_pd(l, h); // h3 l3 h1 l1 } #endif template <> Vc_CONST AVX2::double_v sorted<CurrentImplementation::current()>(AVX2::double_v x_) { __m256d dcba = x_.data(); /* * to find the second largest number find * max(min(max(ab),max(cd)), min(max(ad),max(bc))) * or * max(max(min(ab),min(cd)), min(max(ab),max(cd))) * const __m256d adcb = avx_cast<__m256d>(AVX::concat(_mm_alignr_epi8(avx_cast<__m128i>(dc), avx_cast<__m128i>(ba), 8), _mm_alignr_epi8(avx_cast<__m128i>(ba), avx_cast<__m128i>(dc), 8))); const __m256d l = _mm256_min_pd(dcba, adcb); // min(ad cd bc ab) const __m256d h = _mm256_max_pd(dcba, adcb); // max(ad cd bc ab) // max(h3, h1) // max(min(h0,h2), min(h3,h1)) // min(max(l0,l2), max(l3,l1)) // min(l3, l1) const __m256d ll = _mm256_min_pd(h, Reg::permute128<X0, X1>(h, h)); // min(h3h1 h2h0 h1h3 h0h2) //const __m256d hh = _mm256_max_pd(h3 ll1_3 l1 l0, h1 ll0_2 l3 l2); const __m256d hh = _mm256_max_pd( Reg::permute128<X1, Y0>(_mm256_unpackhi_pd(ll, h), l), Reg::permute128<X0, Y1>(_mm256_blend_pd(h ll, 0x1), l)); _mm256_min_pd(hh0, hh1 */ ////////////////////////////////////////////////////////////////////////////////// // max(max(ac), max(bd)) // max(max(min(ac),min(bd)), min(max(ac),max(bd))) // min(max(min(ac),min(bd)), min(max(ac),max(bd))) // min(min(ac), min(bd)) __m128d l = _mm_min_pd(AVX::lo128(dcba), AVX::hi128(dcba)); // min(bd) min(ac) __m128d h = _mm_max_pd(AVX::lo128(dcba), AVX::hi128(dcba)); // max(bd) max(ac) __m128d h0_l0 = _mm_unpacklo_pd(l, h); __m128d h1_l1 = _mm_unpackhi_pd(l, h); l = _mm_min_pd(h0_l0, h1_l1); h = _mm_max_pd(h0_l0, h1_l1); return AVX::concat( _mm_min_pd(l, Reg::permute<X0, X0>(h)), _mm_max_pd(h, Reg::permute<X1, X1>(l)) ); // extract: 1 cycle // min/max: 4 cycles // unpacklo/hi: 2 cycles // min/max: 4 cycles // permute: 1 cycle // min/max: 4 cycles // insert: 1 cycle // ---------------------- // total: 17 cycles /* __m256d cdab = Reg::permute<X2, X3, X0, X1>(dcba); __m256d l = _mm256_min_pd(dcba, cdab); __m256d h = _mm256_max_pd(dcba, cdab); __m256d maxmin_ba = Reg::permute128<X0, Y0>(l, h); __m256d maxmin_dc = Reg::permute128<X1, Y1>(l, h); l = _mm256_min_pd(maxmin_ba, maxmin_dc); h = _mm256_max_pd(maxmin_ba, maxmin_dc); return _mm256_blend_pd(h, l, 0x55); */ /* // a b c d // b a d c // sort pairs __m256d y, l, h; __m128d l2, h2; y = shuffle<X1, Y0, X3, Y2>(x, x); l = _mm256_min_pd(x, y); // min[ab ab cd cd] h = _mm256_max_pd(x, y); // max[ab ab cd cd] // 1 of 2 is at [0] // 1 of 4 is at [1] // 1 of 4 is at [2] // 1 of 2 is at [3] // don't be fooled by unpack here. It works differently for AVX pd than for SSE ps x = _mm256_unpacklo_pd(l, h); // l_ab h_ab l_cd h_cd l2 = _mm_min_pd(AVX::lo128(x), AVX::hi128(x)); // l_abcd l(h_ab hcd) h2 = _mm_max_pd(AVX::lo128(x), AVX::hi128(x)); // h(l_ab l_cd) h_abcd // either it is: return AVX::concat(l2, h2); // or: // AVX::concat(_mm_unpacklo_pd(l2, h2), _mm_unpackhi_pd(l2, h2)); // I'd like to have four useful compares const __m128d dc = AVX::hi128(dcba); const __m128d ba = AVX::lo128(dcba); const __m256d adcb = avx_cast<__m256d>(AVX::concat(_mm_alignr_epi8(avx_cast<__m128i>(dc), avx_cast<__m128i>(ba), 8), _mm_alignr_epi8(avx_cast<__m128i>(ba), avx_cast<__m128i>(dc), 8))); const int extraCmp = _mm_movemask_pd(_mm_cmpgt_pd(dc, ba)); // 0x0: d <= b && c <= a // 0x1: d <= b && c > a // 0x2: d > b && c <= a // 0x3: d > b && c > a switch (_mm256_movemask_pd(_mm256_cmpgt_pd(dcba, adcb))) { // impossible: 0x0, 0xf case 0x1: // a <= b && b <= c && c <= d && d > a // abcd return Reg::permute<X2, X3, X0, X1>(Reg::permute<X0, X1>(dcba, dcba)); case 0x2: // a <= b && b <= c && c > d && d <= a // dabc return Reg::permute<X2, X3, X0, X1>(adcb); case 0x3: // a <= b && b <= c && c > d && d > a // a[bd]c if (extraCmp & 2) { // abdc return Reg::permute<X2, X3, X1, X0>(Reg::permute<X0, X1>(dcba, dcba)); } else { // adbc return Reg::permute<X3, X2, X0, X1>(adcb); } case 0x4: // a <= b && b > c && c <= d && d <= a // cdab; return Reg::permute<X2, X3, X0, X1>(dcba); case 0x5: // a <= b && b > c && c <= d && d > a // [ac] < [bd] switch (extraCmp) { case 0x0: // d <= b && c <= a // cadb return shuffle<>(dcba, bcda); case 0x1: // d <= b && c > a case 0x2: // d > b && c <= a case 0x3: // d > b && c > a } case 0x6: // a <= b && b > c && c > d && d <= a // d[ac]b case 0x7: // a <= b && b > c && c > d && d > a // adcb; return permute<X1, X0, X3, X2>(permute128<X1, X0>(bcda, bcda)); case 0x8: // a > b && b <= c && c <= d && d <= a return bcda; case 0x9: // a > b && b <= c && c <= d && d > a // b[ac]d; case 0xa: // a > b && b <= c && c > d && d <= a // [ac] > [bd] case 0xb: // a > b && b <= c && c > d && d > a // badc; return permute128<X1, X0>(dcba); case 0xc: // a > b && b > c && c <= d && d <= a // c[bd]a; case 0xd: // a > b && b > c && c <= d && d > a // cbad; return permute<X1, X0, X3, X2>(bcda); case 0xe: // a > b && b > c && c > d && d <= a return dcba; } */ } } // namespace Detail } // namespace Vc // vim: foldmethod=marker
chr-engwer/Vc
src/avx_sorthelper.cpp
C++
bsd-3-clause
25,912
 /// <reference path="../lib/types.d.ts" /> import utils = require('../lib/utils'); import file = require('../lib/FileUtil'); import childProcess = require("child_process"); export function buildRunEmulate(callback: (code: number) => void) { exec(egret.args.command, [egret.args.platform], callback); } function exec(command: string, params: string[], callback: Function) { var cdvProcess = childProcess.exec(`cordova ${command} ${params.join(' ')}`, {}, (e, stdout, stdin) => { console.log(e) }); cdvProcess.stdout.on("data", data=> console.log("/"+data)); cdvProcess.stderr.on("data", data=> console.log("/"+data)); cdvProcess.on("close", code=> callback(code)); cdvProcess.on("error", (ee) => console.log("error when build", ee)); }
Lanfei/egret-core
tools/actions/Cordova.ts
TypeScript
bsd-3-clause
767
<?php class ObjectPath { static protected $type = array(0=>'main'); static function getType() { return self::$type; } } print_r(ObjectPath::getType()); $object_type = array_pop((ObjectPath::getType())); print_r(ObjectPath::getType()); ?>
JSchwehn/php
testdata/fuzzdir/corpus/Zend_tests_bug35393.php
PHP
bsd-3-clause
263
<?php Yii::import('application.modules.store.models.StoreCategory'); /** * Class CategoryWidget * * <pre> * <?php * $this->widget('application.modules.store.widgets.CategoryWidget'); * ?> * </pre> */ class CategoryWidget extends yupe\widgets\YWidget { public $parent = 0; public $depth = 1; public $view = 'category-widget'; public $htmlOptions = []; public function run() { $this->render($this->view, [ 'tree' => (new StoreCategory())->getMenuList($this->depth, $this->parent), 'htmlOptions' => $this->htmlOptions ]); } }
RonLab1987/43berega
protected/modules/store/widgets/CategoryWidget.php
PHP
bsd-3-clause
609
/* * Portions of this file Copyright 1999-2005 University of Chicago * Portions of this file Copyright 1999-2005 The University of Southern California. * * This file or a portion of this file is licensed under the * terms of the Globus Toolkit Public License, found at * http://www.globus.org/toolkit/download/license.html. * If you redistribute this file, with or without * modifications, you must include this notice in the file. */ package org.globus.util.tests; import org.globus.util.GlobusURL; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; public class GlobusURLTest extends TestCase { public GlobusURLTest(String name) { super(name); } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); } public static Test suite() { return new TestSuite(GlobusURLTest.class); } public void testParse() { GlobusURL url = null; try { url = new GlobusURL("file://host1"); } catch(Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "file", "host1", -1, null, null, null); try { url = new GlobusURL("http:///file1"); } catch(Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "http", "", 80, "file1", null, null); try { url = new GlobusURL("http://host1:124"); } catch(Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "http", "host1", 124, null, null, null); try { url = new GlobusURL("http://host1:124/"); } catch(Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "http", "host1", 124, null, null, null); try { url = new GlobusURL("http://host1/mis/ptys"); } catch(Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "http", "host1", 80, "mis/ptys", null, null); try { url = new GlobusURL("http://usr@host1"); } catch(Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "http", "host1", 80, null, "usr", null); try { url = new GlobusURL("http://usr:@host1:124"); } catch(Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "http", "host1", 124, null, "usr", ""); try { url = new GlobusURL("http://usr:pwd@host1:124//mis"); } catch(Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "http", "host1", 124, "/mis", "usr", "pwd"); try { url = new GlobusURL(" gsiftp://localhost/foo"); } catch(Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "gsiftp", "localhost", 2811, "foo", null, null); } private void checkUrl(GlobusURL url, String protocol, String host, int port, String urlPath, String user, String pwd) { assertEquals("protocol", protocol, url.getProtocol()); assertEquals("host", host, url.getHost()); assertEquals("port", port, url.getPort()); assertEquals("urlpath", urlPath, url.getPath()); assertEquals("user", user, url.getUser()); assertEquals("pwd", pwd, url.getPwd()); } public void testParseBad() { try { new GlobusURL("http:/host1"); fail("The url was parsed ok!"); } catch(Exception e) { } } public void testEquals1() { GlobusURL url, url2, url3; url = url2 = url3 = null; try { url = new GlobusURL("http://host1:123/jarek"); url2 = new GlobusURL("http://host1:123/jarek"); url3 = new GlobusURL("ftp://host1:123/jarek"); } catch(Exception e) { } assertTrue("c1", url.equals("HTTP://host1:123/jarek")); assertTrue("c2", !url.equals("HTTP://host1:123/Jarek")); assertTrue("c3", url.equals(url)); assertTrue("c4", url.equals(url2)); assertTrue("c5", !url.equals(url3)); } public void testIPv6Address() { GlobusURL url = null; try { url = new GlobusURL( "http://[1080:0:0:0:8:800:200C:417A]/index.html" ); } catch(Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "http", "[1080:0:0:0:8:800:200C:417A]", 80, "index.html", null, null); try { url = new GlobusURL( "hdl://[3ffe:2a00:100:7031::1]:123" ); } catch(Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "hdl", "[3ffe:2a00:100:7031::1]", 123, null, null, null); try { url = new GlobusURL( "p1://gawor:123@[3ffe:2a00:100:7031::1]:123/testFile" ); } catch(Exception e) { fail("Parse failed: " + e.getMessage()); } checkUrl(url, "p1", "[3ffe:2a00:100:7031::1]", 123, "testFile", "gawor", "123"); } }
NCIP/cagrid2-wsrf
wsrf-jglobus/src/test/java/org/globus/util/tests/GlobusURLTest.java
Java
bsd-3-clause
4,887
import os import cStringIO as StringIO git_binary = "git" verbose_mode = False try: from subprocess import Popen, PIPE def run_cmd(cmd): p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) return p.stdin, p.stdout, p.stderr except ImportError: def run_cmd(cmd): return os.popen3(self._cmd) class GitData (object): def __init__(self, location, command_string): self._cmd = "%s %s" % (git_binary, command_string) self._location = location self._data = None def open(self): if verbose_mode: print " >> %s" % (self._cmd) cwd = os.getcwd() os.chdir(self._location) self._in, self._data, self._err = run_cmd(self._cmd) self._read = 0 os.chdir(cwd) def tell(self): return self._read def read(self, l=-1): if self._data is None: self.open() data = self._data.read(l) self._read += len(data) return data def write(self, data): if self._data is None: self.open() self._in.write(data) def flush(self): if self._data is not None: self._in.flush() def close_stdin(self): if self._data is not None: self._in.close() def close(self): if self._data is not None: self._in.close() self._data.close() self._err.close() self._data = None def reopen(self): self.close() self.open() class FakeData (object): def __init__(self, data): self._data = data self._string = None def open(self): self._string = StringIO.StringIO(self._data) def read(self, l=-1): if self._string is None: self.open() return self._string.read(l) def close(self): if self._string is not None: self._string.close() self._string = None def reopen(self): self.close() self.open()
slonopotamus/git_svn_server
GitSvnServer/vcs/git/data.py
Python
bsd-3-clause
2,086
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.opengl; import javax.annotation.*; import java.nio.*; import org.lwjgl.system.*; import static org.lwjgl.system.Checks.*; import static org.lwjgl.system.JNI.*; import static org.lwjgl.system.MemoryStack.*; import static org.lwjgl.system.MemoryUtil.*; /** * Native bindings to the <a target="_blank" href="https://www.khronos.org/registry/OpenGL/extensions/AMD/AMD_performance_monitor.txt">AMD_performance_monitor</a> extension. * * <p>This extension enables the capture and reporting of performance monitors. Performance monitors contain groups of counters which hold arbitrary counted * data. Typically, the counters hold information on performance-related counters in the underlying hardware. The extension is general enough to allow the * implementation to choose which counters to expose and pick the data type and range of the counters. The extension also allows counting to start and end * on arbitrary boundaries during rendering.</p> */ public class AMDPerformanceMonitor { static { GL.initialize(); } /** Accepted by the {@code pame} parameter of GetPerfMonitorCounterInfoAMD. */ public static final int GL_COUNTER_TYPE_AMD = 0x8BC0, GL_COUNTER_RANGE_AMD = 0x8BC1; /** Returned as a valid value in {@code data} parameter of GetPerfMonitorCounterInfoAMD if {@code pname} = COUNTER_TYPE_AMD. */ public static final int GL_UNSIGNED_INT64_AMD = 0x8BC2, GL_PERCENTAGE_AMD = 0x8BC3; /** Accepted by the {@code pname} parameter of GetPerfMonitorCounterDataAMD. */ public static final int GL_PERFMON_RESULT_AVAILABLE_AMD = 0x8BC4, GL_PERFMON_RESULT_SIZE_AMD = 0x8BC5, GL_PERFMON_RESULT_AMD = 0x8BC6; protected AMDPerformanceMonitor() { throw new UnsupportedOperationException(); } // --- [ glGetPerfMonitorGroupsAMD ] --- public static native void nglGetPerfMonitorGroupsAMD(long numGroups, int groupsSize, long groups); public static void glGetPerfMonitorGroupsAMD(@Nullable @NativeType("GLint *") IntBuffer numGroups, @Nullable @NativeType("GLuint *") IntBuffer groups) { if (CHECKS) { checkSafe(numGroups, 1); } nglGetPerfMonitorGroupsAMD(memAddressSafe(numGroups), remainingSafe(groups), memAddressSafe(groups)); } // --- [ glGetPerfMonitorCountersAMD ] --- public static native void nglGetPerfMonitorCountersAMD(int group, long numCounters, long maxActiveCounters, int counterSize, long counters); public static void glGetPerfMonitorCountersAMD(@NativeType("GLuint") int group, @NativeType("GLint *") IntBuffer numCounters, @NativeType("GLint *") IntBuffer maxActiveCounters, @NativeType("GLuint *") IntBuffer counters) { if (CHECKS) { check(numCounters, 1); check(maxActiveCounters, 1); } nglGetPerfMonitorCountersAMD(group, memAddress(numCounters), memAddress(maxActiveCounters), counters.remaining(), memAddress(counters)); } // --- [ glGetPerfMonitorGroupStringAMD ] --- public static native void nglGetPerfMonitorGroupStringAMD(int group, int bufSize, long length, long groupString); public static void glGetPerfMonitorGroupStringAMD(@NativeType("GLuint") int group, @NativeType("GLsizei *") IntBuffer length, @NativeType("GLchar *") ByteBuffer groupString) { if (CHECKS) { check(length, 1); } nglGetPerfMonitorGroupStringAMD(group, groupString.remaining(), memAddress(length), memAddress(groupString)); } // --- [ glGetPerfMonitorCounterStringAMD ] --- public static native void nglGetPerfMonitorCounterStringAMD(int group, int counter, int bufSize, long length, long counterString); public static void glGetPerfMonitorCounterStringAMD(@NativeType("GLuint") int group, @NativeType("GLuint") int counter, @Nullable @NativeType("GLsizei *") IntBuffer length, @Nullable @NativeType("GLchar *") ByteBuffer counterString) { if (CHECKS) { checkSafe(length, 1); } nglGetPerfMonitorCounterStringAMD(group, counter, remainingSafe(counterString), memAddressSafe(length), memAddressSafe(counterString)); } // --- [ glGetPerfMonitorCounterInfoAMD ] --- public static native void nglGetPerfMonitorCounterInfoAMD(int group, int counter, int pname, long data); public static void glGetPerfMonitorCounterInfoAMD(@NativeType("GLuint") int group, @NativeType("GLuint") int counter, @NativeType("GLenum") int pname, @NativeType("void *") ByteBuffer data) { if (CHECKS) { check(data, 4); } nglGetPerfMonitorCounterInfoAMD(group, counter, pname, memAddress(data)); } public static void glGetPerfMonitorCounterInfoAMD(@NativeType("GLuint") int group, @NativeType("GLuint") int counter, @NativeType("GLenum") int pname, @NativeType("void *") IntBuffer data) { if (CHECKS) { check(data, 4 >> 2); } nglGetPerfMonitorCounterInfoAMD(group, counter, pname, memAddress(data)); } public static void glGetPerfMonitorCounterInfoAMD(@NativeType("GLuint") int group, @NativeType("GLuint") int counter, @NativeType("GLenum") int pname, @NativeType("void *") FloatBuffer data) { if (CHECKS) { check(data, 4 >> 2); } nglGetPerfMonitorCounterInfoAMD(group, counter, pname, memAddress(data)); } // --- [ glGenPerfMonitorsAMD ] --- public static native void nglGenPerfMonitorsAMD(int n, long monitors); public static void glGenPerfMonitorsAMD(@NativeType("GLuint *") IntBuffer monitors) { nglGenPerfMonitorsAMD(monitors.remaining(), memAddress(monitors)); } @NativeType("void") public static int glGenPerfMonitorsAMD() { MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { IntBuffer monitors = stack.callocInt(1); nglGenPerfMonitorsAMD(1, memAddress(monitors)); return monitors.get(0); } finally { stack.setPointer(stackPointer); } } // --- [ glDeletePerfMonitorsAMD ] --- public static native void nglDeletePerfMonitorsAMD(int n, long monitors); public static void glDeletePerfMonitorsAMD(@NativeType("GLuint *") IntBuffer monitors) { nglDeletePerfMonitorsAMD(monitors.remaining(), memAddress(monitors)); } public static void glDeletePerfMonitorsAMD(@NativeType("GLuint *") int monitor) { MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { IntBuffer monitors = stack.ints(monitor); nglDeletePerfMonitorsAMD(1, memAddress(monitors)); } finally { stack.setPointer(stackPointer); } } // --- [ glSelectPerfMonitorCountersAMD ] --- public static native void nglSelectPerfMonitorCountersAMD(int monitor, boolean enable, int group, int numCounters, long counterList); public static void glSelectPerfMonitorCountersAMD(@NativeType("GLuint") int monitor, @NativeType("GLboolean") boolean enable, @NativeType("GLuint") int group, @NativeType("GLuint *") IntBuffer counterList) { nglSelectPerfMonitorCountersAMD(monitor, enable, group, counterList.remaining(), memAddress(counterList)); } // --- [ glBeginPerfMonitorAMD ] --- public static native void glBeginPerfMonitorAMD(@NativeType("GLuint") int monitor); // --- [ glEndPerfMonitorAMD ] --- public static native void glEndPerfMonitorAMD(@NativeType("GLuint") int monitor); // --- [ glGetPerfMonitorCounterDataAMD ] --- public static native void nglGetPerfMonitorCounterDataAMD(int monitor, int pname, int dataSize, long data, long bytesWritten); public static void glGetPerfMonitorCounterDataAMD(@NativeType("GLuint") int monitor, @NativeType("GLenum") int pname, @NativeType("GLuint *") IntBuffer data, @Nullable @NativeType("GLint *") IntBuffer bytesWritten) { if (CHECKS) { checkSafe(bytesWritten, 1); } nglGetPerfMonitorCounterDataAMD(monitor, pname, data.remaining(), memAddress(data), memAddressSafe(bytesWritten)); } /** Array version of: {@link #glGetPerfMonitorGroupsAMD GetPerfMonitorGroupsAMD} */ public static void glGetPerfMonitorGroupsAMD(@Nullable @NativeType("GLint *") int[] numGroups, @Nullable @NativeType("GLuint *") int[] groups) { long __functionAddress = GL.getICD().glGetPerfMonitorGroupsAMD; if (CHECKS) { check(__functionAddress); checkSafe(numGroups, 1); } callPPV(numGroups, lengthSafe(groups), groups, __functionAddress); } /** Array version of: {@link #glGetPerfMonitorCountersAMD GetPerfMonitorCountersAMD} */ public static void glGetPerfMonitorCountersAMD(@NativeType("GLuint") int group, @NativeType("GLint *") int[] numCounters, @NativeType("GLint *") int[] maxActiveCounters, @NativeType("GLuint *") int[] counters) { long __functionAddress = GL.getICD().glGetPerfMonitorCountersAMD; if (CHECKS) { check(__functionAddress); check(numCounters, 1); check(maxActiveCounters, 1); } callPPPV(group, numCounters, maxActiveCounters, counters.length, counters, __functionAddress); } /** Array version of: {@link #glGetPerfMonitorGroupStringAMD GetPerfMonitorGroupStringAMD} */ public static void glGetPerfMonitorGroupStringAMD(@NativeType("GLuint") int group, @NativeType("GLsizei *") int[] length, @NativeType("GLchar *") ByteBuffer groupString) { long __functionAddress = GL.getICD().glGetPerfMonitorGroupStringAMD; if (CHECKS) { check(__functionAddress); check(length, 1); } callPPV(group, groupString.remaining(), length, memAddress(groupString), __functionAddress); } /** Array version of: {@link #glGetPerfMonitorCounterStringAMD GetPerfMonitorCounterStringAMD} */ public static void glGetPerfMonitorCounterStringAMD(@NativeType("GLuint") int group, @NativeType("GLuint") int counter, @Nullable @NativeType("GLsizei *") int[] length, @Nullable @NativeType("GLchar *") ByteBuffer counterString) { long __functionAddress = GL.getICD().glGetPerfMonitorCounterStringAMD; if (CHECKS) { check(__functionAddress); checkSafe(length, 1); } callPPV(group, counter, remainingSafe(counterString), length, memAddressSafe(counterString), __functionAddress); } /** Array version of: {@link #glGetPerfMonitorCounterInfoAMD GetPerfMonitorCounterInfoAMD} */ public static void glGetPerfMonitorCounterInfoAMD(@NativeType("GLuint") int group, @NativeType("GLuint") int counter, @NativeType("GLenum") int pname, @NativeType("void *") int[] data) { long __functionAddress = GL.getICD().glGetPerfMonitorCounterInfoAMD; if (CHECKS) { check(__functionAddress); check(data, 4 >> 2); } callPV(group, counter, pname, data, __functionAddress); } /** Array version of: {@link #glGetPerfMonitorCounterInfoAMD GetPerfMonitorCounterInfoAMD} */ public static void glGetPerfMonitorCounterInfoAMD(@NativeType("GLuint") int group, @NativeType("GLuint") int counter, @NativeType("GLenum") int pname, @NativeType("void *") float[] data) { long __functionAddress = GL.getICD().glGetPerfMonitorCounterInfoAMD; if (CHECKS) { check(__functionAddress); check(data, 4 >> 2); } callPV(group, counter, pname, data, __functionAddress); } /** Array version of: {@link #glGenPerfMonitorsAMD GenPerfMonitorsAMD} */ public static void glGenPerfMonitorsAMD(@NativeType("GLuint *") int[] monitors) { long __functionAddress = GL.getICD().glGenPerfMonitorsAMD; if (CHECKS) { check(__functionAddress); } callPV(monitors.length, monitors, __functionAddress); } /** Array version of: {@link #glDeletePerfMonitorsAMD DeletePerfMonitorsAMD} */ public static void glDeletePerfMonitorsAMD(@NativeType("GLuint *") int[] monitors) { long __functionAddress = GL.getICD().glDeletePerfMonitorsAMD; if (CHECKS) { check(__functionAddress); } callPV(monitors.length, monitors, __functionAddress); } /** Array version of: {@link #glSelectPerfMonitorCountersAMD SelectPerfMonitorCountersAMD} */ public static void glSelectPerfMonitorCountersAMD(@NativeType("GLuint") int monitor, @NativeType("GLboolean") boolean enable, @NativeType("GLuint") int group, @NativeType("GLuint *") int[] counterList) { long __functionAddress = GL.getICD().glSelectPerfMonitorCountersAMD; if (CHECKS) { check(__functionAddress); } callPV(monitor, enable, group, counterList.length, counterList, __functionAddress); } /** Array version of: {@link #glGetPerfMonitorCounterDataAMD GetPerfMonitorCounterDataAMD} */ public static void glGetPerfMonitorCounterDataAMD(@NativeType("GLuint") int monitor, @NativeType("GLenum") int pname, @NativeType("GLuint *") int[] data, @Nullable @NativeType("GLint *") int[] bytesWritten) { long __functionAddress = GL.getICD().glGetPerfMonitorCounterDataAMD; if (CHECKS) { check(__functionAddress); checkSafe(bytesWritten, 1); } callPPV(monitor, pname, data.length, data, bytesWritten, __functionAddress); } }
LWJGL-CI/lwjgl3
modules/lwjgl/opengl/src/generated/java/org/lwjgl/opengl/AMDPerformanceMonitor.java
Java
bsd-3-clause
13,606
<?php /** * @see https://github.com/zendframework/zend-uri for the canonical source repository * @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (https://www.zend.com) * @license https://github.com/zendframework/zend-uri/blob/master/LICENSE.md New BSD License */ namespace Zend\Uri; /** * URI Factory Class * * The URI factory can be used to generate URI objects from strings, using a * different URI subclass depending on the input URI scheme. New scheme-specific * classes can be registered using the registerScheme() method. * * Note that this class contains only static methods and should not be * instantiated */ abstract class UriFactory { /** * Registered scheme-specific classes * * @var array */ protected static $schemeClasses = [ 'http' => 'Zend\Uri\Http', 'https' => 'Zend\Uri\Http', 'mailto' => 'Zend\Uri\Mailto', 'file' => 'Zend\Uri\File', 'urn' => 'Zend\Uri\Uri', 'tag' => 'Zend\Uri\Uri', ]; /** * Register a scheme-specific class to be used * * @param string $scheme * @param string $class */ public static function registerScheme($scheme, $class) { $scheme = strtolower($scheme); static::$schemeClasses[$scheme] = $class; } /** * Unregister a scheme * * @param string $scheme */ public static function unregisterScheme($scheme) { $scheme = strtolower($scheme); if (isset(static::$schemeClasses[$scheme])) { unset(static::$schemeClasses[$scheme]); } } /** * Get the class name for a registered scheme * * If provided scheme is not registered, will return NULL * * @param string $scheme * @return string|null */ public static function getRegisteredSchemeClass($scheme) { if (isset(static::$schemeClasses[$scheme])) { return static::$schemeClasses[$scheme]; } return; } /** * Create a URI from a string * * @param string $uriString * @param string $defaultScheme * @throws Exception\InvalidArgumentException * @return \Zend\Uri\Uri */ public static function factory($uriString, $defaultScheme = null) { if (! is_string($uriString)) { throw new Exception\InvalidArgumentException(sprintf( 'Expecting a string, received "%s"', (is_object($uriString) ? get_class($uriString) : gettype($uriString)) )); } $uri = new Uri($uriString); $scheme = strtolower($uri->getScheme()); if (! $scheme && $defaultScheme) { $scheme = $defaultScheme; } if ($scheme && ! isset(static::$schemeClasses[$scheme])) { throw new Exception\InvalidArgumentException(sprintf( 'no class registered for scheme "%s"', $scheme )); } if ($scheme && isset(static::$schemeClasses[$scheme])) { $class = static::$schemeClasses[$scheme]; $uri = new $class($uri); if (! $uri instanceof UriInterface) { throw new Exception\InvalidArgumentException( sprintf( 'class "%s" registered for scheme "%s" does not implement Zend\Uri\UriInterface', $class, $scheme ) ); } } return $uri; } }
rongeb/anit_cms_for_zf3
vendor/zendframework/zend-uri/src/UriFactory.php
PHP
bsd-3-clause
3,567
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/background_sync/background_sync_manager.h" #include "base/barrier_closure.h" #include "base/bind.h" #include "base/location.h" #include "base/single_thread_task_runner.h" #include "base/thread_task_runner_handle.h" #include "content/browser/background_sync/background_sync_metrics.h" #include "content/browser/background_sync/background_sync_network_observer.h" #include "content/browser/background_sync/background_sync_power_observer.h" #include "content/browser/background_sync/background_sync_registration_handle.h" #include "content/browser/background_sync/background_sync_registration_options.h" #include "content/browser/service_worker/service_worker_context_wrapper.h" #include "content/browser/service_worker/service_worker_storage.h" #include "content/public/browser/browser_thread.h" #if defined(OS_ANDROID) #include "content/browser/android/background_sync_launcher_android.h" #endif namespace content { class BackgroundSyncManager::RefCountedRegistration : public base::RefCounted<RefCountedRegistration> { public: BackgroundSyncRegistration* value() { return &registration_; } const BackgroundSyncRegistration* value() const { return &registration_; } private: friend class base::RefCounted<RefCountedRegistration>; ~RefCountedRegistration() = default; BackgroundSyncRegistration registration_; }; namespace { const char kBackgroundSyncUserDataKey[] = "BackgroundSyncUserData"; void PostErrorResponse( BackgroundSyncStatus status, const BackgroundSyncManager::StatusAndRegistrationCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind( callback, status, base::Passed(scoped_ptr<BackgroundSyncRegistrationHandle>().Pass()))); } } // namespace BackgroundSyncManager::BackgroundSyncRegistrations:: BackgroundSyncRegistrations() : next_id(BackgroundSyncRegistration::kInitialId) { } BackgroundSyncManager::BackgroundSyncRegistrations:: ~BackgroundSyncRegistrations() { } // static scoped_ptr<BackgroundSyncManager> BackgroundSyncManager::Create( const scoped_refptr<ServiceWorkerContextWrapper>& service_worker_context) { DCHECK_CURRENTLY_ON(BrowserThread::IO); BackgroundSyncManager* sync_manager = new BackgroundSyncManager(service_worker_context); sync_manager->Init(); return make_scoped_ptr(sync_manager); } BackgroundSyncManager::~BackgroundSyncManager() { DCHECK_CURRENTLY_ON(BrowserThread::IO); service_worker_context_->RemoveObserver(this); } BackgroundSyncManager::RegistrationKey::RegistrationKey( const BackgroundSyncRegistration& registration) : RegistrationKey(registration.options()->tag, registration.options()->periodicity) { } BackgroundSyncManager::RegistrationKey::RegistrationKey( const BackgroundSyncRegistrationOptions& options) : RegistrationKey(options.tag, options.periodicity) { } BackgroundSyncManager::RegistrationKey::RegistrationKey( const std::string& tag, SyncPeriodicity periodicity) : value_(periodicity == SYNC_ONE_SHOT ? "o_" + tag : "p_" + tag) { } void BackgroundSyncManager::Register( int64 sw_registration_id, const BackgroundSyncRegistrationOptions& options, bool requested_from_service_worker, const StatusAndRegistrationCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // For UMA, determine here whether the sync could fire immediately BackgroundSyncMetrics::RegistrationCouldFire registration_could_fire = AreOptionConditionsMet(options) ? BackgroundSyncMetrics::REGISTRATION_COULD_FIRE : BackgroundSyncMetrics::REGISTRATION_COULD_NOT_FIRE; if (disabled_) { BackgroundSyncMetrics::CountRegister( options.periodicity, registration_could_fire, BackgroundSyncMetrics::REGISTRATION_IS_NOT_DUPLICATE, BACKGROUND_SYNC_STATUS_STORAGE_ERROR); PostErrorResponse(BACKGROUND_SYNC_STATUS_STORAGE_ERROR, callback); return; } op_scheduler_.ScheduleOperation(base::Bind( &BackgroundSyncManager::RegisterImpl, weak_ptr_factory_.GetWeakPtr(), sw_registration_id, options, requested_from_service_worker, MakeStatusAndRegistrationCompletion(callback))); } void BackgroundSyncManager::GetRegistration( int64 sw_registration_id, const std::string& sync_registration_tag, SyncPeriodicity periodicity, const StatusAndRegistrationCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { PostErrorResponse(BACKGROUND_SYNC_STATUS_STORAGE_ERROR, callback); return; } RegistrationKey registration_key(sync_registration_tag, periodicity); op_scheduler_.ScheduleOperation(base::Bind( &BackgroundSyncManager::GetRegistrationImpl, weak_ptr_factory_.GetWeakPtr(), sw_registration_id, registration_key, MakeStatusAndRegistrationCompletion(callback))); } void BackgroundSyncManager::GetRegistrations( int64 sw_registration_id, SyncPeriodicity periodicity, const StatusAndRegistrationsCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind( callback, BACKGROUND_SYNC_STATUS_STORAGE_ERROR, base::Passed( scoped_ptr<ScopedVector<BackgroundSyncRegistrationHandle>>() .Pass()))); return; } op_scheduler_.ScheduleOperation( base::Bind(&BackgroundSyncManager::GetRegistrationsImpl, weak_ptr_factory_.GetWeakPtr(), sw_registration_id, periodicity, MakeStatusAndRegistrationsCompletion(callback))); } // Given a HandleId |handle_id|, return a new handle for the same // registration. scoped_ptr<BackgroundSyncRegistrationHandle> BackgroundSyncManager::DuplicateRegistrationHandle( BackgroundSyncRegistrationHandle::HandleId handle_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); scoped_refptr<RefCountedRegistration>* ref_registration = registration_handle_ids_.Lookup(handle_id); if (!ref_registration) return scoped_ptr<BackgroundSyncRegistrationHandle>(); return CreateRegistrationHandle(ref_registration->get()); } void BackgroundSyncManager::OnRegistrationDeleted(int64 registration_id, const GURL& pattern) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // Operations already in the queue will either fail when they write to storage // or return stale results based on registrations loaded in memory. This is // inconsequential since the service worker is gone. op_scheduler_.ScheduleOperation(base::Bind( &BackgroundSyncManager::OnRegistrationDeletedImpl, weak_ptr_factory_.GetWeakPtr(), registration_id, MakeEmptyCompletion())); } void BackgroundSyncManager::OnStorageWiped() { DCHECK_CURRENTLY_ON(BrowserThread::IO); // Operations already in the queue will either fail when they write to storage // or return stale results based on registrations loaded in memory. This is // inconsequential since the service workers are gone. op_scheduler_.ScheduleOperation( base::Bind(&BackgroundSyncManager::OnStorageWipedImpl, weak_ptr_factory_.GetWeakPtr(), MakeEmptyCompletion())); } BackgroundSyncManager::BackgroundSyncManager( const scoped_refptr<ServiceWorkerContextWrapper>& service_worker_context) : service_worker_context_(service_worker_context), disabled_(false), weak_ptr_factory_(this) { DCHECK_CURRENTLY_ON(BrowserThread::IO); service_worker_context_->AddObserver(this); network_observer_.reset(new BackgroundSyncNetworkObserver( base::Bind(&BackgroundSyncManager::OnNetworkChanged, weak_ptr_factory_.GetWeakPtr()))); power_observer_.reset(new BackgroundSyncPowerObserver(base::Bind( &BackgroundSyncManager::OnPowerChanged, weak_ptr_factory_.GetWeakPtr()))); } void BackgroundSyncManager::Init() { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(!op_scheduler_.ScheduledOperations()); DCHECK(!disabled_); op_scheduler_.ScheduleOperation(base::Bind(&BackgroundSyncManager::InitImpl, weak_ptr_factory_.GetWeakPtr(), MakeEmptyCompletion())); } void BackgroundSyncManager::InitImpl(const base::Closure& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback)); return; } GetDataFromBackend( kBackgroundSyncUserDataKey, base::Bind(&BackgroundSyncManager::InitDidGetDataFromBackend, weak_ptr_factory_.GetWeakPtr(), callback)); } void BackgroundSyncManager::InitDidGetDataFromBackend( const base::Closure& callback, const std::vector<std::pair<int64, std::string>>& user_data, ServiceWorkerStatusCode status) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (status != SERVICE_WORKER_OK && status != SERVICE_WORKER_ERROR_NOT_FOUND) { LOG(ERROR) << "BackgroundSync failed to init due to backend failure."; DisableAndClearManager(base::Bind(callback)); return; } bool corruption_detected = false; for (const std::pair<int64, std::string>& data : user_data) { BackgroundSyncRegistrationsProto registrations_proto; if (registrations_proto.ParseFromString(data.second)) { BackgroundSyncRegistrations* registrations = &active_registrations_[data.first]; registrations->next_id = registrations_proto.next_registration_id(); registrations->origin = GURL(registrations_proto.origin()); for (int i = 0, max = registrations_proto.registration_size(); i < max; ++i) { const BackgroundSyncRegistrationProto& registration_proto = registrations_proto.registration(i); if (registration_proto.id() >= registrations->next_id) { corruption_detected = true; break; } RegistrationKey registration_key(registration_proto.tag(), registration_proto.periodicity()); scoped_refptr<RefCountedRegistration> ref_registration( new RefCountedRegistration()); registrations->registration_map[registration_key] = ref_registration; BackgroundSyncRegistration* registration = ref_registration->value(); BackgroundSyncRegistrationOptions* options = registration->options(); options->tag = registration_proto.tag(); options->periodicity = registration_proto.periodicity(); options->min_period = registration_proto.min_period(); options->network_state = registration_proto.network_state(); options->power_state = registration_proto.power_state(); registration->set_id(registration_proto.id()); registration->set_sync_state(registration_proto.sync_state()); if (registration->sync_state() == SYNC_STATE_FIRING) { // If the browser (or worker) closed while firing the event, consider // it pending again> registration->set_sync_state(SYNC_STATE_PENDING); } } } if (corruption_detected) break; } if (corruption_detected) { LOG(ERROR) << "Corruption detected in background sync backend"; DisableAndClearManager(base::Bind(callback)); return; } FireReadyEvents(); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback)); } void BackgroundSyncManager::RegisterImpl( int64 sw_registration_id, const BackgroundSyncRegistrationOptions& options, bool requested_from_service_worker, const StatusAndRegistrationCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // For UMA, determine here whether the sync could fire immediately BackgroundSyncMetrics::RegistrationCouldFire registration_could_fire = AreOptionConditionsMet(options) ? BackgroundSyncMetrics::REGISTRATION_COULD_FIRE : BackgroundSyncMetrics::REGISTRATION_COULD_NOT_FIRE; if (disabled_) { BackgroundSyncMetrics::CountRegister( options.periodicity, registration_could_fire, BackgroundSyncMetrics::REGISTRATION_IS_NOT_DUPLICATE, BACKGROUND_SYNC_STATUS_STORAGE_ERROR); PostErrorResponse(BACKGROUND_SYNC_STATUS_STORAGE_ERROR, callback); return; } ServiceWorkerRegistration* sw_registration = service_worker_context_->GetLiveRegistration(sw_registration_id); if (!sw_registration || !sw_registration->active_version()) { BackgroundSyncMetrics::CountRegister( options.periodicity, registration_could_fire, BackgroundSyncMetrics::REGISTRATION_IS_NOT_DUPLICATE, BACKGROUND_SYNC_STATUS_NO_SERVICE_WORKER); PostErrorResponse(BACKGROUND_SYNC_STATUS_NO_SERVICE_WORKER, callback); return; } if (requested_from_service_worker && !sw_registration->active_version()->HasWindowClients()) { PostErrorResponse(BACKGROUND_SYNC_STATUS_NOT_ALLOWED, callback); return; } RefCountedRegistration* existing_registration_ref = LookupActiveRegistration(sw_registration_id, RegistrationKey(options)); if (existing_registration_ref && existing_registration_ref->value()->options()->Equals(options)) { BackgroundSyncRegistration* existing_registration = existing_registration_ref->value(); if (existing_registration->sync_state() == SYNC_STATE_FAILED) { existing_registration->set_sync_state(SYNC_STATE_PENDING); StoreRegistrations( sw_registration_id, base::Bind(&BackgroundSyncManager::RegisterDidStore, weak_ptr_factory_.GetWeakPtr(), sw_registration_id, make_scoped_refptr(existing_registration_ref), callback)); return; } // Record the duplicated registration BackgroundSyncMetrics::CountRegister( existing_registration->options()->periodicity, registration_could_fire, BackgroundSyncMetrics::REGISTRATION_IS_DUPLICATE, BACKGROUND_SYNC_STATUS_OK); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind( callback, BACKGROUND_SYNC_STATUS_OK, base::Passed( CreateRegistrationHandle(existing_registration_ref).Pass()))); return; } scoped_refptr<RefCountedRegistration> new_ref_registration( new RefCountedRegistration()); BackgroundSyncRegistration* new_registration = new_ref_registration->value(); *new_registration->options() = options; BackgroundSyncRegistrations* registrations = &active_registrations_[sw_registration_id]; new_registration->set_id(registrations->next_id++); AddActiveRegistration(sw_registration_id, sw_registration->pattern().GetOrigin(), new_ref_registration); StoreRegistrations( sw_registration_id, base::Bind(&BackgroundSyncManager::RegisterDidStore, weak_ptr_factory_.GetWeakPtr(), sw_registration_id, new_ref_registration, callback)); } void BackgroundSyncManager::DisableAndClearManager( const base::Closure& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback)); return; } disabled_ = true; active_registrations_.clear(); // Delete all backend entries. The memory representation of registered syncs // may be out of sync with storage (e.g., due to corruption detection on // loading from storage), so reload the registrations from storage again. GetDataFromBackend( kBackgroundSyncUserDataKey, base::Bind(&BackgroundSyncManager::DisableAndClearDidGetRegistrations, weak_ptr_factory_.GetWeakPtr(), callback)); } void BackgroundSyncManager::DisableAndClearDidGetRegistrations( const base::Closure& callback, const std::vector<std::pair<int64, std::string>>& user_data, ServiceWorkerStatusCode status) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (status != SERVICE_WORKER_OK || user_data.empty()) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback)); return; } base::Closure barrier_closure = base::BarrierClosure(user_data.size(), base::Bind(callback)); for (const auto& sw_id_and_regs : user_data) { service_worker_context_->ClearRegistrationUserData( sw_id_and_regs.first, kBackgroundSyncUserDataKey, base::Bind(&BackgroundSyncManager::DisableAndClearManagerClearedOne, weak_ptr_factory_.GetWeakPtr(), barrier_closure)); } } void BackgroundSyncManager::DisableAndClearManagerClearedOne( const base::Closure& barrier_closure, ServiceWorkerStatusCode status) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // The status doesn't matter at this point, there is nothing else to be done. base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(barrier_closure)); } BackgroundSyncManager::RefCountedRegistration* BackgroundSyncManager::LookupActiveRegistration( int64 sw_registration_id, const RegistrationKey& registration_key) { DCHECK_CURRENTLY_ON(BrowserThread::IO); SWIdToRegistrationsMap::iterator it = active_registrations_.find(sw_registration_id); if (it == active_registrations_.end()) return nullptr; BackgroundSyncRegistrations& registrations = it->second; DCHECK_LE(BackgroundSyncRegistration::kInitialId, registrations.next_id); DCHECK(!registrations.origin.is_empty()); auto key_and_registration_iter = registrations.registration_map.find(registration_key); if (key_and_registration_iter == registrations.registration_map.end()) return nullptr; return key_and_registration_iter->second.get(); } void BackgroundSyncManager::StoreRegistrations( int64 sw_registration_id, const ServiceWorkerStorage::StatusCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // Serialize the data. const BackgroundSyncRegistrations& registrations = active_registrations_[sw_registration_id]; BackgroundSyncRegistrationsProto registrations_proto; registrations_proto.set_next_registration_id(registrations.next_id); registrations_proto.set_origin(registrations.origin.spec()); for (const auto& key_and_registration : registrations.registration_map) { const BackgroundSyncRegistration& registration = *key_and_registration.second->value(); BackgroundSyncRegistrationProto* registration_proto = registrations_proto.add_registration(); registration_proto->set_id(registration.id()); registration_proto->set_sync_state(registration.sync_state()); registration_proto->set_tag(registration.options()->tag); registration_proto->set_periodicity(registration.options()->periodicity); registration_proto->set_min_period(registration.options()->min_period); registration_proto->set_network_state( registration.options()->network_state); registration_proto->set_power_state(registration.options()->power_state); } std::string serialized; bool success = registrations_proto.SerializeToString(&serialized); DCHECK(success); StoreDataInBackend(sw_registration_id, registrations.origin, kBackgroundSyncUserDataKey, serialized, callback); } void BackgroundSyncManager::RegisterDidStore( int64 sw_registration_id, const scoped_refptr<RefCountedRegistration>& new_registration_ref, const StatusAndRegistrationCallback& callback, ServiceWorkerStatusCode status) { DCHECK_CURRENTLY_ON(BrowserThread::IO); const BackgroundSyncRegistration* new_registration = new_registration_ref->value(); // For UMA, determine here whether the sync could fire immediately BackgroundSyncMetrics::RegistrationCouldFire registration_could_fire = AreOptionConditionsMet(*new_registration->options()) ? BackgroundSyncMetrics::REGISTRATION_COULD_FIRE : BackgroundSyncMetrics::REGISTRATION_COULD_NOT_FIRE; if (status == SERVICE_WORKER_ERROR_NOT_FOUND) { // The service worker registration is gone. BackgroundSyncMetrics::CountRegister( new_registration->options()->periodicity, registration_could_fire, BackgroundSyncMetrics::REGISTRATION_IS_NOT_DUPLICATE, BACKGROUND_SYNC_STATUS_STORAGE_ERROR); active_registrations_.erase(sw_registration_id); PostErrorResponse(BACKGROUND_SYNC_STATUS_STORAGE_ERROR, callback); return; } if (status != SERVICE_WORKER_OK) { LOG(ERROR) << "BackgroundSync failed to store registration due to backend " "failure."; BackgroundSyncMetrics::CountRegister( new_registration->options()->periodicity, registration_could_fire, BackgroundSyncMetrics::REGISTRATION_IS_NOT_DUPLICATE, BACKGROUND_SYNC_STATUS_STORAGE_ERROR); DisableAndClearManager(base::Bind( callback, BACKGROUND_SYNC_STATUS_STORAGE_ERROR, base::Passed(scoped_ptr<BackgroundSyncRegistrationHandle>().Pass()))); return; } BackgroundSyncMetrics::CountRegister( new_registration->options()->periodicity, registration_could_fire, BackgroundSyncMetrics::REGISTRATION_IS_NOT_DUPLICATE, BACKGROUND_SYNC_STATUS_OK); FireReadyEvents(); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind( callback, BACKGROUND_SYNC_STATUS_OK, base::Passed( CreateRegistrationHandle(new_registration_ref.get()).Pass()))); } void BackgroundSyncManager::RemoveActiveRegistration( int64 sw_registration_id, const RegistrationKey& registration_key) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(LookupActiveRegistration(sw_registration_id, registration_key)); BackgroundSyncRegistrations* registrations = &active_registrations_[sw_registration_id]; registrations->registration_map.erase(registration_key); } void BackgroundSyncManager::AddActiveRegistration( int64 sw_registration_id, const GURL& origin, const scoped_refptr<RefCountedRegistration>& sync_registration) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(sync_registration->value()->IsValid()); BackgroundSyncRegistrations* registrations = &active_registrations_[sw_registration_id]; registrations->origin = origin; RegistrationKey registration_key(*sync_registration->value()); registrations->registration_map[registration_key] = sync_registration; } void BackgroundSyncManager::StoreDataInBackend( int64 sw_registration_id, const GURL& origin, const std::string& backend_key, const std::string& data, const ServiceWorkerStorage::StatusCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); service_worker_context_->StoreRegistrationUserData( sw_registration_id, origin, backend_key, data, callback); } void BackgroundSyncManager::GetDataFromBackend( const std::string& backend_key, const ServiceWorkerStorage::GetUserDataForAllRegistrationsCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); service_worker_context_->GetUserDataForAllRegistrations(backend_key, callback); } void BackgroundSyncManager::FireOneShotSync( BackgroundSyncRegistrationHandle::HandleId handle_id, const scoped_refptr<ServiceWorkerVersion>& active_version, const ServiceWorkerVersion::StatusCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(active_version); // The ServiceWorkerVersion doesn't know when the client (javascript) is done // with the registration so don't give it a BackgroundSyncRegistrationHandle. // Once the render process gets the handle_id it can create its own handle // (with a new unique handle id). active_version->DispatchSyncEvent(handle_id, callback); } scoped_ptr<BackgroundSyncRegistrationHandle> BackgroundSyncManager::CreateRegistrationHandle( const scoped_refptr<RefCountedRegistration>& registration) { scoped_refptr<RefCountedRegistration>* ptr = new scoped_refptr<RefCountedRegistration>(registration); // Registration handles have unique handle ids. The handle id maps to an // internal RefCountedRegistration (which has the persistent registration id) // via // registration_reference_ids_. BackgroundSyncRegistrationHandle::HandleId handle_id = registration_handle_ids_.Add(ptr); return make_scoped_ptr(new BackgroundSyncRegistrationHandle( weak_ptr_factory_.GetWeakPtr(), handle_id)); } BackgroundSyncRegistration* BackgroundSyncManager::GetRegistrationForHandle( BackgroundSyncRegistrationHandle::HandleId handle_id) const { scoped_refptr<RefCountedRegistration>* ref_registration = registration_handle_ids_.Lookup(handle_id); if (!ref_registration) return nullptr; return (*ref_registration)->value(); } void BackgroundSyncManager::ReleaseRegistrationHandle( BackgroundSyncRegistrationHandle::HandleId handle_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(registration_handle_ids_.Lookup(handle_id)); registration_handle_ids_.Remove(handle_id); } void BackgroundSyncManager::Unregister( int64 sw_registration_id, SyncPeriodicity periodicity, BackgroundSyncRegistrationHandle::HandleId handle_id, const StatusCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { BackgroundSyncMetrics::CountUnregister( periodicity, BACKGROUND_SYNC_STATUS_STORAGE_ERROR); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, BACKGROUND_SYNC_STATUS_STORAGE_ERROR)); return; } BackgroundSyncRegistration* registration = GetRegistrationForHandle(handle_id); DCHECK(registration); op_scheduler_.ScheduleOperation(base::Bind( &BackgroundSyncManager::UnregisterImpl, weak_ptr_factory_.GetWeakPtr(), sw_registration_id, RegistrationKey(*registration), registration->id(), periodicity, MakeStatusCompletion(callback))); } void BackgroundSyncManager::UnregisterImpl( int64 sw_registration_id, const RegistrationKey& registration_key, BackgroundSyncRegistration::RegistrationId sync_registration_id, SyncPeriodicity periodicity, const StatusCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { BackgroundSyncMetrics::CountUnregister( periodicity, BACKGROUND_SYNC_STATUS_STORAGE_ERROR); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, BACKGROUND_SYNC_STATUS_STORAGE_ERROR)); return; } const RefCountedRegistration* existing_registration = LookupActiveRegistration(sw_registration_id, registration_key); if (!existing_registration || existing_registration->value()->id() != sync_registration_id) { BackgroundSyncMetrics::CountUnregister(periodicity, BACKGROUND_SYNC_STATUS_NOT_FOUND); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, BACKGROUND_SYNC_STATUS_NOT_FOUND)); return; } RemoveActiveRegistration(sw_registration_id, registration_key); StoreRegistrations(sw_registration_id, base::Bind(&BackgroundSyncManager::UnregisterDidStore, weak_ptr_factory_.GetWeakPtr(), sw_registration_id, periodicity, callback)); } void BackgroundSyncManager::UnregisterDidStore(int64 sw_registration_id, SyncPeriodicity periodicity, const StatusCallback& callback, ServiceWorkerStatusCode status) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (status == SERVICE_WORKER_ERROR_NOT_FOUND) { // ServiceWorker was unregistered. BackgroundSyncMetrics::CountUnregister( periodicity, BACKGROUND_SYNC_STATUS_STORAGE_ERROR); active_registrations_.erase(sw_registration_id); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, BACKGROUND_SYNC_STATUS_STORAGE_ERROR)); return; } if (status != SERVICE_WORKER_OK) { LOG(ERROR) << "BackgroundSync failed to unregister due to backend failure."; BackgroundSyncMetrics::CountUnregister( periodicity, BACKGROUND_SYNC_STATUS_STORAGE_ERROR); DisableAndClearManager( base::Bind(callback, BACKGROUND_SYNC_STATUS_STORAGE_ERROR)); return; } BackgroundSyncMetrics::CountUnregister(periodicity, BACKGROUND_SYNC_STATUS_OK); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, BACKGROUND_SYNC_STATUS_OK)); } void BackgroundSyncManager::GetRegistrationImpl( int64 sw_registration_id, const RegistrationKey& registration_key, const StatusAndRegistrationCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { PostErrorResponse(BACKGROUND_SYNC_STATUS_STORAGE_ERROR, callback); return; } RefCountedRegistration* registration = LookupActiveRegistration(sw_registration_id, registration_key); if (!registration) { PostErrorResponse(BACKGROUND_SYNC_STATUS_NOT_FOUND, callback); return; } base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, BACKGROUND_SYNC_STATUS_OK, base::Passed(CreateRegistrationHandle(registration).Pass()))); } void BackgroundSyncManager::GetRegistrationsImpl( int64 sw_registration_id, SyncPeriodicity periodicity, const StatusAndRegistrationsCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); scoped_ptr<ScopedVector<BackgroundSyncRegistrationHandle>> out_registrations( new ScopedVector<BackgroundSyncRegistrationHandle>()); if (disabled_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, BACKGROUND_SYNC_STATUS_STORAGE_ERROR, base::Passed(out_registrations.Pass()))); return; } SWIdToRegistrationsMap::iterator it = active_registrations_.find(sw_registration_id); if (it != active_registrations_.end()) { const BackgroundSyncRegistrations& registrations = it->second; for (const auto& tag_and_registration : registrations.registration_map) { RefCountedRegistration* registration = tag_and_registration.second.get(); if (registration->value()->options()->periodicity == periodicity) { out_registrations->push_back( CreateRegistrationHandle(registration).release()); } } } base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, BACKGROUND_SYNC_STATUS_OK, base::Passed(out_registrations.Pass()))); } bool BackgroundSyncManager::AreOptionConditionsMet( const BackgroundSyncRegistrationOptions& options) { DCHECK_CURRENTLY_ON(BrowserThread::IO); return network_observer_->NetworkSufficient(options.network_state) && power_observer_->PowerSufficient(options.power_state); } bool BackgroundSyncManager::IsRegistrationReadyToFire( const BackgroundSyncRegistration& registration) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // TODO(jkarlin): Add support for firing periodic registrations. if (registration.options()->periodicity == SYNC_PERIODIC) return false; if (registration.sync_state() != SYNC_STATE_PENDING) return false; DCHECK_EQ(SYNC_ONE_SHOT, registration.options()->periodicity); return AreOptionConditionsMet(*registration.options()); } void BackgroundSyncManager::SchedulePendingRegistrations() { #if defined(OS_ANDROID) bool keep_browser_alive_for_one_shot = false; for (const auto& sw_id_and_registrations : active_registrations_) { for (const auto& key_and_registration : sw_id_and_registrations.second.registration_map) { const BackgroundSyncRegistration& registration = *key_and_registration.second->value(); if (registration.sync_state() == SYNC_STATE_PENDING) { if (registration.options()->periodicity == SYNC_ONE_SHOT) { keep_browser_alive_for_one_shot = true; } else { // TODO(jkarlin): Support keeping the browser alive for periodic // syncs. } } } } // TODO(jkarlin): Use the context's path instead of the 'this' pointer as an // identifier. See crbug.com/489705. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&BackgroundSyncLauncherAndroid::LaunchBrowserWhenNextOnline, this, keep_browser_alive_for_one_shot)); #else // TODO(jkarlin): Toggle Chrome's background mode. #endif } void BackgroundSyncManager::FireReadyEvents() { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) return; op_scheduler_.ScheduleOperation( base::Bind(&BackgroundSyncManager::FireReadyEventsImpl, weak_ptr_factory_.GetWeakPtr(), MakeEmptyCompletion())); } void BackgroundSyncManager::FireReadyEventsImpl(const base::Closure& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback)); return; } // Find the registrations that are ready to run. std::vector<std::pair<int64, RegistrationKey>> sw_id_and_keys_to_fire; for (auto& sw_id_and_registrations : active_registrations_) { const int64 service_worker_id = sw_id_and_registrations.first; for (auto& key_and_registration : sw_id_and_registrations.second.registration_map) { BackgroundSyncRegistration* registration = key_and_registration.second->value(); if (IsRegistrationReadyToFire(*registration)) { sw_id_and_keys_to_fire.push_back( std::make_pair(service_worker_id, key_and_registration.first)); // The state change is not saved to persistent storage because // if the sync event is killed mid-sync then it should return to // SYNC_STATE_PENDING. registration->set_sync_state(SYNC_STATE_FIRING); } } } // If there are no registrations currently ready, then just run |callback|. // Otherwise, fire them all, and record the result when done. if (sw_id_and_keys_to_fire.size() == 0) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback)); } else { base::TimeTicks start_time = base::TimeTicks::Now(); // Fire the sync event of the ready registrations and run |callback| once // they're all done. base::Closure events_fired_barrier_closure = base::BarrierClosure( sw_id_and_keys_to_fire.size(), base::Bind(callback)); // Record the total time taken after all events have run to completion. base::Closure events_completed_barrier_closure = base::BarrierClosure(sw_id_and_keys_to_fire.size(), base::Bind(&OnAllSyncEventsCompleted, start_time, sw_id_and_keys_to_fire.size())); for (const auto& sw_id_and_key : sw_id_and_keys_to_fire) { int64 service_worker_id = sw_id_and_key.first; const RefCountedRegistration* registration = LookupActiveRegistration(service_worker_id, sw_id_and_key.second); DCHECK(registration); service_worker_context_->FindRegistrationForId( service_worker_id, active_registrations_[service_worker_id].origin, base::Bind(&BackgroundSyncManager::FireReadyEventsDidFindRegistration, weak_ptr_factory_.GetWeakPtr(), sw_id_and_key.second, registration->value()->id(), events_fired_barrier_closure, events_completed_barrier_closure)); } } SchedulePendingRegistrations(); } void BackgroundSyncManager::FireReadyEventsDidFindRegistration( const RegistrationKey& registration_key, BackgroundSyncRegistration::RegistrationId registration_id, const base::Closure& event_fired_callback, const base::Closure& event_completed_callback, ServiceWorkerStatusCode service_worker_status, const scoped_refptr<ServiceWorkerRegistration>& service_worker_registration) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (service_worker_status != SERVICE_WORKER_OK) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(event_fired_callback)); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(event_completed_callback)); return; } RefCountedRegistration* registration = LookupActiveRegistration( service_worker_registration->id(), registration_key); DCHECK(registration); // Create a handle and keep it until the sync event completes. The client can // acquire its own handle for longer-term use. scoped_ptr<BackgroundSyncRegistrationHandle> registration_handle = CreateRegistrationHandle(registration); BackgroundSyncRegistrationHandle::HandleId handle_id = registration_handle->handle_id(); FireOneShotSync( handle_id, service_worker_registration->active_version(), base::Bind( &BackgroundSyncManager::EventComplete, weak_ptr_factory_.GetWeakPtr(), service_worker_registration, service_worker_registration->id(), base::Passed(registration_handle.Pass()), event_completed_callback)); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(event_fired_callback)); } // |service_worker_registration| is just to keep the registration alive // while the event is firing. void BackgroundSyncManager::EventComplete( const scoped_refptr<ServiceWorkerRegistration>& service_worker_registration, int64 service_worker_id, scoped_ptr<BackgroundSyncRegistrationHandle> registration_handle, const base::Closure& callback, ServiceWorkerStatusCode status_code) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) return; op_scheduler_.ScheduleOperation(base::Bind( &BackgroundSyncManager::EventCompleteImpl, weak_ptr_factory_.GetWeakPtr(), service_worker_id, base::Passed(registration_handle.Pass()), status_code, MakeClosureCompletion(callback))); } void BackgroundSyncManager::EventCompleteImpl( int64 service_worker_id, scoped_ptr<BackgroundSyncRegistrationHandle> registration_handle, ServiceWorkerStatusCode status_code, const base::Closure& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback)); return; } BackgroundSyncRegistration* registration = registration_handle->registration(); DCHECK(registration); // The event ran to completion, we should count it, no matter what happens // from here. BackgroundSyncMetrics::RecordEventResult(registration->options()->periodicity, status_code == SERVICE_WORKER_OK); if (registration->options()->periodicity == SYNC_ONE_SHOT) { if (status_code != SERVICE_WORKER_OK) { // TODO(jkarlin) Fire the sync event on the next page load controlled by // this registration. (crbug.com/479665) registration->set_sync_state(SYNC_STATE_FAILED); } else { RegistrationKey key(*registration); // Remove the registration if it's still active. RefCountedRegistration* active_registration = LookupActiveRegistration(service_worker_id, key); if (active_registration && active_registration->value()->id() == registration->id()) RemoveActiveRegistration(service_worker_id, key); } } else { // TODO(jkarlin): Add support for running periodic syncs. (crbug.com/479674) NOTREACHED(); } StoreRegistrations( service_worker_id, base::Bind(&BackgroundSyncManager::EventCompleteDidStore, weak_ptr_factory_.GetWeakPtr(), service_worker_id, callback)); } void BackgroundSyncManager::EventCompleteDidStore( int64 service_worker_id, const base::Closure& callback, ServiceWorkerStatusCode status_code) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (status_code == SERVICE_WORKER_ERROR_NOT_FOUND) { // The registration is gone. active_registrations_.erase(service_worker_id); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback)); return; } if (status_code != SERVICE_WORKER_OK) { LOG(ERROR) << "BackgroundSync failed to store registration due to backend " "failure."; DisableAndClearManager(base::Bind(callback)); return; } base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback)); } // static void BackgroundSyncManager::OnAllSyncEventsCompleted( const base::TimeTicks& start_time, int number_of_batched_sync_events) { // Record the combined time taken by all sync events. BackgroundSyncMetrics::RecordBatchSyncEventComplete( base::TimeTicks::Now() - start_time, number_of_batched_sync_events); } void BackgroundSyncManager::OnRegistrationDeletedImpl( int64 registration_id, const base::Closure& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // The backend (ServiceWorkerStorage) will delete the data, so just delete the // memory representation here. active_registrations_.erase(registration_id); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback)); } void BackgroundSyncManager::OnStorageWipedImpl(const base::Closure& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); active_registrations_.clear(); disabled_ = false; InitImpl(callback); } void BackgroundSyncManager::OnNetworkChanged() { DCHECK_CURRENTLY_ON(BrowserThread::IO); FireReadyEvents(); } void BackgroundSyncManager::OnPowerChanged() { DCHECK_CURRENTLY_ON(BrowserThread::IO); FireReadyEvents(); } // TODO(jkarlin): Figure out how to pass scoped_ptrs with this. template <typename CallbackT, typename... Params> void BackgroundSyncManager::CompleteOperationCallback(const CallbackT& callback, Params... parameters) { DCHECK_CURRENTLY_ON(BrowserThread::IO); callback.Run(parameters...); op_scheduler_.CompleteOperationAndRunNext(); } void BackgroundSyncManager::CompleteStatusAndRegistrationCallback( StatusAndRegistrationCallback callback, BackgroundSyncStatus status, scoped_ptr<BackgroundSyncRegistrationHandle> registration_handle) { DCHECK_CURRENTLY_ON(BrowserThread::IO); callback.Run(status, registration_handle.Pass()); op_scheduler_.CompleteOperationAndRunNext(); } void BackgroundSyncManager::CompleteStatusAndRegistrationsCallback( StatusAndRegistrationsCallback callback, BackgroundSyncStatus status, scoped_ptr<ScopedVector<BackgroundSyncRegistrationHandle>> registration_handles) { DCHECK_CURRENTLY_ON(BrowserThread::IO); callback.Run(status, registration_handles.Pass()); op_scheduler_.CompleteOperationAndRunNext(); } base::Closure BackgroundSyncManager::MakeEmptyCompletion() { DCHECK_CURRENTLY_ON(BrowserThread::IO); return MakeClosureCompletion(base::Bind(base::DoNothing)); } base::Closure BackgroundSyncManager::MakeClosureCompletion( const base::Closure& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); return base::Bind( &BackgroundSyncManager::CompleteOperationCallback<base::Closure>, weak_ptr_factory_.GetWeakPtr(), callback); } BackgroundSyncManager::StatusAndRegistrationCallback BackgroundSyncManager::MakeStatusAndRegistrationCompletion( const StatusAndRegistrationCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); return base::Bind( &BackgroundSyncManager::CompleteStatusAndRegistrationCallback, weak_ptr_factory_.GetWeakPtr(), callback); } BackgroundSyncManager::StatusAndRegistrationsCallback BackgroundSyncManager::MakeStatusAndRegistrationsCompletion( const StatusAndRegistrationsCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); return base::Bind( &BackgroundSyncManager::CompleteStatusAndRegistrationsCallback, weak_ptr_factory_.GetWeakPtr(), callback); } BackgroundSyncManager::StatusCallback BackgroundSyncManager::MakeStatusCompletion(const StatusCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); return base::Bind( &BackgroundSyncManager::CompleteOperationCallback<StatusCallback, BackgroundSyncStatus>, weak_ptr_factory_.GetWeakPtr(), callback); } } // namespace content
Chilledheart/chromium
content/browser/background_sync/background_sync_manager.cc
C++
bsd-3-clause
45,304
var http = require('http'); // check against public file to see if this is the current version of Mapbox Studio Classic module.exports = function (opts, callback) { var update = false; http.request({ host: opts.host, port: opts.port || 80, path: opts.path, method: 'GET' }, function(response){ var latest = ''; response.on('data', function (chunk) { latest += chunk; }); response.on('end', function () { var current = opts.pckge.version.replace(/^\s+|\s+$/g, ''); latest = latest.replace(/^\s+|\s+$/g, ''); if (latest !== current) { update = true; } return callback(update, current, latest); }); }) .on('error', function(err){ return callback(false); }) .end(); };
mapbox/mapbox-studio
lib/version-check.js
JavaScript
bsd-3-clause
862
<?php /* * This file is part of Cachet. * * (c) Alt Three Services Limited * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace CachetHQ\Cachet\Composers; use CachetHQ\Cachet\Facades\Setting; use CachetHQ\Cachet\Models\Metric; use CachetHQ\Cachet\Repositories\Metric\MetricRepository; use Illuminate\Contracts\View\View; class MetricsComposer { /** * @var \CachetHQ\Cachet\Repositories\Metric\MetricRepository */ protected $metricRepository; /** * Construct a new home controller instance. * * @param \CachetHQ\Cachet\Repositories\Metric\MetricRepository $metricRepository * * @return void */ public function __construct(MetricRepository $metricRepository) { $this->metricRepository = $metricRepository; } /** * Metrics view composer. * * @param \Illuminate\Contracts\View\View $view * * @return void */ public function compose(View $view) { $metrics = null; $metricData = []; if ($displayMetrics = Setting::get('display_graphs')) { $metrics = Metric::where('display_chart', 1)->get(); $metrics->map(function ($metric) use (&$metricData) { $metricData[$metric->id] = [ 'today' => $this->metricRepository->listPointsToday($metric), 'week' => $this->metricRepository->listPointsForWeek($metric), 'month' => $this->metricRepository->listPointsForMonth($metric), ]; }); } $view->withDisplayMetrics($displayMetrics) ->withMetrics($metrics) ->withMetricData($metricData); } }
katzien/Cachet
app/Composers/MetricsComposer.php
PHP
bsd-3-clause
1,783
// $G $D/$F.go && $L $F.$A && // ./$A.out -pass 0 >tmp.go && $G tmp.go && $L -o $A.out1 tmp.$A && ./$A.out1 && // ./$A.out -pass 1 >tmp.go && errchk $G -e tmp.go && // ./$A.out -pass 2 >tmp.go && errchk $G -e tmp.go // rm -f tmp.go $A.out1 // Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Generate test of index and slice bounds checks. // The output is compiled and run. package main import ( "bufio" "flag" "fmt" "os" ) const prolog = ` package main import ( "runtime" ) type quad struct { x, y, z, w int } const ( cj = 11 ci int = 12 ci32 int32 = 13 ci64 int64 = 14 ci64big int64 = 1<<31 ci64bigger int64 = 1<<32 chuge = 1<<100 cnj = -2 cni int = -3 cni32 int32 = -4 cni64 int64 = -5 cni64big int64 = -1<<31 cni64bigger int64 = -1<<32 cnhuge = -1<<100 ) var j int = 20 var i int = 21 var i32 int32 = 22 var i64 int64 = 23 var i64big int64 = 1<<31 var i64bigger int64 = 1<<32 var huge uint64 = 1<<64 - 1 var nj int = -10 var ni int = -11 var ni32 int32 = -12 var ni64 int64 = -13 var ni64big int64 = -1<<31 var ni64bigger int64 = -1<<32 var nhuge int64 = -1<<63 var si []int = make([]int, 10) var ai [10]int var pai *[10]int = &ai var sq []quad = make([]quad, 10) var aq [10]quad var paq *[10]quad = &aq type T struct { si []int ai [10]int pai *[10]int sq []quad aq [10]quad paq *[10]quad } var t = T{si, ai, pai, sq, aq, paq} var pt = &T{si, ai, pai, sq, aq, paq} // test that f panics func test(f func(), s string) { defer func() { if err := recover(); err == nil { _, file, line, _ := runtime.Caller(2) bug() print(file, ":", line, ": ", s, " did not panic\n") } }() f() } var X interface{} func use(y interface{}) { X = y } var didBug = false func bug() { if !didBug { didBug = true println("BUG") } } func main() { ` // Passes: // 0 - dynamic checks // 1 - static checks of invalid constants (cannot assign to types) // 2 - static checks of array bounds var pass = flag.Int("pass", 0, "which test (0,1,2)") func testExpr(b *bufio.Writer, expr string) { if *pass == 0 { fmt.Fprintf(b, "\ttest(func(){use(%s)}, %q)\n", expr, expr) } else { fmt.Fprintf(b, "\tuse(%s) // ERROR \"index|overflow\"\n", expr) } } func main() { b := bufio.NewWriter(os.Stdout) flag.Parse() if *pass == 0 { fmt.Fprint(b, "// $G $D/$F.go && $L $F.$A && ./$A.out\n\n") } else { fmt.Fprint(b, "// errchk $G -e $D/$F.go\n\n") } fmt.Fprint(b, prolog) var choices = [][]string{ // Direct value, fetch from struct, fetch from struct pointer. // The last two cases get us to oindex_const_sudo in gsubr.c. []string{"", "t.", "pt."}, // Array, pointer to array, slice. []string{"a", "pa", "s"}, // Element is int, element is quad (struct). // This controls whether we end up in gsubr.c (i) or cgen.c (q). []string{"i", "q"}, // Variable or constant. []string{"", "c"}, // Positive or negative. []string{"", "n"}, // Size of index. []string{"j", "i", "i32", "i64", "i64big", "i64bigger", "huge"}, } forall(choices, func(x []string) { p, a, e, c, n, i := x[0], x[1], x[2], x[3], x[4], x[5] // Pass: dynamic=0, static=1, 2. // Which cases should be caught statically? // Only constants, obviously. // Beyond that, must be one of these: // indexing into array or pointer to array // negative constant // large constant thisPass := 0 if c == "c" && (a == "a" || a == "pa" || n == "n" || i == "i64big" || i == "i64bigger" || i == "huge") { if i == "huge" { // Due to a detail of 6g's internals, // the huge constant errors happen in an // earlier pass than the others and inhibits // the next pass from running. // So run it as a separate check. thisPass = 1 } else { thisPass = 2 } } // Only print the test case if it is appropriate for this pass. if thisPass == *pass { pae := p+a+e cni := c+n+i // Index operation testExpr(b, pae + "[" + cni + "]") // Slice operation. // Low index 0 is a special case in ggen.c // so test both 0 and 1. testExpr(b, pae + "[0:" + cni + "]") testExpr(b, pae + "[1:" + cni + "]") testExpr(b, pae + "[" + cni + ":]") testExpr(b, pae + "[" + cni + ":" + cni + "]") } }) fmt.Fprintln(b, "}") b.Flush() } func forall(choices [][]string, f func([]string)) { x := make([]string, len(choices)) var recurse func(d int) recurse = func(d int) { if d >= len(choices) { f(x) return } for _, x[d] = range choices[d] { recurse(d+1) } } recurse(0) }
oopos/go
test/index.go
GO
bsd-3-clause
4,621
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_SDK_SIMD_EXTENSIONS_POWERPC_QPX_HPP_INCLUDED #define BOOST_SIMD_SDK_SIMD_EXTENSIONS_POWERPC_QPX_HPP_INCLUDED #if defined(__VECTOR4DOUBLE__) # ifndef BOOST_SIMD_HAS_QPX_SUPPORT # define BOOST_SIMD_HAS_QPX_SUPPORT # endif #elif defined(BOOST_SIMD_HAS_QPX_SUPPORT) # undef BOOST_SIMD_HAS_QPX_SUPPORT #endif #if !defined(BOOST_SIMD_DETECTED) && defined(BOOST_SIMD_HAS_QPX_SUPPORT) //////////////////////////////////////////////////////////////////////////////// // Altivec PPC extensions flags //////////////////////////////////////////////////////////////////////////////// #define BOOST_SIMD_DETECTED #define BOOST_SIMD_ALTIVEC #define BOOST_SIMD_STRING "QPX" #define BOOST_SIMD_STRING_LIST "QPX" #define BOOST_SIMD_VMX_FAMILY #define BOOST_SIMD_BYTES 32 #define BOOST_SIMD_BITS 256 #define BOOST_SIMD_CARDINALS (8) #define BOOST_SIMD_TAG_SEQ (::boost::simd::tag::qpx_) #ifndef BOOST_SIMD_DEFAULT_EXTENSION #define BOOST_SIMD_DEFAULT_EXTENSION ::boost::simd::tag::qpx_ #endif #define BOOST_SIMD_DEFAULT_SITE ::boost::simd::tag::qpx_ #define BOOST_SIMD_NO_DENORMALS #define BOOST_SIMD_SIMD_REAL_TYPES (double) #define BOOST_SIMD_SIMD_INTEGRAL_UNSIGNED_TYPES #define BOOST_SIMD_SIMD_INTEGRAL_SIGNED_TYPES #define BOOST_SIMD_SIMD_INT_CONVERT_TYPES #define BOOST_SIMD_SIMD_UINT_CONVERT_TYPES #define BOOST_SIMD_SIMD_GROUPABLE_TYPES #define BOOST_SIMD_SIMD_SPLITABLE_TYPES #define BOOST_SIMD_SIMD_REAL_GROUPABLE_TYPES #define BOOST_SIMD_SIMD_REAL_SPLITABLE_TYPES #include <boost/simd/sdk/simd/extensions/meta/qpx.hpp> #endif #endif
hainm/pythran
third_party/boost/simd/sdk/simd/extensions/powerpc/qpx.hpp
C++
bsd-3-clause
2,143
<?php error_reporting(E_ALL & ~E_NOTICE); $root = simplexml_load_string('<?xml version="1.0"?> <root xmlns:reserved="reserved-ns"> <child reserved:attribute="Sample" /> </root> '); $attr = $root->child->attributes('reserved-ns'); echo $attr['attribute']; echo "\n---Done---\n"; ?>
JSchwehn/php
testdata/fuzzdir/corpus/ext_simplexml_tests_profile06.php
PHP
bsd-3-clause
283
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/speech/speech_recognizer_impl_android.h" #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/bind.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/speech_recognition_event_listener.h" #include "content/public/browser/speech_recognition_manager.h" #include "content/public/browser/speech_recognition_session_config.h" #include "content/public/common/speech_recognition_grammar.h" #include "content/public/common/speech_recognition_result.h" #include "jni/SpeechRecognition_jni.h" using base::android::AppendJavaStringArrayToStringVector; using base::android::AttachCurrentThread; using base::android::GetApplicationContext; using base::android::JavaFloatArrayToFloatVector; namespace content { SpeechRecognizerImplAndroid::SpeechRecognizerImplAndroid( SpeechRecognitionEventListener* listener, int session_id) : SpeechRecognizer(listener, session_id), state_(STATE_IDLE) { } SpeechRecognizerImplAndroid::~SpeechRecognizerImplAndroid() { } void SpeechRecognizerImplAndroid::StartRecognition() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind( &SpeechRecognitionEventListener::OnRecognitionStart, base::Unretained(listener()), session_id())); SpeechRecognitionSessionConfig config = SpeechRecognitionManager::GetInstance()->GetSessionConfig(session_id()); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind( &content::SpeechRecognizerImplAndroid::StartRecognitionOnUIThread, this, config.continuous, config.interim_results)); } void SpeechRecognizerImplAndroid::StartRecognitionOnUIThread( bool continuous, bool interim_results) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); JNIEnv* env = AttachCurrentThread(); j_recognition_.Reset(Java_SpeechRecognition_createSpeechRecognition(env, GetApplicationContext(), reinterpret_cast<jint>(this))); Java_SpeechRecognition_startRecognition(env, j_recognition_.obj(), continuous, interim_results); } void SpeechRecognizerImplAndroid::AbortRecognition() { if (BrowserThread::CurrentlyOn(BrowserThread::IO)) { state_ = STATE_IDLE; BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind( &content::SpeechRecognizerImplAndroid::AbortRecognition, this)); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); JNIEnv* env = AttachCurrentThread(); if (!j_recognition_.is_null()) Java_SpeechRecognition_abortRecognition(env, j_recognition_.obj()); } void SpeechRecognizerImplAndroid::StopAudioCapture() { if (BrowserThread::CurrentlyOn(BrowserThread::IO)) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind( &content::SpeechRecognizerImplAndroid::StopAudioCapture, this)); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); JNIEnv* env = AttachCurrentThread(); if (!j_recognition_.is_null()) Java_SpeechRecognition_stopRecognition(env, j_recognition_.obj()); } bool SpeechRecognizerImplAndroid::IsActive() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); return state_ != STATE_IDLE; } bool SpeechRecognizerImplAndroid::IsCapturingAudio() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); return state_ == STATE_CAPTURING_AUDIO; } void SpeechRecognizerImplAndroid::OnAudioStart(JNIEnv* env, jobject obj) { if (BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind( &SpeechRecognizerImplAndroid::OnAudioStart, this, static_cast<JNIEnv*>(NULL), static_cast<jobject>(NULL))); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); state_ = STATE_CAPTURING_AUDIO; listener()->OnAudioStart(session_id()); } void SpeechRecognizerImplAndroid::OnSoundStart(JNIEnv* env, jobject obj) { if (BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind( &SpeechRecognizerImplAndroid::OnSoundStart, this, static_cast<JNIEnv*>(NULL), static_cast<jobject>(NULL))); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); listener()->OnSoundStart(session_id()); } void SpeechRecognizerImplAndroid::OnSoundEnd(JNIEnv* env, jobject obj) { if (BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind( &SpeechRecognizerImplAndroid::OnSoundEnd, this, static_cast<JNIEnv*>(NULL), static_cast<jobject>(NULL))); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); listener()->OnSoundEnd(session_id()); } void SpeechRecognizerImplAndroid::OnAudioEnd(JNIEnv* env, jobject obj) { if (BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind( &SpeechRecognizerImplAndroid::OnAudioEnd, this, static_cast<JNIEnv*>(NULL), static_cast<jobject>(NULL))); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (state_ == STATE_CAPTURING_AUDIO) state_ = STATE_AWAITING_FINAL_RESULT; listener()->OnAudioEnd(session_id()); } void SpeechRecognizerImplAndroid::OnRecognitionResults(JNIEnv* env, jobject obj, jobjectArray strings, jfloatArray floats, jboolean provisional) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); std::vector<string16> options; AppendJavaStringArrayToStringVector(env, strings, &options); std::vector<float> scores(options.size(), 0.0); if (floats != NULL) JavaFloatArrayToFloatVector(env, floats, &scores); SpeechRecognitionResults results; results.push_back(SpeechRecognitionResult()); SpeechRecognitionResult& result = results.back(); CHECK_EQ(options.size(), scores.size()); for (size_t i = 0; i < options.size(); ++i) { result.hypotheses.push_back(SpeechRecognitionHypothesis( options[i], static_cast<double>(scores[i]))); } result.is_provisional = provisional; BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind( &SpeechRecognizerImplAndroid::OnRecognitionResultsOnIOThread, this, results)); } void SpeechRecognizerImplAndroid::OnRecognitionResultsOnIOThread( SpeechRecognitionResults const &results) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); listener()->OnRecognitionResults(session_id(), results); } void SpeechRecognizerImplAndroid::OnRecognitionError(JNIEnv* env, jobject obj, jint error) { if (BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind( &SpeechRecognizerImplAndroid::OnRecognitionError, this, static_cast<JNIEnv*>(NULL), static_cast<jobject>(NULL), error)); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); SpeechRecognitionErrorCode code = static_cast<SpeechRecognitionErrorCode>(error); listener()->OnRecognitionError(session_id(), SpeechRecognitionError(code)); } void SpeechRecognizerImplAndroid::OnRecognitionEnd(JNIEnv* env, jobject obj) { if (BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind( &SpeechRecognizerImplAndroid::OnRecognitionEnd, this, static_cast<JNIEnv*>(NULL), static_cast<jobject>(NULL))); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); state_ = STATE_IDLE; listener()->OnRecognitionEnd(session_id()); } // static bool SpeechRecognizerImplAndroid::RegisterSpeechRecognizer(JNIEnv* env) { return RegisterNativesImpl(env); } } // namespace content
hujiajie/pa-chromium
content/browser/speech/speech_recognizer_impl_android.cc
C++
bsd-3-clause
8,013
/***************************************************************************** * McPAT/CACTI * SOFTWARE LICENSE AGREEMENT * Copyright 2012 Hewlett-Packard Development Company, L.P. * 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 copyright holders 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 * OWNER 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.” * ***************************************************************************/ #include <math.h> #include "basic_circuit.h" #include "parameter.h" double wire_resistance(double resistivity, double wire_width, double wire_thickness, double barrier_thickness, double dishing_thickness, double alpha_scatter) { double resistance; resistance = alpha_scatter * resistivity /((wire_thickness - barrier_thickness - dishing_thickness)*(wire_width - 2 * barrier_thickness)); return(resistance); } double wire_capacitance(double wire_width, double wire_thickness, double wire_spacing, double ild_thickness, double miller_value, double horiz_dielectric_constant, double vert_dielectric_constant, double fringe_cap) { double vertical_cap, sidewall_cap, total_cap; vertical_cap = 2 * PERMITTIVITY_FREE_SPACE * vert_dielectric_constant * wire_width / ild_thickness; sidewall_cap = 2 * PERMITTIVITY_FREE_SPACE * miller_value * horiz_dielectric_constant * wire_thickness / wire_spacing; total_cap = vertical_cap + sidewall_cap + fringe_cap; return(total_cap); } void init_tech_params(double technology, bool is_tag) { int iter, tech, tech_lo, tech_hi; double curr_alpha, curr_vpp; double wire_width, wire_thickness, wire_spacing, fringe_cap, pmos_to_nmos_sizing_r; // double aspect_ratio,ild_thickness, miller_value = 1.5, horiz_dielectric_constant, vert_dielectric_constant; double barrier_thickness, dishing_thickness, alpha_scatter; double curr_vdd_dram_cell, curr_v_th_dram_access_transistor, curr_I_on_dram_cell, curr_c_dram_cell; uint32_t ram_cell_tech_type = (is_tag) ? g_ip->tag_arr_ram_cell_tech_type : g_ip->data_arr_ram_cell_tech_type; uint32_t peri_global_tech_type = (is_tag) ? g_ip->tag_arr_peri_global_tech_type : g_ip->data_arr_peri_global_tech_type; technology = technology * 1000.0; // in the unit of nm // initialize parameters g_tp.reset(); double gmp_to_gmn_multiplier_periph_global = 0; double curr_Wmemcella_dram, curr_Wmemcellpmos_dram, curr_Wmemcellnmos_dram, curr_area_cell_dram, curr_asp_ratio_cell_dram, curr_Wmemcella_sram, curr_Wmemcellpmos_sram, curr_Wmemcellnmos_sram, curr_area_cell_sram, curr_asp_ratio_cell_sram, curr_I_off_dram_cell_worst_case_length_temp; double curr_Wmemcella_cam, curr_Wmemcellpmos_cam, curr_Wmemcellnmos_cam, curr_area_cell_cam,//Sheng: CAM data curr_asp_ratio_cell_cam; double SENSE_AMP_D, SENSE_AMP_P; // J double area_cell_dram = 0; double asp_ratio_cell_dram = 0; double area_cell_sram = 0; double asp_ratio_cell_sram = 0; double area_cell_cam = 0; double asp_ratio_cell_cam = 0; double mobility_eff_periph_global = 0; double Vdsat_periph_global = 0; double nmos_effective_resistance_multiplier; double width_dram_access_transistor; double curr_logic_scaling_co_eff = 0;//This is based on the reported numbers of Intel Merom 65nm, Penryn45nm and IBM cell 90/65/45 date double curr_core_tx_density = 0;//this is density per um^2; 90, ...22nm based on Intel Penryn double curr_chip_layout_overhead = 0; double curr_macro_layout_overhead = 0; double curr_sckt_co_eff = 0; if (technology < 181 && technology > 179) { tech_lo = 180; tech_hi = 180; } else if (technology < 91 && technology > 89) { tech_lo = 90; tech_hi = 90; } else if (technology < 66 && technology > 64) { tech_lo = 65; tech_hi = 65; } else if (technology < 46 && technology > 44) { tech_lo = 45; tech_hi = 45; } else if (technology < 33 && technology > 31) { tech_lo = 32; tech_hi = 32; } else if (technology < 23 && technology > 21) { tech_lo = 22; tech_hi = 22; if (ram_cell_tech_type == 3 ) { cout<<"current version does not support eDRAM technologies at 22nm"<<endl; exit(0); } } // else if (technology < 17 && technology > 15) // { // tech_lo = 16; // tech_hi = 16; // } else if (technology < 180 && technology > 90) { tech_lo = 180; tech_hi = 90; } else if (technology < 90 && technology > 65) { tech_lo = 90; tech_hi = 65; } else if (technology < 65 && technology > 45) { tech_lo = 65; tech_hi = 45; } else if (technology < 45 && technology > 32) { tech_lo = 45; tech_hi = 32; } else if (technology < 32 && technology > 22) { tech_lo = 32; tech_hi = 22; } // else if (technology < 22 && technology > 16) // { // tech_lo = 22; // tech_hi = 16; // } else { cout<<"Invalid technology nodes"<<endl; exit(0); } double vdd[NUMBER_TECH_FLAVORS];//default vdd from itrs double vdd_real[NUMBER_TECH_FLAVORS]; //real vdd defined by user, this is for changing vdd from itrs; it actually does not dependent on technology node since it is user defined double alpha_power_law[NUMBER_TECH_FLAVORS];//co-efficient for ap-law double Lphy[NUMBER_TECH_FLAVORS]; double Lelec[NUMBER_TECH_FLAVORS]; double t_ox[NUMBER_TECH_FLAVORS]; double v_th[NUMBER_TECH_FLAVORS]; double c_ox[NUMBER_TECH_FLAVORS]; double mobility_eff[NUMBER_TECH_FLAVORS]; double Vdsat[NUMBER_TECH_FLAVORS]; double c_g_ideal[NUMBER_TECH_FLAVORS]; double c_fringe[NUMBER_TECH_FLAVORS]; double c_junc[NUMBER_TECH_FLAVORS]; double I_on_n[NUMBER_TECH_FLAVORS]; double I_on_p[NUMBER_TECH_FLAVORS]; double Rnchannelon[NUMBER_TECH_FLAVORS]; double Rpchannelon[NUMBER_TECH_FLAVORS]; double n_to_p_eff_curr_drv_ratio[NUMBER_TECH_FLAVORS]; double I_off_n[NUMBER_TECH_FLAVORS][101]; double I_g_on_n[NUMBER_TECH_FLAVORS][101]; //double I_off_p[NUMBER_TECH_FLAVORS][101]; double gmp_to_gmn_multiplier[NUMBER_TECH_FLAVORS]; //double curr_sckt_co_eff[NUMBER_TECH_FLAVORS]; double long_channel_leakage_reduction[NUMBER_TECH_FLAVORS]; for (iter = 0; iter <= 1; ++iter) { // linear interpolation if (iter == 0) { tech = tech_lo; if (tech_lo == tech_hi) { curr_alpha = 1; } else { curr_alpha = (technology - tech_hi)/(tech_lo - tech_hi); } } else { tech = tech_hi; if (tech_lo == tech_hi) { break; } else { curr_alpha = (tech_lo - technology)/(tech_lo - tech_hi); } } if (tech == 180) { //180nm technology-node. Corresponds to year 1999 in ITRS //Only HP transistor was of interest that 180nm since leakage power was not a big issue. Performance was the king //MASTAR does not contain data for 0.18um process. The following parameters are projected based on ITRS 2000 update and IBM 0.18 Cu Spice input //180nm does not support DVS bool Aggre_proj = false; SENSE_AMP_D = .28e-9; // s SENSE_AMP_P = 14.7e-15; // J vdd[0] = 1.5; vdd_real[0] = g_ip->specific_hp_vdd ? g_ip->hp_Vdd : vdd[0]; alpha_power_law[0]=1.4; Lphy[0] = 0.12;//Lphy is the physical gate-length. micron Lelec[0] = 0.10;//Lelec is the electrical gate-length. micron t_ox[0] = 1.2e-3*(Aggre_proj? 1.9/1.2:2);//micron v_th[0] = Aggre_proj? 0.36 : 0.4407;//V c_ox[0] = 1.79e-14*(Aggre_proj? 1.9/1.2:2);//F/micron2 mobility_eff[0] = 302.16 * (1e-2 * 1e6 * 1e-2 * 1e6); //micron2 / Vs Vdsat[0] = 0.128*2; //V c_g_ideal[0] = (Aggre_proj? 1.9/1.2:2)*6.64e-16;//F/micron c_fringe[0] = (Aggre_proj? 1.9/1.2:2)*0.08e-15;//F/micron c_junc[0] = (Aggre_proj? 1.9/1.2:2)*1e-15;//F/micron2 I_on_n[0] = 750e-6*pow((vdd_real[0]-v_th[0])/(vdd[0]-v_th[0]),alpha_power_law[0]);//A/micron I_on_p[0] = 350e-6;//A/micron //Note that nmos_effective_resistance_multiplier, n_to_p_eff_curr_drv_ratio and gmp_to_gmn_multiplier values are calculated offline nmos_effective_resistance_multiplier = 1.54; n_to_p_eff_curr_drv_ratio[0] = 2.45; gmp_to_gmn_multiplier[0] = 1.22; Rnchannelon[0] = nmos_effective_resistance_multiplier * vdd[0] / I_on_n[0];//ohm-micron Rpchannelon[0] = n_to_p_eff_curr_drv_ratio[0] * Rnchannelon[0];//ohm-micron long_channel_leakage_reduction[0] = 1; I_off_n[0][0] = 7e-10;//A/micron I_off_n[0][10] = 8.26e-10; I_off_n[0][20] = 9.74e-10; I_off_n[0][30] = 1.15e-9; I_off_n[0][40] = 1.35e-9; I_off_n[0][50] = 1.60e-9; I_off_n[0][60] = 1.88e-9; I_off_n[0][70] = 2.29e-9; I_off_n[0][80] = 2.70e-9; I_off_n[0][90] = 3.19e-9; I_off_n[0][100] = 3.76e-9; I_g_on_n[0][0] = 1.65e-10;//A/micron I_g_on_n[0][10] = 1.65e-10; I_g_on_n[0][20] = 1.65e-10; I_g_on_n[0][30] = 1.65e-10; I_g_on_n[0][40] = 1.65e-10; I_g_on_n[0][50] = 1.65e-10; I_g_on_n[0][60] = 1.65e-10; I_g_on_n[0][70] = 1.65e-10; I_g_on_n[0][80] = 1.65e-10; I_g_on_n[0][90] = 1.65e-10; I_g_on_n[0][100] = 1.65e-10; //SRAM cell properties curr_Wmemcella_sram = 1.31 * g_ip->F_sz_um; curr_Wmemcellpmos_sram = 1.23 * g_ip->F_sz_um; curr_Wmemcellnmos_sram = 2.08 * g_ip->F_sz_um; curr_area_cell_sram = 146 * g_ip->F_sz_um * g_ip->F_sz_um; curr_asp_ratio_cell_sram = 1.46; //CAM cell properties //TODO: data need to be revisited curr_Wmemcella_cam = 1.31 * g_ip->F_sz_um; curr_Wmemcellpmos_cam = 1.23 * g_ip->F_sz_um; curr_Wmemcellnmos_cam = 2.08 * g_ip->F_sz_um; curr_area_cell_cam = 292 * g_ip->F_sz_um * g_ip->F_sz_um;//360 curr_asp_ratio_cell_cam = 2.92;//2.5 //Empirical undifferetiated core/FU coefficient curr_logic_scaling_co_eff = 1.5;//linear scaling from 90nm curr_core_tx_density = 1.25*0.7*0.7*0.4; curr_sckt_co_eff = 1.11; curr_chip_layout_overhead = 1.0;//die measurement results based on Niagara 1 and 2 curr_macro_layout_overhead = 1.0;//EDA placement and routing tool rule of thumb } if (tech == 90) { SENSE_AMP_D = .28e-9; // s SENSE_AMP_P = 14.7e-15; // J //90nm technology-node. Corresponds to year 2004 in ITRS //ITRS HP device type vdd[0] = 1.2; vdd_real[0] = g_ip->specific_hp_vdd ? g_ip->hp_Vdd : vdd[0]; alpha_power_law[0]=1.34; Lphy[0] = 0.037;//Lphy is the physical gate-length. micron Lelec[0] = 0.0266;//Lelec is the electrical gate-length. micron t_ox[0] = 1.2e-3;//micron v_th[0] = 0.23707;//V c_ox[0] = 1.79e-14;//F/micron2 mobility_eff[0] = 342.16 * (1e-2 * 1e6 * 1e-2 * 1e6); //micron2 / Vs Vdsat[0] = 0.128; //V c_g_ideal[0] = 6.64e-16;//F/micron c_fringe[0] = 0.08e-15;//F/micron c_junc[0] = 1e-15;//F/micron2 I_on_n[0] = 1076.9e-6*pow((vdd_real[0]-v_th[0])/(vdd[0]-v_th[0]),alpha_power_law[0]);//A/micron with ap-law applied for dvs and arbitrary vdd I_on_p[0] = 712.6e-6;//A/micron //Note that nmos_effective_resistance_multiplier, n_to_p_eff_curr_drv_ratio and gmp_to_gmn_multiplier values are calculated offline nmos_effective_resistance_multiplier = 1.54; n_to_p_eff_curr_drv_ratio[0] = 2.45; gmp_to_gmn_multiplier[0] = 1.22; Rnchannelon[0] = nmos_effective_resistance_multiplier * vdd_real[0] / I_on_n[0];//ohm-micron Rpchannelon[0] = n_to_p_eff_curr_drv_ratio[0] * Rnchannelon[0];//ohm-micron long_channel_leakage_reduction[0] = 1; I_off_n[0][0] = 3.24e-8*pow(vdd_real[0]/(vdd[0]),4);//A/micron I_off_n[0][10] = 4.01e-8*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][20] = 4.90e-8*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][30] = 5.92e-8*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][40] = 7.08e-8*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][50] = 8.38e-8*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][60] = 9.82e-8*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][70] = 1.14e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][80] = 1.29e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][90] = 1.43e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][100] = 1.54e-7*pow(vdd_real[0]/(vdd[0]),4); I_g_on_n[0][0] = 1.65e-8;//A/micron I_g_on_n[0][10] = 1.65e-8; I_g_on_n[0][20] = 1.65e-8; I_g_on_n[0][30] = 1.65e-8; I_g_on_n[0][40] = 1.65e-8; I_g_on_n[0][50] = 1.65e-8; I_g_on_n[0][60] = 1.65e-8; I_g_on_n[0][70] = 1.65e-8; I_g_on_n[0][80] = 1.65e-8; I_g_on_n[0][90] = 1.65e-8; I_g_on_n[0][100] = 1.65e-8; //ITRS LSTP device type vdd[1] = 1.3; vdd_real[1] = g_ip->specific_lstp_vdd ? g_ip->lstp_Vdd : vdd[1]; alpha_power_law[1]=1.47; Lphy[1] = 0.075; Lelec[1] = 0.0486; t_ox[1] = 2.2e-3; v_th[1] = 0.48203; c_ox[1] = 1.22e-14; mobility_eff[1] = 356.76 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[1] = 0.373; c_g_ideal[1] = 9.15e-16; c_fringe[1] = 0.08e-15; c_junc[1] = 1e-15; I_on_n[1] = 503.6e-6*pow((vdd_real[1]-v_th[1])/(vdd[1]-v_th[1]),alpha_power_law[1]); I_on_p[1] = 235.1e-6; nmos_effective_resistance_multiplier = 1.92; n_to_p_eff_curr_drv_ratio[1] = 2.44; gmp_to_gmn_multiplier[1] =0.88; Rnchannelon[1] = nmos_effective_resistance_multiplier * vdd_real[1] / I_on_n[1]; Rpchannelon[1] = n_to_p_eff_curr_drv_ratio[1] * Rnchannelon[1]; long_channel_leakage_reduction[1] = 1; I_off_n[1][0] = 2.81e-12*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][10] = 4.76e-12*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][20] = 7.82e-12*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][30] = 1.25e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][40] = 1.94e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][50] = 2.94e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][60] = 4.36e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][70] = 6.32e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][80] = 8.95e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][90] = 1.25e-10*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][100] = 1.7e-10*pow(vdd_real[1]/(vdd[1]),4); I_g_on_n[1][0] = 3.87e-11;//A/micron I_g_on_n[1][10] = 3.87e-11; I_g_on_n[1][20] = 3.87e-11; I_g_on_n[1][30] = 3.87e-11; I_g_on_n[1][40] = 3.87e-11; I_g_on_n[1][50] = 3.87e-11; I_g_on_n[1][60] = 3.87e-11; I_g_on_n[1][70] = 3.87e-11; I_g_on_n[1][80] = 3.87e-11; I_g_on_n[1][90] = 3.87e-11; I_g_on_n[1][100] = 3.87e-11; //ITRS LOP device type vdd[2] = 0.9; vdd_real[2] = g_ip->specific_lop_vdd ? g_ip->lop_Vdd : vdd[2]; alpha_power_law[2]=1.55; Lphy[2] = 0.053; Lelec[2] = 0.0354; t_ox[2] = 1.5e-3; v_th[2] = 0.30764; c_ox[2] = 1.59e-14; mobility_eff[2] = 460.39 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[2] = 0.113; c_g_ideal[2] = 8.45e-16; c_fringe[2] = 0.08e-15; c_junc[2] = 1e-15; I_on_n[2] = 386.6e-6*pow((vdd_real[2]-v_th[2])/(vdd[2]-v_th[2]),alpha_power_law[2]); I_on_p[2] = 209.7e-6; nmos_effective_resistance_multiplier = 1.77; n_to_p_eff_curr_drv_ratio[2] = 2.54; gmp_to_gmn_multiplier[2] = 0.98; Rnchannelon[2] = nmos_effective_resistance_multiplier * vdd_real[2] / I_on_n[2]; Rpchannelon[2] = n_to_p_eff_curr_drv_ratio[2] * Rnchannelon[2]; long_channel_leakage_reduction[2] = 1; I_off_n[2][0] = 2.14e-9*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][10] = 2.9e-9*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][20] = 3.87e-9*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][30] = 5.07e-9*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][40] = 6.54e-9*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][50] = 8.27e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][60] = 1.02e-7*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][70] = 1.20e-7*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][80] = 1.36e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][90] = 1.52e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][100] = 1.73e-8*pow(vdd_real[2]/(vdd[2]),5); I_g_on_n[2][0] = 4.31e-8;//A/micron I_g_on_n[2][10] = 4.31e-8; I_g_on_n[2][20] = 4.31e-8; I_g_on_n[2][30] = 4.31e-8; I_g_on_n[2][40] = 4.31e-8; I_g_on_n[2][50] = 4.31e-8; I_g_on_n[2][60] = 4.31e-8; I_g_on_n[2][70] = 4.31e-8; I_g_on_n[2][80] = 4.31e-8; I_g_on_n[2][90] = 4.31e-8; I_g_on_n[2][100] = 4.31e-8; if (ram_cell_tech_type == lp_dram) { //LP-DRAM cell access transistor technology parameters curr_vdd_dram_cell = 1.2; Lphy[3] = 0.12; Lelec[3] = 0.0756; curr_v_th_dram_access_transistor = 0.4545; width_dram_access_transistor = 0.14; curr_I_on_dram_cell = 45e-6; curr_I_off_dram_cell_worst_case_length_temp = 21.1e-12; curr_Wmemcella_dram = width_dram_access_transistor; curr_Wmemcellpmos_dram = 0; curr_Wmemcellnmos_dram = 0; curr_area_cell_dram = 0.168; curr_asp_ratio_cell_dram = 1.46; curr_c_dram_cell = 20e-15; //LP-DRAM wordline transistor parameters curr_vpp = 1.6; t_ox[3] = 2.2e-3; v_th[3] = 0.4545; c_ox[3] = 1.22e-14; mobility_eff[3] = 323.95 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[3] = 0.3; c_g_ideal[3] = 1.47e-15; c_fringe[3] = 0.08e-15; c_junc[3] = 1e-15; I_on_n[3] = 321.6e-6; I_on_p[3] = 203.3e-6; nmos_effective_resistance_multiplier = 1.65; n_to_p_eff_curr_drv_ratio[3] = 1.95; gmp_to_gmn_multiplier[3] = 0.90; Rnchannelon[3] = nmos_effective_resistance_multiplier * curr_vpp / I_on_n[3]; Rpchannelon[3] = n_to_p_eff_curr_drv_ratio[3] * Rnchannelon[3]; long_channel_leakage_reduction[3] = 1; I_off_n[3][0] = 1.42e-11; I_off_n[3][10] = 2.25e-11; I_off_n[3][20] = 3.46e-11; I_off_n[3][30] = 5.18e-11; I_off_n[3][40] = 7.58e-11; I_off_n[3][50] = 1.08e-10; I_off_n[3][60] = 1.51e-10; I_off_n[3][70] = 2.02e-10; I_off_n[3][80] = 2.57e-10; I_off_n[3][90] = 3.14e-10; I_off_n[3][100] = 3.85e-10; } else if (ram_cell_tech_type == comm_dram) { //COMM-DRAM cell access transistor technology parameters curr_vdd_dram_cell = 1.6; Lphy[3] = 0.09; Lelec[3] = 0.0576; curr_v_th_dram_access_transistor = 1; width_dram_access_transistor = 0.09; curr_I_on_dram_cell = 20e-6; curr_I_off_dram_cell_worst_case_length_temp = 1e-15; curr_Wmemcella_dram = width_dram_access_transistor; curr_Wmemcellpmos_dram = 0; curr_Wmemcellnmos_dram = 0; curr_area_cell_dram = 6*0.09*0.09; curr_asp_ratio_cell_dram = 1.5; curr_c_dram_cell = 30e-15; //COMM-DRAM wordline transistor parameters curr_vpp = 3.7; t_ox[3] = 5.5e-3; v_th[3] = 1.0; c_ox[3] = 5.65e-15; mobility_eff[3] = 302.2 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[3] = 0.32; c_g_ideal[3] = 5.08e-16; c_fringe[3] = 0.08e-15; c_junc[3] = 1e-15; I_on_n[3] = 1094.3e-6; I_on_p[3] = I_on_n[3] / 2; nmos_effective_resistance_multiplier = 1.62; n_to_p_eff_curr_drv_ratio[3] = 2.05; gmp_to_gmn_multiplier[3] = 0.90; Rnchannelon[3] = nmos_effective_resistance_multiplier * curr_vpp / I_on_n[3]; Rpchannelon[3] = n_to_p_eff_curr_drv_ratio[3] * Rnchannelon[3]; long_channel_leakage_reduction[3] = 1; I_off_n[3][0] = 5.80e-15; I_off_n[3][10] = 1.21e-14; I_off_n[3][20] = 2.42e-14; I_off_n[3][30] = 4.65e-14; I_off_n[3][40] = 8.60e-14; I_off_n[3][50] = 1.54e-13; I_off_n[3][60] = 2.66e-13; I_off_n[3][70] = 4.45e-13; I_off_n[3][80] = 7.17e-13; I_off_n[3][90] = 1.11e-12; I_off_n[3][100] = 1.67e-12; } //SRAM cell properties curr_Wmemcella_sram = 1.31 * g_ip->F_sz_um; curr_Wmemcellpmos_sram = 1.23 * g_ip->F_sz_um; curr_Wmemcellnmos_sram = 2.08 * g_ip->F_sz_um; curr_area_cell_sram = 146 * g_ip->F_sz_um * g_ip->F_sz_um; curr_asp_ratio_cell_sram = 1.46; //CAM cell properties //TODO: data need to be revisited curr_Wmemcella_cam = 1.31 * g_ip->F_sz_um; curr_Wmemcellpmos_cam = 1.23 * g_ip->F_sz_um; curr_Wmemcellnmos_cam = 2.08 * g_ip->F_sz_um; curr_area_cell_cam = 292 * g_ip->F_sz_um * g_ip->F_sz_um;//360 curr_asp_ratio_cell_cam = 2.92;//2.5 //Empirical undifferetiated core/FU coefficient curr_logic_scaling_co_eff = 1; curr_core_tx_density = 1.25*0.7*0.7; curr_sckt_co_eff = 1.1539; curr_chip_layout_overhead = 1.2;//die measurement results based on Niagara 1 and 2 curr_macro_layout_overhead = 1.1;//EDA placement and routing tool rule of thumb } if (tech == 65) { //65nm technology-node. Corresponds to year 2007 in ITRS //ITRS HP device type SENSE_AMP_D = .2e-9; // s SENSE_AMP_P = 5.7e-15; // J vdd[0] = 1.1; vdd_real[0] = g_ip->specific_hp_vdd ? g_ip->hp_Vdd : vdd[0]; alpha_power_law[0]=1.27; Lphy[0] = 0.025; Lelec[0] = 0.019; t_ox[0] = 1.1e-3; v_th[0] = .19491; c_ox[0] = 1.88e-14; mobility_eff[0] = 436.24 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[0] = 7.71e-2; c_g_ideal[0] = 4.69e-16; c_fringe[0] = 0.077e-15; c_junc[0] = 1e-15; I_on_n[0] = 1197.2e-6*pow((vdd_real[0]-v_th[0])/(vdd[0]-v_th[0]),alpha_power_law[0]); I_on_p[0] = 870.8e-6; nmos_effective_resistance_multiplier = 1.50; n_to_p_eff_curr_drv_ratio[0] = 2.41; gmp_to_gmn_multiplier[0] = 1.38; Rnchannelon[0] = nmos_effective_resistance_multiplier * vdd_real[0] / I_on_n[0]; Rpchannelon[0] = n_to_p_eff_curr_drv_ratio[0] * Rnchannelon[0]; long_channel_leakage_reduction[0] = 1/3.74; //Using MASTAR, @380K, increase Lgate until Ion reduces to 90% or Lgate increase by 10%, whichever comes first //Ioff(Lgate normal)/Ioff(Lgate long)= 3.74. I_off_n[0][0] = 1.96e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][10] = 2.29e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][20] = 2.66e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][30] = 3.05e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][40] = 3.49e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][50] = 3.95e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][60] = 4.45e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][70] = 4.97e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][80] = 5.48e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][90] = 5.94e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][100] = 6.3e-7*pow(vdd_real[0]/(vdd[0]),4); I_g_on_n[0][0] = 4.09e-8;//A/micron I_g_on_n[0][10] = 4.09e-8; I_g_on_n[0][20] = 4.09e-8; I_g_on_n[0][30] = 4.09e-8; I_g_on_n[0][40] = 4.09e-8; I_g_on_n[0][50] = 4.09e-8; I_g_on_n[0][60] = 4.09e-8; I_g_on_n[0][70] = 4.09e-8; I_g_on_n[0][80] = 4.09e-8; I_g_on_n[0][90] = 4.09e-8; I_g_on_n[0][100] = 4.09e-8; //ITRS LSTP device type vdd[1] = 1.2; vdd_real[1] = g_ip->specific_lstp_vdd ? g_ip->lstp_Vdd : vdd[1];//TODO alpha_power_law[1]=1.40; Lphy[1] = 0.045; Lelec[1] = 0.0298; t_ox[1] = 1.9e-3; v_th[1] = 0.52354; c_ox[1] = 1.36e-14; mobility_eff[1] = 341.21 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[1] = 0.128; c_g_ideal[1] = 6.14e-16; c_fringe[1] = 0.08e-15; c_junc[1] = 1e-15; I_on_n[1] = 519.2e-6*pow((vdd_real[1]-v_th[1])/(vdd[1]-v_th[1]),alpha_power_law[1]); I_on_p[1] = 266e-6; nmos_effective_resistance_multiplier = 1.96; n_to_p_eff_curr_drv_ratio[1] = 2.23; gmp_to_gmn_multiplier[1] = 0.99; Rnchannelon[1] = nmos_effective_resistance_multiplier * vdd_real[1] / I_on_n[1]; Rpchannelon[1] = n_to_p_eff_curr_drv_ratio[1] * Rnchannelon[1]; long_channel_leakage_reduction[1] = 1/2.82; I_off_n[1][0] = 9.12e-12*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][10] = 1.49e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][20] = 2.36e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][30] = 3.64e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][40] = 5.48e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][50] = 8.05e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][60] = 1.15e-10*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][70] = 1.59e-10*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][80] = 2.1e-10*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][90] = 2.62e-10*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][100] = 3.21e-10*pow(vdd_real[1]/(vdd[1]),4); I_g_on_n[1][0] = 1.09e-10;//A/micron I_g_on_n[1][10] = 1.09e-10; I_g_on_n[1][20] = 1.09e-10; I_g_on_n[1][30] = 1.09e-10; I_g_on_n[1][40] = 1.09e-10; I_g_on_n[1][50] = 1.09e-10; I_g_on_n[1][60] = 1.09e-10; I_g_on_n[1][70] = 1.09e-10; I_g_on_n[1][80] = 1.09e-10; I_g_on_n[1][90] = 1.09e-10; I_g_on_n[1][100] = 1.09e-10; //ITRS LOP device type vdd[2] = 0.8; alpha_power_law[2]=1.43; vdd_real[2] = g_ip->specific_lop_vdd ? g_ip->lop_Vdd : vdd[2]; Lphy[2] = 0.032; Lelec[2] = 0.0216; t_ox[2] = 1.2e-3; v_th[2] = 0.28512; c_ox[2] = 1.87e-14; mobility_eff[2] = 495.19 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[2] = 0.292; c_g_ideal[2] = 6e-16; c_fringe[2] = 0.08e-15; c_junc[2] = 1e-15; I_on_n[2] = 573.1e-6*pow((vdd_real[2]-v_th[2])/(vdd[2]-v_th[2]),alpha_power_law[2]); I_on_p[2] = 340.6e-6; nmos_effective_resistance_multiplier = 1.82; n_to_p_eff_curr_drv_ratio[2] = 2.28; gmp_to_gmn_multiplier[2] = 1.11; Rnchannelon[2] = nmos_effective_resistance_multiplier * vdd_real[2] / I_on_n[2]; Rpchannelon[2] = n_to_p_eff_curr_drv_ratio[2] * Rnchannelon[2]; long_channel_leakage_reduction[2] = 1/2.05; I_off_n[2][0] = 4.9e-9*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][10] = 6.49e-9*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][20] = 8.45e-9*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][30] = 1.08e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][40] = 1.37e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][50] = 1.71e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][60] = 2.09e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][70] = 2.48e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][80] = 2.84e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][90] = 3.13e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][100] = 3.42e-8*pow(vdd_real[2]/(vdd[2]),5); I_g_on_n[2][0] = 9.61e-9;//A/micron I_g_on_n[2][10] = 9.61e-9; I_g_on_n[2][20] = 9.61e-9; I_g_on_n[2][30] = 9.61e-9; I_g_on_n[2][40] = 9.61e-9; I_g_on_n[2][50] = 9.61e-9; I_g_on_n[2][60] = 9.61e-9; I_g_on_n[2][70] = 9.61e-9; I_g_on_n[2][80] = 9.61e-9; I_g_on_n[2][90] = 9.61e-9; I_g_on_n[2][100] = 9.61e-9; if (ram_cell_tech_type == lp_dram) { //LP-DRAM cell access transistor technology parameters curr_vdd_dram_cell = 1.2; Lphy[3] = 0.12; Lelec[3] = 0.0756; curr_v_th_dram_access_transistor = 0.43806; width_dram_access_transistor = 0.09; curr_I_on_dram_cell = 36e-6; curr_I_off_dram_cell_worst_case_length_temp = 19.6e-12; curr_Wmemcella_dram = width_dram_access_transistor; curr_Wmemcellpmos_dram = 0; curr_Wmemcellnmos_dram = 0; curr_area_cell_dram = 0.11; curr_asp_ratio_cell_dram = 1.46; curr_c_dram_cell = 20e-15; //LP-DRAM wordline transistor parameters curr_vpp = 1.6; t_ox[3] = 2.2e-3; v_th[3] = 0.43806; c_ox[3] = 1.22e-14; mobility_eff[3] = 328.32 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[3] = 0.43806; c_g_ideal[3] = 1.46e-15; c_fringe[3] = 0.08e-15; c_junc[3] = 1e-15 ; I_on_n[3] = 399.8e-6; I_on_p[3] = 243.4e-6; nmos_effective_resistance_multiplier = 1.65; n_to_p_eff_curr_drv_ratio[3] = 2.05; gmp_to_gmn_multiplier[3] = 0.90; Rnchannelon[3] = nmos_effective_resistance_multiplier * curr_vpp / I_on_n[3]; Rpchannelon[3] = n_to_p_eff_curr_drv_ratio[3] * Rnchannelon[3]; long_channel_leakage_reduction[3] = 1; I_off_n[3][0] = 2.23e-11; I_off_n[3][10] = 3.46e-11; I_off_n[3][20] = 5.24e-11; I_off_n[3][30] = 7.75e-11; I_off_n[3][40] = 1.12e-10; I_off_n[3][50] = 1.58e-10; I_off_n[3][60] = 2.18e-10; I_off_n[3][70] = 2.88e-10; I_off_n[3][80] = 3.63e-10; I_off_n[3][90] = 4.41e-10; I_off_n[3][100] = 5.36e-10; } else if (ram_cell_tech_type == comm_dram) { //COMM-DRAM cell access transistor technology parameters curr_vdd_dram_cell = 1.3; Lphy[3] = 0.065; Lelec[3] = 0.0426; curr_v_th_dram_access_transistor = 1; width_dram_access_transistor = 0.065; curr_I_on_dram_cell = 20e-6; curr_I_off_dram_cell_worst_case_length_temp = 1e-15; curr_Wmemcella_dram = width_dram_access_transistor; curr_Wmemcellpmos_dram = 0; curr_Wmemcellnmos_dram = 0; curr_area_cell_dram = 6*0.065*0.065; curr_asp_ratio_cell_dram = 1.5; curr_c_dram_cell = 30e-15; //COMM-DRAM wordline transistor parameters curr_vpp = 3.3; t_ox[3] = 5e-3; v_th[3] = 1.0; c_ox[3] = 6.16e-15; mobility_eff[3] = 303.44 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[3] = 0.385; c_g_ideal[3] = 4e-16; c_fringe[3] = 0.08e-15; c_junc[3] = 1e-15 ; I_on_n[3] = 1031e-6; I_on_p[3] = I_on_n[3] / 2; nmos_effective_resistance_multiplier = 1.69; n_to_p_eff_curr_drv_ratio[3] = 2.39; gmp_to_gmn_multiplier[3] = 0.90; Rnchannelon[3] = nmos_effective_resistance_multiplier * curr_vpp / I_on_n[3]; Rpchannelon[3] = n_to_p_eff_curr_drv_ratio[3] * Rnchannelon[3]; long_channel_leakage_reduction[3] = 1; I_off_n[3][0] = 1.80e-14; I_off_n[3][10] = 3.64e-14; I_off_n[3][20] = 7.03e-14; I_off_n[3][30] = 1.31e-13; I_off_n[3][40] = 2.35e-13; I_off_n[3][50] = 4.09e-13; I_off_n[3][60] = 6.89e-13; I_off_n[3][70] = 1.13e-12; I_off_n[3][80] = 1.78e-12; I_off_n[3][90] = 2.71e-12; I_off_n[3][100] = 3.99e-12; } //SRAM cell properties curr_Wmemcella_sram = 1.31 * g_ip->F_sz_um; curr_Wmemcellpmos_sram = 1.23 * g_ip->F_sz_um; curr_Wmemcellnmos_sram = 2.08 * g_ip->F_sz_um; curr_area_cell_sram = 146 * g_ip->F_sz_um * g_ip->F_sz_um; curr_asp_ratio_cell_sram = 1.46; //CAM cell properties //TODO: data need to be revisited curr_Wmemcella_cam = 1.31 * g_ip->F_sz_um; curr_Wmemcellpmos_cam = 1.23 * g_ip->F_sz_um; curr_Wmemcellnmos_cam = 2.08 * g_ip->F_sz_um; curr_area_cell_cam = 292 * g_ip->F_sz_um * g_ip->F_sz_um; curr_asp_ratio_cell_cam = 2.92; //Empirical undifferetiated core/FU coefficient curr_logic_scaling_co_eff = 0.7; //Rather than scale proportionally to square of feature size, only scale linearly according to IBM cell processor curr_core_tx_density = 1.25*0.7; curr_sckt_co_eff = 1.1359; curr_chip_layout_overhead = 1.2;//die measurement results based on Niagara 1 and 2 curr_macro_layout_overhead = 1.1;//EDA placement and routing tool rule of thumb } if (tech == 45) { //45nm technology-node. Corresponds to year 2010 in ITRS //ITRS HP device type SENSE_AMP_D = .04e-9; // s SENSE_AMP_P = 2.7e-15; // J vdd[0] = 1.0; vdd_real[0] = g_ip->specific_hp_vdd ? g_ip->hp_Vdd : vdd[0];//TODO alpha_power_law[0]=1.21; Lphy[0] = 0.018; Lelec[0] = 0.01345; t_ox[0] = 0.65e-3; v_th[0] = .18035; c_ox[0] = 3.77e-14; mobility_eff[0] = 266.68 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[0] = 9.38E-2; c_g_ideal[0] = 6.78e-16; c_fringe[0] = 0.05e-15; c_junc[0] = 1e-15; I_on_n[0] = 2046.6e-6*pow((vdd_real[0]-v_th[0])/(vdd[0]-v_th[0]),alpha_power_law[0]); //There are certain problems with the ITRS PMOS numbers in MASTAR for 45nm. So we are using 65nm values of //n_to_p_eff_curr_drv_ratio and gmp_to_gmn_multiplier for 45nm I_on_p[0] = I_on_n[0] / 2;//This value is fixed arbitrarily but I_on_p is not being used in CACTI nmos_effective_resistance_multiplier = 1.51; n_to_p_eff_curr_drv_ratio[0] = 2.41; gmp_to_gmn_multiplier[0] = 1.38; Rnchannelon[0] = nmos_effective_resistance_multiplier * vdd_real[0] / I_on_n[0]; Rpchannelon[0] = n_to_p_eff_curr_drv_ratio[0] * Rnchannelon[0]; long_channel_leakage_reduction[0] = 1/3.546;//Using MASTAR, @380K, increase Lgate until Ion reduces to 90%, Ioff(Lgate normal)/Ioff(Lgate long)= 3.74 I_off_n[0][0] = 2.8e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][10] = 3.28e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][20] = 3.81e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][30] = 4.39e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][40] = 5.02e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][50] = 5.69e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][60] = 6.42e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][70] = 7.2e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][80] = 8.03e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][90] = 8.91e-7*pow(vdd_real[0]/(vdd[0]),4); I_off_n[0][100] = 9.84e-7*pow(vdd_real[0]/(vdd[0]),4); I_g_on_n[0][0] = 3.59e-8;//A/micron I_g_on_n[0][10] = 3.59e-8; I_g_on_n[0][20] = 3.59e-8; I_g_on_n[0][30] = 3.59e-8; I_g_on_n[0][40] = 3.59e-8; I_g_on_n[0][50] = 3.59e-8; I_g_on_n[0][60] = 3.59e-8; I_g_on_n[0][70] = 3.59e-8; I_g_on_n[0][80] = 3.59e-8; I_g_on_n[0][90] = 3.59e-8; I_g_on_n[0][100] = 3.59e-8; //ITRS LSTP device type vdd[1] = 1.1; vdd_real[1] = g_ip->specific_lstp_vdd ? g_ip->lstp_Vdd : vdd[1]; alpha_power_law[1]=1.33; Lphy[1] = 0.028; Lelec[1] = 0.0212; t_ox[1] = 1.4e-3; v_th[1] = 0.50245; c_ox[1] = 2.01e-14; mobility_eff[1] = 363.96 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[1] = 9.12e-2; c_g_ideal[1] = 5.18e-16; c_fringe[1] = 0.08e-15; c_junc[1] = 1e-15; I_on_n[1] = 666.2e-6*pow((vdd_real[1]-v_th[1])/(vdd[1]-v_th[1]),alpha_power_law[1]); I_on_p[1] = I_on_n[1] / 2; nmos_effective_resistance_multiplier = 1.99; n_to_p_eff_curr_drv_ratio[1] = 2.23; gmp_to_gmn_multiplier[1] = 0.99; Rnchannelon[1] = nmos_effective_resistance_multiplier * vdd_real[1] / I_on_n[1]; Rpchannelon[1] = n_to_p_eff_curr_drv_ratio[1] * Rnchannelon[1]; long_channel_leakage_reduction[1] = 1/2.08; I_off_n[1][0] = 1.01e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][10] = 1.65e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][20] = 2.62e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][30] = 4.06e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][40] = 6.12e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][50] = 9.02e-11*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][60] = 1.3e-10*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][70] = 1.83e-10*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][80] = 2.51e-10*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][90] = 3.29e-10*pow(vdd_real[1]/(vdd[1]),4); I_off_n[1][100] = 4.1e-10*pow(vdd_real[1]/(vdd[1]),4); I_g_on_n[1][0] = 9.47e-12;//A/micron I_g_on_n[1][10] = 9.47e-12; I_g_on_n[1][20] = 9.47e-12; I_g_on_n[1][30] = 9.47e-12; I_g_on_n[1][40] = 9.47e-12; I_g_on_n[1][50] = 9.47e-12; I_g_on_n[1][60] = 9.47e-12; I_g_on_n[1][70] = 9.47e-12; I_g_on_n[1][80] = 9.47e-12; I_g_on_n[1][90] = 9.47e-12; I_g_on_n[1][100] = 9.47e-12; //ITRS LOP device type vdd[2] = 0.7; vdd_real[2] = g_ip->specific_lop_vdd ? g_ip->lop_Vdd : vdd[2];//TODO alpha_power_law[2]=1.39; Lphy[2] = 0.022; Lelec[2] = 0.016; t_ox[2] = 0.9e-3; v_th[2] = 0.22599; c_ox[2] = 2.82e-14;//F/micron2 mobility_eff[2] = 508.9 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[2] = 5.71e-2; c_g_ideal[2] = 6.2e-16; c_fringe[2] = 0.073e-15; c_junc[2] = 1e-15; I_on_n[2] = 748.9e-6*pow((vdd_real[2]-v_th[2])/(vdd[2]-v_th[2]),alpha_power_law[2]); I_on_p[2] = I_on_n[2] / 2; nmos_effective_resistance_multiplier = 1.76; n_to_p_eff_curr_drv_ratio[2] = 2.28; gmp_to_gmn_multiplier[2] = 1.11; Rnchannelon[2] = nmos_effective_resistance_multiplier * vdd_real[2] / I_on_n[2]; Rpchannelon[2] = n_to_p_eff_curr_drv_ratio[2] * Rnchannelon[2]; long_channel_leakage_reduction[2] = 1/1.92; I_off_n[2][0] = 4.03e-9*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][10] = 5.02e-9*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][20] = 6.18e-9*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][30] = 7.51e-9*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][40] = 9.04e-9*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][50] = 1.08e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][60] = 1.27e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][70] = 1.47e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][80] = 1.66e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][90] = 1.84e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][100] = 2.03e-8*pow(vdd_real[2]/(vdd[2]),5); I_g_on_n[2][0] = 3.24e-8;//A/micron I_g_on_n[2][10] = 4.01e-8; I_g_on_n[2][20] = 4.90e-8; I_g_on_n[2][30] = 5.92e-8; I_g_on_n[2][40] = 7.08e-8; I_g_on_n[2][50] = 8.38e-8; I_g_on_n[2][60] = 9.82e-8; I_g_on_n[2][70] = 1.14e-7; I_g_on_n[2][80] = 1.29e-7; I_g_on_n[2][90] = 1.43e-7; I_g_on_n[2][100] = 1.54e-7; if (ram_cell_tech_type == lp_dram) { //LP-DRAM cell access transistor technology parameters curr_vdd_dram_cell = 1.1; Lphy[3] = 0.078; Lelec[3] = 0.0504;// Assume Lelec is 30% lesser than Lphy for DRAM access and wordline transistors. curr_v_th_dram_access_transistor = 0.44559; width_dram_access_transistor = 0.079; curr_I_on_dram_cell = 36e-6;//A curr_I_off_dram_cell_worst_case_length_temp = 19.5e-12; curr_Wmemcella_dram = width_dram_access_transistor; curr_Wmemcellpmos_dram = 0; curr_Wmemcellnmos_dram = 0; curr_area_cell_dram = width_dram_access_transistor * Lphy[3] * 10.0; curr_asp_ratio_cell_dram = 1.46; curr_c_dram_cell = 20e-15; //LP-DRAM wordline transistor parameters curr_vpp = 1.5; t_ox[3] = 2.1e-3; v_th[3] = 0.44559; c_ox[3] = 1.41e-14; mobility_eff[3] = 426.30 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[3] = 0.181; c_g_ideal[3] = 1.10e-15; c_fringe[3] = 0.08e-15; c_junc[3] = 1e-15; I_on_n[3] = 456e-6; I_on_p[3] = I_on_n[3] / 2; nmos_effective_resistance_multiplier = 1.65; n_to_p_eff_curr_drv_ratio[3] = 2.05; gmp_to_gmn_multiplier[3] = 0.90; Rnchannelon[3] = nmos_effective_resistance_multiplier * curr_vpp / I_on_n[3]; Rpchannelon[3] = n_to_p_eff_curr_drv_ratio[3] * Rnchannelon[3]; long_channel_leakage_reduction[3] = 1; I_off_n[3][0] = 2.54e-11; I_off_n[3][10] = 3.94e-11; I_off_n[3][20] = 5.95e-11; I_off_n[3][30] = 8.79e-11; I_off_n[3][40] = 1.27e-10; I_off_n[3][50] = 1.79e-10; I_off_n[3][60] = 2.47e-10; I_off_n[3][70] = 3.31e-10; I_off_n[3][80] = 4.26e-10; I_off_n[3][90] = 5.27e-10; I_off_n[3][100] = 6.46e-10; } else if (ram_cell_tech_type == comm_dram) { //COMM-DRAM cell access transistor technology parameters curr_vdd_dram_cell = 1.1; Lphy[3] = 0.045; Lelec[3] = 0.0298; curr_v_th_dram_access_transistor = 1; width_dram_access_transistor = 0.045; curr_I_on_dram_cell = 20e-6;//A curr_I_off_dram_cell_worst_case_length_temp = 1e-15; curr_Wmemcella_dram = width_dram_access_transistor; curr_Wmemcellpmos_dram = 0; curr_Wmemcellnmos_dram = 0; curr_area_cell_dram = 6*0.045*0.045; curr_asp_ratio_cell_dram = 1.5; curr_c_dram_cell = 30e-15; //COMM-DRAM wordline transistor parameters curr_vpp = 2.7; t_ox[3] = 4e-3; v_th[3] = 1.0; c_ox[3] = 7.98e-15; mobility_eff[3] = 368.58 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[3] = 0.147; c_g_ideal[3] = 3.59e-16; c_fringe[3] = 0.08e-15; c_junc[3] = 1e-15; I_on_n[3] = 999.4e-6; I_on_p[3] = I_on_n[3] / 2; nmos_effective_resistance_multiplier = 1.69; n_to_p_eff_curr_drv_ratio[3] = 1.95; gmp_to_gmn_multiplier[3] = 0.90; Rnchannelon[3] = nmos_effective_resistance_multiplier * curr_vpp / I_on_n[3]; Rpchannelon[3] = n_to_p_eff_curr_drv_ratio[3] * Rnchannelon[3]; long_channel_leakage_reduction[3] = 1; I_off_n[3][0] = 1.31e-14; I_off_n[3][10] = 2.68e-14; I_off_n[3][20] = 5.25e-14; I_off_n[3][30] = 9.88e-14; I_off_n[3][40] = 1.79e-13; I_off_n[3][50] = 3.15e-13; I_off_n[3][60] = 5.36e-13; I_off_n[3][70] = 8.86e-13; I_off_n[3][80] = 1.42e-12; I_off_n[3][90] = 2.20e-12; I_off_n[3][100] = 3.29e-12; } //SRAM cell properties curr_Wmemcella_sram = 1.31 * g_ip->F_sz_um; curr_Wmemcellpmos_sram = 1.23 * g_ip->F_sz_um; curr_Wmemcellnmos_sram = 2.08 * g_ip->F_sz_um; curr_area_cell_sram = 146 * g_ip->F_sz_um * g_ip->F_sz_um; curr_asp_ratio_cell_sram = 1.46; //CAM cell properties //TODO: data need to be revisited curr_Wmemcella_cam = 1.31 * g_ip->F_sz_um; curr_Wmemcellpmos_cam = 1.23 * g_ip->F_sz_um; curr_Wmemcellnmos_cam = 2.08 * g_ip->F_sz_um; curr_area_cell_cam = 292 * g_ip->F_sz_um * g_ip->F_sz_um; curr_asp_ratio_cell_cam = 2.92; //Empirical undifferetiated core/FU coefficient curr_logic_scaling_co_eff = 0.7*0.7; curr_core_tx_density = 1.25; curr_sckt_co_eff = 1.1387; curr_chip_layout_overhead = 1.2;//die measurement results based on Niagara 1 and 2 curr_macro_layout_overhead = 1.1;//EDA placement and routing tool rule of thumb } if (tech == 32) { SENSE_AMP_D = .03e-9; // s SENSE_AMP_P = 2.16e-15; // J //For 2013, MPU/ASIC stagger-contacted M1 half-pitch is 32 nm (so this is 32 nm //technology i.e. FEATURESIZE = 0.032). Using the SOI process numbers for //HP and LSTP. vdd[0] = 0.9; vdd_real[0] = g_ip->specific_hp_vdd ? g_ip->hp_Vdd : vdd[0]; alpha_power_law[0]=1.19; Lphy[0] = 0.013; Lelec[0] = 0.01013; t_ox[0] = 0.5e-3; v_th[0] = 0.21835; c_ox[0] = 4.11e-14; mobility_eff[0] = 361.84 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[0] = 5.09E-2; c_g_ideal[0] = 5.34e-16; c_fringe[0] = 0.04e-15; c_junc[0] = 1e-15; I_on_n[0] = 2211.7e-6*pow((vdd_real[0]-v_th[0])/(vdd[0]-v_th[0]),alpha_power_law[0]); I_on_p[0] = I_on_n[0] / 2; nmos_effective_resistance_multiplier = 1.49; n_to_p_eff_curr_drv_ratio[0] = 2.41; gmp_to_gmn_multiplier[0] = 1.38; Rnchannelon[0] = nmos_effective_resistance_multiplier * vdd_real[0] / I_on_n[0];//ohm-micron Rpchannelon[0] = n_to_p_eff_curr_drv_ratio[0] * Rnchannelon[0];//ohm-micron long_channel_leakage_reduction[0] = 1/3.706; //Using MASTAR, @300K (380K does not work in MASTAR), increase Lgate until Ion reduces to 95% or Lgate increase by 5% (DG device can only increase by 5%), //whichever comes first I_off_n[0][0] = 1.52e-7*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][10] = 1.55e-7*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][20] = 1.59e-7*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][30] = 1.68e-7*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][40] = 1.90e-7*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][50] = 2.69e-7*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][60] = 5.32e-7*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][70] = 1.02e-6*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][80] = 1.62e-6*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][90] = 2.73e-6*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][100] = 6.1e-6*pow(vdd_real[0]/(vdd[0]),2); I_g_on_n[0][0] = 6.55e-8;//A/micron I_g_on_n[0][10] = 6.55e-8; I_g_on_n[0][20] = 6.55e-8; I_g_on_n[0][30] = 6.55e-8; I_g_on_n[0][40] = 6.55e-8; I_g_on_n[0][50] = 6.55e-8; I_g_on_n[0][60] = 6.55e-8; I_g_on_n[0][70] = 6.55e-8; I_g_on_n[0][80] = 6.55e-8; I_g_on_n[0][90] = 6.55e-8; I_g_on_n[0][100] = 6.55e-8; // 32 DG // I_g_on_n[0][0] = 2.71e-9;//A/micron // I_g_on_n[0][10] = 2.71e-9; // I_g_on_n[0][20] = 2.71e-9; // I_g_on_n[0][30] = 2.71e-9; // I_g_on_n[0][40] = 2.71e-9; // I_g_on_n[0][50] = 2.71e-9; // I_g_on_n[0][60] = 2.71e-9; // I_g_on_n[0][70] = 2.71e-9; // I_g_on_n[0][80] = 2.71e-9; // I_g_on_n[0][90] = 2.71e-9; // I_g_on_n[0][100] = 2.71e-9; //LSTP device type vdd[1] = 1; vdd_real[1] = g_ip->specific_lstp_vdd ? g_ip->lstp_Vdd : vdd[1]; alpha_power_law[1]=1.27; Lphy[1] = 0.020; Lelec[1] = 0.0173; t_ox[1] = 1.2e-3; v_th[1] = 0.513; c_ox[1] = 2.29e-14; mobility_eff[1] = 347.46 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[1] = 8.64e-2; c_g_ideal[1] = 4.58e-16; c_fringe[1] = 0.053e-15; c_junc[1] = 1e-15; I_on_n[1] = 683.6e-6*pow((vdd_real[1]-v_th[1])/(vdd[1]-v_th[1]),alpha_power_law[1]); I_on_p[1] = I_on_n[1] / 2; nmos_effective_resistance_multiplier = 1.99; n_to_p_eff_curr_drv_ratio[1] = 2.23; gmp_to_gmn_multiplier[1] = 0.99; Rnchannelon[1] = nmos_effective_resistance_multiplier * vdd_real[1] / I_on_n[1]; Rpchannelon[1] = n_to_p_eff_curr_drv_ratio[1] * Rnchannelon[1]; long_channel_leakage_reduction[1] = 1/1.93; I_off_n[1][0] = 2.06e-11*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][10] = 3.30e-11*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][20] = 5.15e-11*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][30] = 7.83e-11*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][40] = 1.16e-10*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][50] = 1.69e-10*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][60] = 2.40e-10*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][70] = 3.34e-10*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][80] = 4.54e-10*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][90] = 5.96e-10*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][100] = 7.44e-10*pow(vdd_real[1]/(vdd[1]),1); I_g_on_n[1][0] = 3.73e-11;//A/micron I_g_on_n[1][10] = 3.73e-11; I_g_on_n[1][20] = 3.73e-11; I_g_on_n[1][30] = 3.73e-11; I_g_on_n[1][40] = 3.73e-11; I_g_on_n[1][50] = 3.73e-11; I_g_on_n[1][60] = 3.73e-11; I_g_on_n[1][70] = 3.73e-11; I_g_on_n[1][80] = 3.73e-11; I_g_on_n[1][90] = 3.73e-11; I_g_on_n[1][100] = 3.73e-11; //LOP device type vdd[2] = 0.6; vdd_real[2] = g_ip->specific_lop_vdd ? g_ip->lop_Vdd : vdd[2];//TODO alpha_power_law[2]=1.26; Lphy[2] = 0.016; Lelec[2] = 0.01232; t_ox[2] = 0.9e-3; v_th[2] = 0.24227; c_ox[2] = 2.84e-14; mobility_eff[2] = 513.52 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[2] = 4.64e-2; c_g_ideal[2] = 4.54e-16; c_fringe[2] = 0.057e-15; c_junc[2] = 1e-15; I_on_n[2] = 827.8e-6*pow((vdd_real[2]-v_th[2])/(vdd[2]-v_th[2]),alpha_power_law[2]); I_on_p[2] = I_on_n[2] / 2; nmos_effective_resistance_multiplier = 1.73; n_to_p_eff_curr_drv_ratio[2] = 2.28; gmp_to_gmn_multiplier[2] = 1.11; Rnchannelon[2] = nmos_effective_resistance_multiplier * vdd_real[2] / I_on_n[2]; Rpchannelon[2] = n_to_p_eff_curr_drv_ratio[2] * Rnchannelon[2]; long_channel_leakage_reduction[2] = 1/1.89; I_off_n[2][0] = 5.94e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][10] = 7.23e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][20] = 8.7e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][30] = 1.04e-7*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][40] = 1.22e-7*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][50] = 1.43e-7*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][60] = 1.65e-7*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][70] = 1.90e-7*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][80] = 2.15e-7*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][90] = 2.39e-7*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][100] = 2.63e-7*pow(vdd_real[2]/(vdd[2]),5); I_g_on_n[2][0] = 2.93e-9;//A/micron I_g_on_n[2][10] = 2.93e-9; I_g_on_n[2][20] = 2.93e-9; I_g_on_n[2][30] = 2.93e-9; I_g_on_n[2][40] = 2.93e-9; I_g_on_n[2][50] = 2.93e-9; I_g_on_n[2][60] = 2.93e-9; I_g_on_n[2][70] = 2.93e-9; I_g_on_n[2][80] = 2.93e-9; I_g_on_n[2][90] = 2.93e-9; I_g_on_n[2][100] = 2.93e-9; if (ram_cell_tech_type == lp_dram) { //LP-DRAM cell access transistor technology parameters curr_vdd_dram_cell = 1.0; Lphy[3] = 0.056; Lelec[3] = 0.0419;//Assume Lelec is 30% lesser than Lphy for DRAM access and wordline transistors. curr_v_th_dram_access_transistor = 0.44129; width_dram_access_transistor = 0.056; curr_I_on_dram_cell = 36e-6; curr_I_off_dram_cell_worst_case_length_temp = 18.9e-12; curr_Wmemcella_dram = width_dram_access_transistor; curr_Wmemcellpmos_dram = 0; curr_Wmemcellnmos_dram = 0; curr_area_cell_dram = width_dram_access_transistor * Lphy[3] * 10.0; curr_asp_ratio_cell_dram = 1.46; curr_c_dram_cell = 20e-15; //LP-DRAM wordline transistor parameters curr_vpp = 1.5; t_ox[3] = 2e-3; v_th[3] = 0.44467; c_ox[3] = 1.48e-14; mobility_eff[3] = 408.12 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[3] = 0.174; c_g_ideal[3] = 7.45e-16; c_fringe[3] = 0.053e-15; c_junc[3] = 1e-15; I_on_n[3] = 1055.4e-6; I_on_p[3] = I_on_n[3] / 2; nmos_effective_resistance_multiplier = 1.65; n_to_p_eff_curr_drv_ratio[3] = 2.05; gmp_to_gmn_multiplier[3] = 0.90; Rnchannelon[3] = nmos_effective_resistance_multiplier * curr_vpp / I_on_n[3]; Rpchannelon[3] = n_to_p_eff_curr_drv_ratio[3] * Rnchannelon[3]; long_channel_leakage_reduction[3] = 1; I_off_n[3][0] = 3.57e-11; I_off_n[3][10] = 5.51e-11; I_off_n[3][20] = 8.27e-11; I_off_n[3][30] = 1.21e-10; I_off_n[3][40] = 1.74e-10; I_off_n[3][50] = 2.45e-10; I_off_n[3][60] = 3.38e-10; I_off_n[3][70] = 4.53e-10; I_off_n[3][80] = 5.87e-10; I_off_n[3][90] = 7.29e-10; I_off_n[3][100] = 8.87e-10; } else if (ram_cell_tech_type == comm_dram) { //COMM-DRAM cell access transistor technology parameters curr_vdd_dram_cell = 1.0; Lphy[3] = 0.032; Lelec[3] = 0.0205;//Assume Lelec is 30% lesser than Lphy for DRAM access and wordline transistors. curr_v_th_dram_access_transistor = 1; width_dram_access_transistor = 0.032; curr_I_on_dram_cell = 20e-6; curr_I_off_dram_cell_worst_case_length_temp = 1e-15; curr_Wmemcella_dram = width_dram_access_transistor; curr_Wmemcellpmos_dram = 0; curr_Wmemcellnmos_dram = 0; curr_area_cell_dram = 6*0.032*0.032; curr_asp_ratio_cell_dram = 1.5; curr_c_dram_cell = 30e-15; //COMM-DRAM wordline transistor parameters curr_vpp = 2.6; t_ox[3] = 4e-3; v_th[3] = 1.0; c_ox[3] = 7.99e-15; mobility_eff[3] = 380.76 * (1e-2 * 1e6 * 1e-2 * 1e6); Vdsat[3] = 0.129; c_g_ideal[3] = 2.56e-16; c_fringe[3] = 0.053e-15; c_junc[3] = 1e-15; I_on_n[3] = 1024.5e-6; I_on_p[3] = I_on_n[3] / 2; nmos_effective_resistance_multiplier = 1.69; n_to_p_eff_curr_drv_ratio[3] = 1.95; gmp_to_gmn_multiplier[3] = 0.90; Rnchannelon[3] = nmos_effective_resistance_multiplier * curr_vpp / I_on_n[3]; Rpchannelon[3] = n_to_p_eff_curr_drv_ratio[3] * Rnchannelon[3]; long_channel_leakage_reduction[3] = 1; I_off_n[3][0] = 3.63e-14; I_off_n[3][10] = 7.18e-14; I_off_n[3][20] = 1.36e-13; I_off_n[3][30] = 2.49e-13; I_off_n[3][40] = 4.41e-13; I_off_n[3][50] = 7.55e-13; I_off_n[3][60] = 1.26e-12; I_off_n[3][70] = 2.03e-12; I_off_n[3][80] = 3.19e-12; I_off_n[3][90] = 4.87e-12; I_off_n[3][100] = 7.16e-12; } //SRAM cell properties curr_Wmemcella_sram = 1.31 * g_ip->F_sz_um; curr_Wmemcellpmos_sram = 1.23 * g_ip->F_sz_um; curr_Wmemcellnmos_sram = 2.08 * g_ip->F_sz_um; curr_area_cell_sram = 146 * g_ip->F_sz_um * g_ip->F_sz_um; curr_asp_ratio_cell_sram = 1.46; //CAM cell properties //TODO: data need to be revisited curr_Wmemcella_cam = 1.31 * g_ip->F_sz_um; curr_Wmemcellpmos_cam = 1.23 * g_ip->F_sz_um; curr_Wmemcellnmos_cam = 2.08 * g_ip->F_sz_um; curr_area_cell_cam = 292 * g_ip->F_sz_um * g_ip->F_sz_um; curr_asp_ratio_cell_cam = 2.92; //Empirical undifferetiated core/FU coefficient curr_logic_scaling_co_eff = 0.7*0.7*0.7; curr_core_tx_density = 1.25/0.7; curr_sckt_co_eff = 1.1111; curr_chip_layout_overhead = 1.2;//die measurement results based on Niagara 1 and 2 curr_macro_layout_overhead = 1.1;//EDA placement and routing tool rule of thumb } if(tech == 22){ SENSE_AMP_D = .03e-9; // s SENSE_AMP_P = 2.16e-15; // J //For 2016, MPU/ASIC stagger-contacted M1 half-pitch is 22 nm (so this is 22 nm //technology i.e. FEATURESIZE = 0.022). Using the DG process numbers for HP. //22 nm HP vdd[0] = 0.8; vdd_real[0] = g_ip->specific_hp_vdd ? g_ip->hp_Vdd : vdd[0];//TODO alpha_power_law[0]=1.2;//1.3//1.15; Lphy[0] = 0.009;//Lphy is the physical gate-length. Lelec[0] = 0.00468;//Lelec is the electrical gate-length. t_ox[0] = 0.55e-3;//micron v_th[0] = 0.1395;//V c_ox[0] = 3.63e-14;//F/micron2 mobility_eff[0] = 426.07 * (1e-2 * 1e6 * 1e-2 * 1e6); //micron2 / Vs Vdsat[0] = 2.33e-2; //V/micron c_g_ideal[0] = 3.27e-16;//F/micron c_fringe[0] = 0.06e-15;//F/micron c_junc[0] = 0;//F/micron2 I_on_n[0] = 2626.4e-6*pow((vdd_real[0]-v_th[0])/(vdd[0]-v_th[0]),alpha_power_law[0]);//A/micron I_on_p[0] = I_on_n[0] / 2;//A/micron //This value for I_on_p is not really used. nmos_effective_resistance_multiplier = 1.45; n_to_p_eff_curr_drv_ratio[0] = 2; //Wpmos/Wnmos = 2 in 2007 MASTAR. Look in //"Dynamic" tab of Device workspace. gmp_to_gmn_multiplier[0] = 1.38; //Just using the 32nm SOI value. Rnchannelon[0] = nmos_effective_resistance_multiplier * vdd_real[0] / I_on_n[0];//ohm-micron Rpchannelon[0] = n_to_p_eff_curr_drv_ratio[0] * Rnchannelon[0];//ohm-micron long_channel_leakage_reduction[0] = 1/3.274; I_off_n[0][0] = 1.52e-7/1.5*1.2*pow(vdd_real[0]/(vdd[0]),2);//From 22nm, leakage current are directly from ITRS report rather than MASTAR, since MASTAR has serious bugs there. I_off_n[0][10] = 1.55e-7/1.5*1.2*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][20] = 1.59e-7/1.5*1.2*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][30] = 1.68e-7/1.5*1.2*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][40] = 1.90e-7/1.5*1.2*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][50] = 2.69e-7/1.5*1.2*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][60] = 5.32e-7/1.5*1.2*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][70] = 1.02e-6/1.5*1.2*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][80] = 1.62e-6/1.5*1.2*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][90] = 2.73e-6/1.5*1.2*pow(vdd_real[0]/(vdd[0]),2); I_off_n[0][100] = 6.1e-6/1.5*1.2*pow(vdd_real[0]/(vdd[0]),2); //for 22nm DG HP I_g_on_n[0][0] = 1.81e-9;//A/micron I_g_on_n[0][10] = 1.81e-9; I_g_on_n[0][20] = 1.81e-9; I_g_on_n[0][30] = 1.81e-9; I_g_on_n[0][40] = 1.81e-9; I_g_on_n[0][50] = 1.81e-9; I_g_on_n[0][60] = 1.81e-9; I_g_on_n[0][70] = 1.81e-9; I_g_on_n[0][80] = 1.81e-9; I_g_on_n[0][90] = 1.81e-9; I_g_on_n[0][100] = 1.81e-9; //22 nm LSTP DG vdd[1] = 0.8; vdd_real[1] = g_ip->specific_lstp_vdd ? g_ip->lstp_Vdd : vdd[1];//TODO alpha_power_law[1]=1.23; Lphy[1] = 0.014; Lelec[1] = 0.008;//Lelec is the electrical gate-length. t_ox[1] = 1.1e-3;//micron v_th[1] = 0.40126;//V c_ox[1] = 2.30e-14;//F/micron2 mobility_eff[1] = 738.09 * (1e-2 * 1e6 * 1e-2 * 1e6); //micron2 / Vs Vdsat[1] = 6.64e-2; //V/micron c_g_ideal[1] = 3.22e-16;//F/micron c_fringe[1] = 0.08e-15; c_junc[1] = 0;//F/micron2 I_on_n[1] = 727.6e-6*pow((vdd_real[1]-v_th[1])/(vdd[1]-v_th[1]),alpha_power_law[1]);//A/micron I_on_p[1] = I_on_n[1] / 2; nmos_effective_resistance_multiplier = 1.99; n_to_p_eff_curr_drv_ratio[1] = 2; gmp_to_gmn_multiplier[1] = 0.99; Rnchannelon[1] = nmos_effective_resistance_multiplier * vdd_real[1] / I_on_n[1];//ohm-micron Rpchannelon[1] = n_to_p_eff_curr_drv_ratio[1] * Rnchannelon[1];//ohm-micron long_channel_leakage_reduction[1] = 1/1.89; I_off_n[1][0] = 2.43e-11*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][10] = 4.85e-11*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][20] = 9.68e-11*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][30] = 1.94e-10*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][40] = 3.87e-10*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][50] = 7.73e-10*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][60] = 3.55e-10*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][70] = 3.09e-9*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][80] = 6.19e-9*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][90] = 1.24e-8*pow(vdd_real[1]/(vdd[1]),1); I_off_n[1][100]= 2.48e-8*pow(vdd_real[1]/(vdd[1]),1); I_g_on_n[1][0] = 4.51e-10;//A/micron I_g_on_n[1][10] = 4.51e-10; I_g_on_n[1][20] = 4.51e-10; I_g_on_n[1][30] = 4.51e-10; I_g_on_n[1][40] = 4.51e-10; I_g_on_n[1][50] = 4.51e-10; I_g_on_n[1][60] = 4.51e-10; I_g_on_n[1][70] = 4.51e-10; I_g_on_n[1][80] = 4.51e-10; I_g_on_n[1][90] = 4.51e-10; I_g_on_n[1][100] = 4.51e-10; //22 nm LOP vdd[2] = 0.6; vdd_real[2] = g_ip->specific_lop_vdd ? g_ip->lop_Vdd : vdd[2];//TODO alpha_power_law[2]=1.21; Lphy[2] = 0.011; Lelec[2] = 0.00604;//Lelec is the electrical gate-length. t_ox[2] = 0.8e-3;//micron v_th[2] = 0.2315;//V c_ox[2] = 2.87e-14;//F/micron2 mobility_eff[2] = 698.37 * (1e-2 * 1e6 * 1e-2 * 1e6); //micron2 / Vs Vdsat[2] = 1.81e-2; //V/micron c_g_ideal[2] = 3.16e-16;//F/micron c_fringe[2] = 0.08e-15; c_junc[2] = 0;//F/micron2 This is Cj0 not Cjunc in MASTAR results->Dynamic Tab I_on_n[2] = 916.1e-6*pow((vdd_real[2]-v_th[2])/(vdd[2]-v_th[2]),alpha_power_law[2]);//A/micron I_on_p[2] = I_on_n[2] / 2; nmos_effective_resistance_multiplier = 1.73; n_to_p_eff_curr_drv_ratio[2] = 2; gmp_to_gmn_multiplier[2] = 1.11; Rnchannelon[2] = nmos_effective_resistance_multiplier * vdd_real[2] / I_on_n[2];//ohm-micron Rpchannelon[2] = n_to_p_eff_curr_drv_ratio[2] * Rnchannelon[2];//ohm-micron long_channel_leakage_reduction[2] = 1/2.38; I_off_n[2][0] = 1.31e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][10] = 2.60e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][20] = 5.14e-8*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][30] = 1.02e-7*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][40] = 2.02e-7*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][50] = 3.99e-7*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][60] = 7.91e-7*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][70] = 1.09e-6*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][80] = 2.09e-6*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][90] = 4.04e-6*pow(vdd_real[2]/(vdd[2]),5); I_off_n[2][100]= 4.48e-6*pow(vdd_real[2]/(vdd[2]),5); I_g_on_n[2][0] = 2.74e-9;//A/micron I_g_on_n[2][10] = 2.74e-9; I_g_on_n[2][20] = 2.74e-9; I_g_on_n[2][30] = 2.74e-9; I_g_on_n[2][40] = 2.74e-9; I_g_on_n[2][50] = 2.74e-9; I_g_on_n[2][60] = 2.74e-9; I_g_on_n[2][70] = 2.74e-9; I_g_on_n[2][80] = 2.74e-9; I_g_on_n[2][90] = 2.74e-9; I_g_on_n[2][100] = 2.74e-9; if (ram_cell_tech_type == 3) {} else if (ram_cell_tech_type == 4) { //22 nm commodity DRAM cell access transistor technology parameters. //parameters curr_vdd_dram_cell = 0.9;//0.45;//This value has reduced greatly in 2007 ITRS for all technology nodes. In //2005 ITRS, the value was about twice the value in 2007 ITRS Lphy[3] = 0.022;//micron Lelec[3] = 0.0181;//micron. curr_v_th_dram_access_transistor = 1;//V width_dram_access_transistor = 0.022;//micron curr_I_on_dram_cell = 20e-6; //This is a typical value that I have always //kept constant. In reality this could perhaps be lower curr_I_off_dram_cell_worst_case_length_temp = 1e-15;//A curr_Wmemcella_dram = width_dram_access_transistor; curr_Wmemcellpmos_dram = 0; curr_Wmemcellnmos_dram = 0; curr_area_cell_dram = 6*0.022*0.022;//micron2. curr_asp_ratio_cell_dram = 0.667; curr_c_dram_cell = 30e-15;//This is a typical value that I have alwaus //kept constant. //22 nm commodity DRAM wordline transistor parameters obtained using MASTAR. curr_vpp = 2.3;//vpp. V t_ox[3] = 3.5e-3;//micron v_th[3] = 1.0;//V c_ox[3] = 9.06e-15;//F/micron2 mobility_eff[3] = 367.29 * (1e-2 * 1e6 * 1e-2 * 1e6);//micron2 / Vs Vdsat[3] = 0.0972; //V/micron c_g_ideal[3] = 1.99e-16;//F/micron c_fringe[3] = 0.053e-15;//F/micron c_junc[3] = 1e-15;//F/micron2 I_on_n[3] = 910.5e-6;//A/micron I_on_p[3] = I_on_n[3] / 2;//This value for I_on_p is not really used. nmos_effective_resistance_multiplier = 1.69;//Using the value from 32nm. // n_to_p_eff_curr_drv_ratio[3] = 1.95;//Using the value from 32nm gmp_to_gmn_multiplier[3] = 0.90; Rnchannelon[3] = nmos_effective_resistance_multiplier * curr_vpp / I_on_n[3];//ohm-micron Rpchannelon[3] = n_to_p_eff_curr_drv_ratio[3] * Rnchannelon[3];//ohm-micron long_channel_leakage_reduction[3] = 1; I_off_n[3][0] = 1.1e-13; //A/micron I_off_n[3][10] = 2.11e-13; I_off_n[3][20] = 3.88e-13; I_off_n[3][30] = 6.9e-13; I_off_n[3][40] = 1.19e-12; I_off_n[3][50] = 1.98e-12; I_off_n[3][60] = 3.22e-12; I_off_n[3][70] = 5.09e-12; I_off_n[3][80] = 7.85e-12; I_off_n[3][90] = 1.18e-11; I_off_n[3][100] = 1.72e-11; } else { //some error handler } //SRAM cell properties curr_Wmemcella_sram = 1.31 * g_ip->F_sz_um; curr_Wmemcellpmos_sram = 1.23 * g_ip->F_sz_um; curr_Wmemcellnmos_sram = 2.08 * g_ip->F_sz_um; curr_area_cell_sram = 146 * g_ip->F_sz_um * g_ip->F_sz_um; curr_asp_ratio_cell_sram = 1.46; //CAM cell properties //TODO: data need to be revisited curr_Wmemcella_cam = 1.31 * g_ip->F_sz_um; curr_Wmemcellpmos_cam = 1.23 * g_ip->F_sz_um; curr_Wmemcellnmos_cam = 2.08 * g_ip->F_sz_um; curr_area_cell_cam = 292 * g_ip->F_sz_um * g_ip->F_sz_um; curr_asp_ratio_cell_cam = 2.92; //Empirical undifferetiated core/FU coefficient curr_logic_scaling_co_eff = 0.7*0.7*0.7*0.7; curr_core_tx_density = 1.25/0.7/0.7; curr_sckt_co_eff = 1.1296; curr_chip_layout_overhead = 1.2;//die measurement results based on Niagara 1 and 2 curr_macro_layout_overhead = 1.1;//EDA placement and routing tool rule of thumb } if(tech == 16){ //For 2019, MPU/ASIC stagger-contacted M1 half-pitch is 16 nm (so this is 16 nm //technology i.e. FEATURESIZE = 0.016). Using the DG process numbers for HP. //16 nm HP vdd[0] = 0.7; Lphy[0] = 0.006;//Lphy is the physical gate-length. Lelec[0] = 0.00315;//Lelec is the electrical gate-length. t_ox[0] = 0.5e-3;//micron v_th[0] = 0.1489;//V c_ox[0] = 3.83e-14;//F/micron2 Cox_elec in MASTAR mobility_eff[0] = 476.15 * (1e-2 * 1e6 * 1e-2 * 1e6); //micron2 / Vs Vdsat[0] = 1.42e-2; //V/micron calculated in spreadsheet c_g_ideal[0] = 2.30e-16;//F/micron c_fringe[0] = 0.06e-15;//F/micron MASTAR inputdynamic/3 c_junc[0] = 0;//F/micron2 MASTAR result dynamic I_on_n[0] = 2768.4e-6;//A/micron I_on_p[0] = I_on_n[0] / 2;//A/micron //This value for I_on_p is not really used. nmos_effective_resistance_multiplier = 1.48;//nmos_effective_resistance_multiplier is the ratio of Ieff to Idsat where Ieff is the effective NMOS current and Idsat is the saturation current. n_to_p_eff_curr_drv_ratio[0] = 2; //Wpmos/Wnmos = 2 in 2007 MASTAR. Look in //"Dynamic" tab of Device workspace. gmp_to_gmn_multiplier[0] = 1.38; //Just using the 32nm SOI value. Rnchannelon[0] = nmos_effective_resistance_multiplier * vdd[0] / I_on_n[0];//ohm-micron Rpchannelon[0] = n_to_p_eff_curr_drv_ratio[0] * Rnchannelon[0];//ohm-micron long_channel_leakage_reduction[0] = 1/2.655; I_off_n[0][0] = 1.52e-7/1.5*1.2*1.07; I_off_n[0][10] = 1.55e-7/1.5*1.2*1.07; I_off_n[0][20] = 1.59e-7/1.5*1.2*1.07; I_off_n[0][30] = 1.68e-7/1.5*1.2*1.07; I_off_n[0][40] = 1.90e-7/1.5*1.2*1.07; I_off_n[0][50] = 2.69e-7/1.5*1.2*1.07; I_off_n[0][60] = 5.32e-7/1.5*1.2*1.07; I_off_n[0][70] = 1.02e-6/1.5*1.2*1.07; I_off_n[0][80] = 1.62e-6/1.5*1.2*1.07; I_off_n[0][90] = 2.73e-6/1.5*1.2*1.07; I_off_n[0][100] = 6.1e-6/1.5*1.2*1.07; //for 16nm DG HP I_g_on_n[0][0] = 1.07e-9;//A/micron I_g_on_n[0][10] = 1.07e-9; I_g_on_n[0][20] = 1.07e-9; I_g_on_n[0][30] = 1.07e-9; I_g_on_n[0][40] = 1.07e-9; I_g_on_n[0][50] = 1.07e-9; I_g_on_n[0][60] = 1.07e-9; I_g_on_n[0][70] = 1.07e-9; I_g_on_n[0][80] = 1.07e-9; I_g_on_n[0][90] = 1.07e-9; I_g_on_n[0][100] = 1.07e-9; // //16 nm LSTP DG // vdd[1] = 0.8; // Lphy[1] = 0.014; // Lelec[1] = 0.008;//Lelec is the electrical gate-length. // t_ox[1] = 1.1e-3;//micron // v_th[1] = 0.40126;//V // c_ox[1] = 2.30e-14;//F/micron2 // mobility_eff[1] = 738.09 * (1e-2 * 1e6 * 1e-2 * 1e6); //micron2 / Vs // Vdsat[1] = 6.64e-2; //V/micron // c_g_ideal[1] = 3.22e-16;//F/micron // c_fringe[1] = 0.008e-15; // c_junc[1] = 0;//F/micron2 // I_on_n[1] = 727.6e-6;//A/micron // I_on_p[1] = I_on_n[1] / 2; // nmos_effective_resistance_multiplier = 1.99; // n_to_p_eff_curr_drv_ratio[1] = 2; // gmp_to_gmn_multiplier[1] = 0.99; // Rnchannelon[1] = nmos_effective_resistance_multiplier * vdd[1] / I_on_n[1];//ohm-micron // Rpchannelon[1] = n_to_p_eff_curr_drv_ratio[1] * Rnchannelon[1];//ohm-micron // I_off_n[1][0] = 2.43e-11; // I_off_n[1][10] = 4.85e-11; // I_off_n[1][20] = 9.68e-11; // I_off_n[1][30] = 1.94e-10; // I_off_n[1][40] = 3.87e-10; // I_off_n[1][50] = 7.73e-10; // I_off_n[1][60] = 3.55e-10; // I_off_n[1][70] = 3.09e-9; // I_off_n[1][80] = 6.19e-9; // I_off_n[1][90] = 1.24e-8; // I_off_n[1][100]= 2.48e-8; // // // for 22nm LSTP HP // I_g_on_n[1][0] = 4.51e-10;//A/micron // I_g_on_n[1][10] = 4.51e-10; // I_g_on_n[1][20] = 4.51e-10; // I_g_on_n[1][30] = 4.51e-10; // I_g_on_n[1][40] = 4.51e-10; // I_g_on_n[1][50] = 4.51e-10; // I_g_on_n[1][60] = 4.51e-10; // I_g_on_n[1][70] = 4.51e-10; // I_g_on_n[1][80] = 4.51e-10; // I_g_on_n[1][90] = 4.51e-10; // I_g_on_n[1][100] = 4.51e-10; if (ram_cell_tech_type == 3) {} else if (ram_cell_tech_type == 4) { //22 nm commodity DRAM cell access transistor technology parameters. //parameters curr_vdd_dram_cell = 0.9;//0.45;//This value has reduced greatly in 2007 ITRS for all technology nodes. In //2005 ITRS, the value was about twice the value in 2007 ITRS Lphy[3] = 0.022;//micron Lelec[3] = 0.0181;//micron. curr_v_th_dram_access_transistor = 1;//V width_dram_access_transistor = 0.022;//micron curr_I_on_dram_cell = 20e-6; //This is a typical value that I have always //kept constant. In reality this could perhaps be lower curr_I_off_dram_cell_worst_case_length_temp = 1e-15;//A curr_Wmemcella_dram = width_dram_access_transistor; curr_Wmemcellpmos_dram = 0; curr_Wmemcellnmos_dram = 0; curr_area_cell_dram = 6*0.022*0.022;//micron2. curr_asp_ratio_cell_dram = 0.667; curr_c_dram_cell = 30e-15;//This is a typical value that I have alwaus //kept constant. //22 nm commodity DRAM wordline transistor parameters obtained using MASTAR. curr_vpp = 2.3;//vpp. V t_ox[3] = 3.5e-3;//micron v_th[3] = 1.0;//V c_ox[3] = 9.06e-15;//F/micron2 mobility_eff[3] = 367.29 * (1e-2 * 1e6 * 1e-2 * 1e6);//micron2 / Vs Vdsat[3] = 0.0972; //V/micron c_g_ideal[3] = 1.99e-16;//F/micron c_fringe[3] = 0.053e-15;//F/micron c_junc[3] = 1e-15;//F/micron2 I_on_n[3] = 910.5e-6;//A/micron I_on_p[3] = I_on_n[3] / 2;//This value for I_on_p is not really used. nmos_effective_resistance_multiplier = 1.69;//Using the value from 32nm. // n_to_p_eff_curr_drv_ratio[3] = 1.95;//Using the value from 32nm gmp_to_gmn_multiplier[3] = 0.90; Rnchannelon[3] = nmos_effective_resistance_multiplier * curr_vpp / I_on_n[3];//ohm-micron Rpchannelon[3] = n_to_p_eff_curr_drv_ratio[3] * Rnchannelon[3];//ohm-micron long_channel_leakage_reduction[3] = 1; I_off_n[3][0] = 1.1e-13; //A/micron I_off_n[3][10] = 2.11e-13; I_off_n[3][20] = 3.88e-13; I_off_n[3][30] = 6.9e-13; I_off_n[3][40] = 1.19e-12; I_off_n[3][50] = 1.98e-12; I_off_n[3][60] = 3.22e-12; I_off_n[3][70] = 5.09e-12; I_off_n[3][80] = 7.85e-12; I_off_n[3][90] = 1.18e-11; I_off_n[3][100] = 1.72e-11; } else { //some error handler } //SRAM cell properties curr_Wmemcella_sram = 1.31 * g_ip->F_sz_um; curr_Wmemcellpmos_sram = 1.23 * g_ip->F_sz_um; curr_Wmemcellnmos_sram = 2.08 * g_ip->F_sz_um; curr_area_cell_sram = 146 * g_ip->F_sz_um * g_ip->F_sz_um; curr_asp_ratio_cell_sram = 1.46; //CAM cell properties //TODO: data need to be revisited curr_Wmemcella_cam = 1.31 * g_ip->F_sz_um; curr_Wmemcellpmos_cam = 1.23 * g_ip->F_sz_um; curr_Wmemcellnmos_cam = 2.08 * g_ip->F_sz_um; curr_area_cell_cam = 292 * g_ip->F_sz_um * g_ip->F_sz_um; curr_asp_ratio_cell_cam = 2.92; //Empirical undifferetiated core/FU coefficient curr_logic_scaling_co_eff = 0.7*0.7*0.7*0.7*0.7; curr_core_tx_density = 1.25/0.7/0.7/0.7; curr_sckt_co_eff = 1.1296; curr_chip_layout_overhead = 1.2;//die measurement results based on Niagara 1 and 2 curr_macro_layout_overhead = 1.1;//EDA placement and routing tool rule of thumb } /* * TODO:WL_Vcc does not need to retain data as long as the wordline enable signal is not active (of course enable signal will not be active since it is idle) * So, the WL_Vcc only need to balance the leakage reduction and the required waking up restore time (as mentioned in the 4.0Ghz 291 Mb SRAM Intel Paper) */ g_tp.peri_global.Vdd += curr_alpha * vdd_real[peri_global_tech_type];//real vdd, user defined or itrs g_tp.peri_global.Vdd_default += curr_alpha * vdd[peri_global_tech_type];//itrs vdd this does not have to do within line interpolation loop, can be assigned directly g_tp.peri_global.Vth += curr_alpha * v_th[peri_global_tech_type]; g_tp.peri_global.Vcc_min_default += g_tp.peri_global.Vdd_default * 0.45;// Use minimal voltage to keep the device conducted.//g_tp.peri_global.Vth; g_tp.peri_global.t_ox += curr_alpha * t_ox[peri_global_tech_type]; g_tp.peri_global.C_ox += curr_alpha * c_ox[peri_global_tech_type]; g_tp.peri_global.C_g_ideal += curr_alpha * c_g_ideal[peri_global_tech_type]; g_tp.peri_global.C_fringe += curr_alpha * c_fringe[peri_global_tech_type]; g_tp.peri_global.C_junc += curr_alpha * c_junc[peri_global_tech_type]; g_tp.peri_global.C_junc_sidewall = 0.25e-15; // F/micron g_tp.peri_global.l_phy += curr_alpha * Lphy[peri_global_tech_type]; g_tp.peri_global.l_elec += curr_alpha * Lelec[peri_global_tech_type]; g_tp.peri_global.I_on_n += curr_alpha * I_on_n[peri_global_tech_type]; g_tp.peri_global.R_nch_on += curr_alpha * Rnchannelon[peri_global_tech_type]; g_tp.peri_global.R_pch_on += curr_alpha * Rpchannelon[peri_global_tech_type]; g_tp.peri_global.n_to_p_eff_curr_drv_ratio += curr_alpha * n_to_p_eff_curr_drv_ratio[peri_global_tech_type]; g_tp.peri_global.long_channel_leakage_reduction += curr_alpha * long_channel_leakage_reduction[peri_global_tech_type]; g_tp.peri_global.I_off_n += curr_alpha * I_off_n[peri_global_tech_type][g_ip->temp - 300];//*pow(g_tp.peri_global.Vdd/g_tp.peri_global.Vdd_default,3);//Consider the voltage change may affect the current density as well. TODO: polynomial curve-fitting based on MASTAR may not be accurate enough g_tp.peri_global.I_off_p += curr_alpha * I_off_n[peri_global_tech_type][g_ip->temp - 300];//*pow(g_tp.peri_global.Vdd/g_tp.peri_global.Vdd_default,3);//To mimic the Vdd effect on Ioff (for the same device, dvs should not change default Ioff---only changes if device is different?? but MASTAR shows different results) g_tp.peri_global.I_g_on_n += curr_alpha * I_g_on_n[peri_global_tech_type][g_ip->temp - 300]; g_tp.peri_global.I_g_on_p += curr_alpha * I_g_on_n[peri_global_tech_type][g_ip->temp - 300]; gmp_to_gmn_multiplier_periph_global += curr_alpha * gmp_to_gmn_multiplier[peri_global_tech_type]; g_tp.peri_global.Mobility_n += curr_alpha *mobility_eff[peri_global_tech_type]; //Sleep tx uses LSTP devices g_tp.sleep_tx.Vdd += curr_alpha * vdd_real[1]; g_tp.sleep_tx.Vdd_default += curr_alpha * vdd[1]; g_tp.sleep_tx.Vth += curr_alpha * v_th[1]; g_tp.sleep_tx.Vcc_min_default += g_tp.sleep_tx.Vdd; g_tp.sleep_tx.Vcc_min = g_tp.sleep_tx.Vcc_min_default;//user cannot change this, has to be decided by technology g_tp.sleep_tx.t_ox += curr_alpha * t_ox[1]; g_tp.sleep_tx.C_ox += curr_alpha * c_ox[1]; g_tp.sleep_tx.C_g_ideal += curr_alpha * c_g_ideal[1]; g_tp.sleep_tx.C_fringe += curr_alpha * c_fringe[1]; g_tp.sleep_tx.C_junc += curr_alpha * c_junc[1]; g_tp.sleep_tx.C_junc_sidewall = 0.25e-15; // F/micron g_tp.sleep_tx.l_phy += curr_alpha * Lphy[1]; g_tp.sleep_tx.l_elec += curr_alpha * Lelec[1]; g_tp.sleep_tx.I_on_n += curr_alpha * I_on_n[1]; g_tp.sleep_tx.R_nch_on += curr_alpha * Rnchannelon[1]; g_tp.sleep_tx.R_pch_on += curr_alpha * Rpchannelon[1]; g_tp.sleep_tx.n_to_p_eff_curr_drv_ratio += curr_alpha * n_to_p_eff_curr_drv_ratio[1]; g_tp.sleep_tx.long_channel_leakage_reduction += curr_alpha * long_channel_leakage_reduction[1]; g_tp.sleep_tx.I_off_n += curr_alpha * I_off_n[1][g_ip->temp - 300];//**pow(g_tp.sleep_tx.Vdd/g_tp.sleep_tx.Vdd_default,4); g_tp.sleep_tx.I_off_p += curr_alpha * I_off_n[1][g_ip->temp - 300];//**pow(g_tp.sleep_tx.Vdd/g_tp.sleep_tx.Vdd_default,4); g_tp.sleep_tx.I_g_on_n += curr_alpha * I_g_on_n[1][g_ip->temp - 300]; g_tp.sleep_tx.I_g_on_p += curr_alpha * I_g_on_n[1][g_ip->temp - 300]; g_tp.sleep_tx.Mobility_n += curr_alpha *mobility_eff[1]; // gmp_to_gmn_multiplier_periph_global += curr_alpha * gmp_to_gmn_multiplier[1]; g_tp.sram_cell.Vdd += curr_alpha * vdd_real[ram_cell_tech_type]; g_tp.sram_cell.Vdd_default += curr_alpha * vdd[ram_cell_tech_type]; g_tp.sram_cell.Vth += curr_alpha * v_th[ram_cell_tech_type]; g_tp.sram_cell.Vcc_min_default += g_tp.sram_cell.Vdd_default * 0.6; g_tp.sram_cell.l_phy += curr_alpha * Lphy[ram_cell_tech_type]; g_tp.sram_cell.l_elec += curr_alpha * Lelec[ram_cell_tech_type]; g_tp.sram_cell.t_ox += curr_alpha * t_ox[ram_cell_tech_type]; g_tp.sram_cell.C_g_ideal += curr_alpha * c_g_ideal[ram_cell_tech_type]; g_tp.sram_cell.C_fringe += curr_alpha * c_fringe[ram_cell_tech_type]; g_tp.sram_cell.C_junc += curr_alpha * c_junc[ram_cell_tech_type]; g_tp.sram_cell.C_junc_sidewall = 0.25e-15; // F/micron g_tp.sram_cell.I_on_n += curr_alpha * I_on_n[ram_cell_tech_type]; g_tp.sram_cell.R_nch_on += curr_alpha * Rnchannelon[ram_cell_tech_type]; g_tp.sram_cell.R_pch_on += curr_alpha * Rpchannelon[ram_cell_tech_type]; g_tp.sram_cell.n_to_p_eff_curr_drv_ratio += curr_alpha * n_to_p_eff_curr_drv_ratio[ram_cell_tech_type]; g_tp.sram_cell.long_channel_leakage_reduction += curr_alpha * long_channel_leakage_reduction[ram_cell_tech_type]; g_tp.sram_cell.I_off_n += curr_alpha * I_off_n[ram_cell_tech_type][g_ip->temp - 300];//**pow(g_tp.sram_cell.Vdd/g_tp.sram_cell.Vdd_default,4); g_tp.sram_cell.I_off_p += curr_alpha * I_off_n[ram_cell_tech_type][g_ip->temp - 300];//**pow(g_tp.sram_cell.Vdd/g_tp.sram_cell.Vdd_default,4); g_tp.sram_cell.I_g_on_n += curr_alpha * I_g_on_n[ram_cell_tech_type][g_ip->temp - 300]; g_tp.sram_cell.I_g_on_p += curr_alpha * I_g_on_n[ram_cell_tech_type][g_ip->temp - 300]; g_tp.dram_cell_Vdd += curr_alpha * curr_vdd_dram_cell; g_tp.dram_acc.Vth += curr_alpha * curr_v_th_dram_access_transistor; g_tp.dram_acc.l_phy += curr_alpha * Lphy[dram_cell_tech_flavor]; g_tp.dram_acc.l_elec += curr_alpha * Lelec[dram_cell_tech_flavor]; g_tp.dram_acc.C_g_ideal += curr_alpha * c_g_ideal[dram_cell_tech_flavor]; g_tp.dram_acc.C_fringe += curr_alpha * c_fringe[dram_cell_tech_flavor]; g_tp.dram_acc.C_junc += curr_alpha * c_junc[dram_cell_tech_flavor]; g_tp.dram_acc.C_junc_sidewall = 0.25e-15; // F/micron g_tp.dram_cell_I_on += curr_alpha * curr_I_on_dram_cell; g_tp.dram_cell_I_off_worst_case_len_temp += curr_alpha * curr_I_off_dram_cell_worst_case_length_temp; g_tp.dram_acc.I_on_n += curr_alpha * I_on_n[dram_cell_tech_flavor]; g_tp.dram_cell_C += curr_alpha * curr_c_dram_cell; g_tp.vpp += curr_alpha * curr_vpp; g_tp.dram_wl.l_phy += curr_alpha * Lphy[dram_cell_tech_flavor]; g_tp.dram_wl.l_elec += curr_alpha * Lelec[dram_cell_tech_flavor]; g_tp.dram_wl.C_g_ideal += curr_alpha * c_g_ideal[dram_cell_tech_flavor]; g_tp.dram_wl.C_fringe += curr_alpha * c_fringe[dram_cell_tech_flavor]; g_tp.dram_wl.C_junc += curr_alpha * c_junc[dram_cell_tech_flavor]; g_tp.dram_wl.C_junc_sidewall = 0.25e-15; // F/micron g_tp.dram_wl.I_on_n += curr_alpha * I_on_n[dram_cell_tech_flavor]; g_tp.dram_wl.R_nch_on += curr_alpha * Rnchannelon[dram_cell_tech_flavor]; g_tp.dram_wl.R_pch_on += curr_alpha * Rpchannelon[dram_cell_tech_flavor]; g_tp.dram_wl.n_to_p_eff_curr_drv_ratio += curr_alpha * n_to_p_eff_curr_drv_ratio[dram_cell_tech_flavor]; g_tp.dram_wl.long_channel_leakage_reduction += curr_alpha * long_channel_leakage_reduction[dram_cell_tech_flavor]; g_tp.dram_wl.I_off_n += curr_alpha * I_off_n[dram_cell_tech_flavor][g_ip->temp - 300]; g_tp.dram_wl.I_off_p += curr_alpha * I_off_n[dram_cell_tech_flavor][g_ip->temp - 300]; g_tp.cam_cell.Vdd += curr_alpha * vdd_real[ram_cell_tech_type]; g_tp.cam_cell.Vdd_default += curr_alpha * vdd[ram_cell_tech_type]; g_tp.cam_cell.l_phy += curr_alpha * Lphy[ram_cell_tech_type]; g_tp.cam_cell.l_elec += curr_alpha * Lelec[ram_cell_tech_type]; g_tp.cam_cell.t_ox += curr_alpha * t_ox[ram_cell_tech_type]; g_tp.cam_cell.Vth += curr_alpha * v_th[ram_cell_tech_type]; g_tp.cam_cell.C_g_ideal += curr_alpha * c_g_ideal[ram_cell_tech_type]; g_tp.cam_cell.C_fringe += curr_alpha * c_fringe[ram_cell_tech_type]; g_tp.cam_cell.C_junc += curr_alpha * c_junc[ram_cell_tech_type]; g_tp.cam_cell.C_junc_sidewall = 0.25e-15; // F/micron g_tp.cam_cell.I_on_n += curr_alpha * I_on_n[ram_cell_tech_type]; g_tp.cam_cell.R_nch_on += curr_alpha * Rnchannelon[ram_cell_tech_type]; g_tp.cam_cell.R_pch_on += curr_alpha * Rpchannelon[ram_cell_tech_type]; g_tp.cam_cell.n_to_p_eff_curr_drv_ratio += curr_alpha * n_to_p_eff_curr_drv_ratio[ram_cell_tech_type]; g_tp.cam_cell.long_channel_leakage_reduction += curr_alpha * long_channel_leakage_reduction[ram_cell_tech_type]; g_tp.cam_cell.I_off_n += curr_alpha * I_off_n[ram_cell_tech_type][g_ip->temp - 300];//*pow(g_tp.cam_cell.Vdd/g_tp.cam_cell.Vdd_default,4); g_tp.cam_cell.I_off_p += curr_alpha * I_off_n[ram_cell_tech_type][g_ip->temp - 300];//**pow(g_tp.cam_cell.Vdd/g_tp.cam_cell.Vdd_default,4); g_tp.cam_cell.I_g_on_n += curr_alpha * I_g_on_n[ram_cell_tech_type][g_ip->temp - 300]; g_tp.cam_cell.I_g_on_p += curr_alpha * I_g_on_n[ram_cell_tech_type][g_ip->temp - 300]; g_tp.dram.cell_a_w += curr_alpha * curr_Wmemcella_dram; g_tp.dram.cell_pmos_w += curr_alpha * curr_Wmemcellpmos_dram; g_tp.dram.cell_nmos_w += curr_alpha * curr_Wmemcellnmos_dram; area_cell_dram += curr_alpha * curr_area_cell_dram; asp_ratio_cell_dram += curr_alpha * curr_asp_ratio_cell_dram; g_tp.sram.cell_a_w += curr_alpha * curr_Wmemcella_sram; g_tp.sram.cell_pmos_w += curr_alpha * curr_Wmemcellpmos_sram; g_tp.sram.cell_nmos_w += curr_alpha * curr_Wmemcellnmos_sram; area_cell_sram += curr_alpha * curr_area_cell_sram; asp_ratio_cell_sram += curr_alpha * curr_asp_ratio_cell_sram; g_tp.cam.cell_a_w += curr_alpha * curr_Wmemcella_cam;//sheng g_tp.cam.cell_pmos_w += curr_alpha * curr_Wmemcellpmos_cam; g_tp.cam.cell_nmos_w += curr_alpha * curr_Wmemcellnmos_cam; area_cell_cam += curr_alpha * curr_area_cell_cam; asp_ratio_cell_cam += curr_alpha * curr_asp_ratio_cell_cam; //Sense amplifier latch Gm calculation mobility_eff_periph_global += curr_alpha * mobility_eff[peri_global_tech_type]; Vdsat_periph_global += curr_alpha * Vdsat[peri_global_tech_type]; //Empirical undifferetiated core/FU coefficient g_tp.scaling_factor.logic_scaling_co_eff += curr_alpha * curr_logic_scaling_co_eff; g_tp.scaling_factor.core_tx_density += curr_alpha * curr_core_tx_density; g_tp.chip_layout_overhead += curr_alpha * curr_chip_layout_overhead; g_tp.macro_layout_overhead += curr_alpha * curr_macro_layout_overhead; g_tp.sckt_co_eff += curr_alpha * curr_sckt_co_eff; } //Currently we are not modeling the resistance/capacitance of poly anywhere. //following data are continuous function (or data have been processed) does not need linear interpolation g_tp.w_comp_inv_p1 = 12.5 * g_ip->F_sz_um;//this was 10 micron for the 0.8 micron process g_tp.w_comp_inv_n1 = 7.5 * g_ip->F_sz_um;//this was 6 micron for the 0.8 micron process g_tp.w_comp_inv_p2 = 25 * g_ip->F_sz_um;//this was 20 micron for the 0.8 micron process g_tp.w_comp_inv_n2 = 15 * g_ip->F_sz_um;//this was 12 micron for the 0.8 micron process g_tp.w_comp_inv_p3 = 50 * g_ip->F_sz_um;//this was 40 micron for the 0.8 micron process g_tp.w_comp_inv_n3 = 30 * g_ip->F_sz_um;//this was 24 micron for the 0.8 micron process g_tp.w_eval_inv_p = 100 * g_ip->F_sz_um;//this was 80 micron for the 0.8 micron process g_tp.w_eval_inv_n = 50 * g_ip->F_sz_um;//this was 40 micron for the 0.8 micron process g_tp.w_comp_n = 12.5 * g_ip->F_sz_um;//this was 10 micron for the 0.8 micron process g_tp.w_comp_p = 37.5 * g_ip->F_sz_um;//this was 30 micron for the 0.8 micron process g_tp.MIN_GAP_BET_P_AND_N_DIFFS = 5 * g_ip->F_sz_um; g_tp.MIN_GAP_BET_SAME_TYPE_DIFFS = 1.5 * g_ip->F_sz_um; g_tp.HPOWERRAIL = 2 * g_ip->F_sz_um; g_tp.cell_h_def = 50 * g_ip->F_sz_um; g_tp.w_poly_contact = g_ip->F_sz_um; g_tp.spacing_poly_to_contact = g_ip->F_sz_um; g_tp.spacing_poly_to_poly = 1.5 * g_ip->F_sz_um; g_tp.ram_wl_stitching_overhead_ = 7.5 * g_ip->F_sz_um; g_tp.min_w_nmos_ = 3 * g_ip->F_sz_um / 2; g_tp.max_w_nmos_ = 100 * g_ip->F_sz_um; g_tp.w_iso = 12.5*g_ip->F_sz_um;//was 10 micron for the 0.8 micron process g_tp.w_sense_n = 3.75*g_ip->F_sz_um; // sense amplifier N-trans; was 3 micron for the 0.8 micron process g_tp.w_sense_p = 7.5*g_ip->F_sz_um; // sense amplifier P-trans; was 6 micron for the 0.8 micron process g_tp.w_sense_en = 5*g_ip->F_sz_um; // Sense enable transistor of the sense amplifier; was 4 micron for the 0.8 micron process g_tp.w_nmos_b_mux = 6 * g_tp.min_w_nmos_; g_tp.w_nmos_sa_mux = 6 * g_tp.min_w_nmos_; if (ram_cell_tech_type == comm_dram) { g_tp.max_w_nmos_dec = 8 * g_ip->F_sz_um; g_tp.h_dec = 8; // in the unit of memory cell height } else { g_tp.max_w_nmos_dec = g_tp.max_w_nmos_; g_tp.h_dec = 4; // in the unit of memory cell height } g_tp.peri_global.C_overlap = 0.2 * g_tp.peri_global.C_g_ideal; g_tp.sram_cell.C_overlap = 0.2 * g_tp.sram_cell.C_g_ideal; g_tp.cam_cell.C_overlap = 0.2 * g_tp.cam_cell.C_g_ideal; g_tp.dram_acc.C_overlap = 0.2 * g_tp.dram_acc.C_g_ideal; g_tp.dram_acc.R_nch_on = g_tp.dram_cell_Vdd / g_tp.dram_acc.I_on_n; //g_tp.dram_acc.R_pch_on = g_tp.dram_cell_Vdd / g_tp.dram_acc.I_on_p; g_tp.dram_wl.C_overlap = 0.2 * g_tp.dram_wl.C_g_ideal; double gmn_sense_amp_latch = (mobility_eff_periph_global / 2) * g_tp.peri_global.C_ox * (g_tp.w_sense_n / g_tp.peri_global.l_elec) * Vdsat_periph_global; double gmp_sense_amp_latch = gmp_to_gmn_multiplier_periph_global * gmn_sense_amp_latch; g_tp.gm_sense_amp_latch = gmn_sense_amp_latch + gmp_sense_amp_latch * pow((g_tp.peri_global.Vdd-g_tp.peri_global.Vth)/(g_tp.peri_global.Vdd_default-g_tp.peri_global.Vth),1.3)/(g_tp.peri_global.Vdd/g_tp.peri_global.Vdd_default); g_tp.dram.b_w = sqrt(area_cell_dram / (asp_ratio_cell_dram)); g_tp.dram.b_h = asp_ratio_cell_dram * g_tp.dram.b_w; g_tp.sram.b_w = sqrt(area_cell_sram / (asp_ratio_cell_sram)); g_tp.sram.b_h = asp_ratio_cell_sram * g_tp.sram.b_w; g_tp.cam.b_w = sqrt(area_cell_cam / (asp_ratio_cell_cam));//Sheng g_tp.cam.b_h = asp_ratio_cell_cam * g_tp.cam.b_w; g_tp.dram.Vbitpre = g_tp.dram_cell_Vdd; g_tp.sram.Vbitpre = g_tp.sram_cell.Vdd;//vdd[ram_cell_tech_type]; g_tp.cam.Vbitpre = g_tp.cam_cell.Vdd;//vdd[ram_cell_tech_type];//Sheng pmos_to_nmos_sizing_r = pmos_to_nmos_sz_ratio(); g_tp.w_pmos_bl_precharge = 6 * pmos_to_nmos_sizing_r * g_tp.min_w_nmos_; g_tp.w_pmos_bl_eq = pmos_to_nmos_sizing_r * g_tp.min_w_nmos_; //DVS and power-gating voltage finalization if (g_tp.sram_cell.Vcc_min_default > g_tp.sram_cell.Vdd || g_tp.peri_global.Vdd < g_tp.peri_global.Vdd_default*0.75 || g_tp.sram_cell.Vdd < g_tp.sram_cell.Vdd_default*0.75) { cerr << "User defined Vdd is too low.\n\n"<< endl; exit(0); } if (g_ip->specific_vcc_min) { g_tp.sram_cell.Vcc_min = g_ip->user_defined_vcc_min; g_tp.peri_global.Vcc_min = g_ip->user_defined_vcc_min; g_tp.sram.Vbitfloating = g_tp.sram.Vbitpre*0.7*(g_tp.sram_cell.Vcc_min/g_tp.peri_global.Vcc_min_default); // if (g_ip->user_defined_vcc_min < g_tp.peri_global.Vcc_min_default) // { // g_tp.peri_global.Vcc_min = g_ip->user_defined_vcc_min; // } // else { // // } } else { g_tp.sram_cell.Vcc_min = g_tp.sram_cell.Vcc_min_default; g_tp.peri_global.Vcc_min = g_tp.peri_global.Vcc_min_default; g_tp.sram.Vbitfloating = g_tp.sram.Vbitpre*0.7; } if (g_tp.sram_cell.Vcc_min < g_tp.sram_cell.Vcc_min_default )//if want to compute multiple power-gating vdd settings in one run, should have multiple results copies (each copy containing such flag) in update_pg () { g_ip->user_defined_vcc_underflow = true; } else { g_ip->user_defined_vcc_underflow = false; } if (g_tp.sram_cell.Vcc_min > g_tp.sram_cell.Vdd || g_tp.peri_global.Vcc_min > g_tp.peri_global.Vdd) { cerr << "User defined power-saving supply voltage cannot be lower than Vdd (DVS0).\n\n"<< endl; exit(0); } double wire_pitch [NUMBER_INTERCONNECT_PROJECTION_TYPES][NUMBER_WIRE_TYPES], wire_r_per_micron[NUMBER_INTERCONNECT_PROJECTION_TYPES][NUMBER_WIRE_TYPES], wire_c_per_micron[NUMBER_INTERCONNECT_PROJECTION_TYPES][NUMBER_WIRE_TYPES], horiz_dielectric_constant[NUMBER_INTERCONNECT_PROJECTION_TYPES][NUMBER_WIRE_TYPES], vert_dielectric_constant[NUMBER_INTERCONNECT_PROJECTION_TYPES][NUMBER_WIRE_TYPES], aspect_ratio[NUMBER_INTERCONNECT_PROJECTION_TYPES][NUMBER_WIRE_TYPES], miller_value[NUMBER_INTERCONNECT_PROJECTION_TYPES][NUMBER_WIRE_TYPES], ild_thickness[NUMBER_INTERCONNECT_PROJECTION_TYPES][NUMBER_WIRE_TYPES]; for (iter=0; iter<=1; ++iter) { // linear interpolation if (iter == 0) { tech = tech_lo; if (tech_lo == tech_hi) { curr_alpha = 1; } else { curr_alpha = (technology - tech_hi)/(tech_lo - tech_hi); } } else { tech = tech_hi; if (tech_lo == tech_hi) { break; } else { curr_alpha = (tech_lo - technology)/(tech_lo - tech_hi); } } if (tech == 180) { //Aggressive projections wire_pitch[0][0] = 2.5 * g_ip->F_sz_um;//micron aspect_ratio[0][0] = 2.0; wire_width = wire_pitch[0][0] / 2; //micron wire_thickness = aspect_ratio[0][0] * wire_width;//micron wire_spacing = wire_pitch[0][0] - wire_width;//micron barrier_thickness = 0.017;//micron dishing_thickness = 0;//micron alpha_scatter = 1; wire_r_per_micron[0][0] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter);//ohm/micron ild_thickness[0][0] = 0.75;//micron miller_value[0][0] = 1.5; horiz_dielectric_constant[0][0] = 2.709; vert_dielectric_constant[0][0] = 3.9; fringe_cap = 0.115e-15; //F/micron wire_c_per_micron[0][0] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][0], miller_value[0][0], horiz_dielectric_constant[0][0], vert_dielectric_constant[0][0], fringe_cap);//F/micron. wire_pitch[0][1] = 4 * g_ip->F_sz_um; wire_width = wire_pitch[0][1] / 2; aspect_ratio[0][1] = 2.4; wire_thickness = aspect_ratio[0][1] * wire_width; wire_spacing = wire_pitch[0][1] - wire_width; wire_r_per_micron[0][1] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][1] = 0.75;//micron miller_value[0][1] = 1.5; horiz_dielectric_constant[0][1] = 2.709; vert_dielectric_constant[0][1] = 3.9; fringe_cap = 0.115e-15; //F/micron wire_c_per_micron[0][1] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][1], miller_value[0][1], horiz_dielectric_constant[0][1], vert_dielectric_constant[0][1], fringe_cap); wire_pitch[0][2] = 8 * g_ip->F_sz_um; aspect_ratio[0][2] = 2.2; wire_width = wire_pitch[0][2] / 2; wire_thickness = aspect_ratio[0][2] * wire_width; wire_spacing = wire_pitch[0][2] - wire_width; wire_r_per_micron[0][2] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][2] = 1.5; miller_value[0][2] = 1.5; horiz_dielectric_constant[0][2] = 2.709; vert_dielectric_constant[0][2] = 3.9; wire_c_per_micron[0][2] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][2], miller_value[0][2], horiz_dielectric_constant[0][2], vert_dielectric_constant[0][2], fringe_cap); //Conservative projections wire_pitch[1][0] = 2.5 * g_ip->F_sz_um; aspect_ratio[1][0]= 2.0; wire_width = wire_pitch[1][0] / 2; wire_thickness = aspect_ratio[1][0] * wire_width; wire_spacing = wire_pitch[1][0] - wire_width; barrier_thickness = 0.017; dishing_thickness = 0; alpha_scatter = 1; wire_r_per_micron[1][0] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][0] = 0.75; miller_value[1][0] = 1.5; horiz_dielectric_constant[1][0] = 3.038; vert_dielectric_constant[1][0] = 3.9; fringe_cap = 0.115e-15; wire_c_per_micron[1][0] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][0], miller_value[1][0], horiz_dielectric_constant[1][0], vert_dielectric_constant[1][0], fringe_cap); wire_pitch[1][1] = 4 * g_ip->F_sz_um; wire_width = wire_pitch[1][1] / 2; aspect_ratio[1][1] = 2.0; wire_thickness = aspect_ratio[1][1] * wire_width; wire_spacing = wire_pitch[1][1] - wire_width; wire_r_per_micron[1][1] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][1] = 0.75; miller_value[1][1] = 1.5; horiz_dielectric_constant[1][1] = 3.038; vert_dielectric_constant[1][1] = 3.9; wire_c_per_micron[1][1] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][1], miller_value[1][1], horiz_dielectric_constant[1][1], vert_dielectric_constant[1][1], fringe_cap); wire_pitch[1][2] = 8 * g_ip->F_sz_um; aspect_ratio[1][2] = 2.2; wire_width = wire_pitch[1][2] / 2; wire_thickness = aspect_ratio[1][2] * wire_width; wire_spacing = wire_pitch[1][2] - wire_width; dishing_thickness = 0.1 * wire_thickness; wire_r_per_micron[1][2] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][2] = 1.98; miller_value[1][2] = 1.5; horiz_dielectric_constant[1][2] = 3.038; vert_dielectric_constant[1][2] = 3.9; wire_c_per_micron[1][2] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][2] , miller_value[1][2], horiz_dielectric_constant[1][2], vert_dielectric_constant[1][2], fringe_cap); //Nominal projections for commodity DRAM wordline/bitline wire_pitch[1][3] = 2 * 0.18; wire_c_per_micron[1][3] = 60e-15 / (256 * 2 * 0.18); wire_r_per_micron[1][3] = 12 / 0.18; } else if (tech == 90) { //Aggressive projections wire_pitch[0][0] = 2.5 * g_ip->F_sz_um;//micron aspect_ratio[0][0] = 2.4; wire_width = wire_pitch[0][0] / 2; //micron wire_thickness = aspect_ratio[0][0] * wire_width;//micron wire_spacing = wire_pitch[0][0] - wire_width;//micron barrier_thickness = 0.01;//micron dishing_thickness = 0;//micron alpha_scatter = 1; wire_r_per_micron[0][0] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter);//ohm/micron ild_thickness[0][0] = 0.48;//micron miller_value[0][0] = 1.5; horiz_dielectric_constant[0][0] = 2.709; vert_dielectric_constant[0][0] = 3.9; fringe_cap = 0.115e-15; //F/micron wire_c_per_micron[0][0] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][0], miller_value[0][0], horiz_dielectric_constant[0][0], vert_dielectric_constant[0][0], fringe_cap);//F/micron. wire_pitch[0][1] = 4 * g_ip->F_sz_um; wire_width = wire_pitch[0][1] / 2; aspect_ratio[0][1] = 2.4; wire_thickness = aspect_ratio[0][1] * wire_width; wire_spacing = wire_pitch[0][1] - wire_width; wire_r_per_micron[0][1] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][1] = 0.48;//micron miller_value[0][1] = 1.5; horiz_dielectric_constant[0][1] = 2.709; vert_dielectric_constant[0][1] = 3.9; wire_c_per_micron[0][1] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][1], miller_value[0][1], horiz_dielectric_constant[0][1], vert_dielectric_constant[0][1], fringe_cap); wire_pitch[0][2] = 8 * g_ip->F_sz_um; aspect_ratio[0][2] = 2.7; wire_width = wire_pitch[0][2] / 2; wire_thickness = aspect_ratio[0][2] * wire_width; wire_spacing = wire_pitch[0][2] - wire_width; wire_r_per_micron[0][2] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][2] = 0.96; miller_value[0][2] = 1.5; horiz_dielectric_constant[0][2] = 2.709; vert_dielectric_constant[0][2] = 3.9; wire_c_per_micron[0][2] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][2], miller_value[0][2], horiz_dielectric_constant[0][2], vert_dielectric_constant[0][2], fringe_cap); //Conservative projections wire_pitch[1][0] = 2.5 * g_ip->F_sz_um; aspect_ratio[1][0] = 2.0; wire_width = wire_pitch[1][0] / 2; wire_thickness = aspect_ratio[1][0] * wire_width; wire_spacing = wire_pitch[1][0] - wire_width; barrier_thickness = 0.008; dishing_thickness = 0; alpha_scatter = 1; wire_r_per_micron[1][0] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][0] = 0.48; miller_value[1][0] = 1.5; horiz_dielectric_constant[1][0] = 3.038; vert_dielectric_constant[1][0] = 3.9; fringe_cap = 0.115e-15; wire_c_per_micron[1][0] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][0], miller_value[1][0], horiz_dielectric_constant[1][0], vert_dielectric_constant[1][0], fringe_cap); wire_pitch[1][1] = 4 * g_ip->F_sz_um; wire_width = wire_pitch[1][1] / 2; aspect_ratio[1][1] = 2.0; wire_thickness = aspect_ratio[1][1] * wire_width; wire_spacing = wire_pitch[1][1] - wire_width; wire_r_per_micron[1][1] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][1] = 0.48; miller_value[1][1] = 1.5; horiz_dielectric_constant[1][1] = 3.038; vert_dielectric_constant[1][1] = 3.9; wire_c_per_micron[1][1] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][1], miller_value[1][1], horiz_dielectric_constant[1][1], vert_dielectric_constant[1][1], fringe_cap); wire_pitch[1][2] = 8 * g_ip->F_sz_um; aspect_ratio[1][2] = 2.2; wire_width = wire_pitch[1][2] / 2; wire_thickness = aspect_ratio[1][2] * wire_width; wire_spacing = wire_pitch[1][2] - wire_width; dishing_thickness = 0.1 * wire_thickness; wire_r_per_micron[1][2] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][2] = 1.1; miller_value[1][2] = 1.5; horiz_dielectric_constant[1][2] = 3.038; vert_dielectric_constant[1][2] = 3.9; wire_c_per_micron[1][2] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][2] , miller_value[1][2], horiz_dielectric_constant[1][2], vert_dielectric_constant[1][2], fringe_cap); //Nominal projections for commodity DRAM wordline/bitline wire_pitch[1][3] = 2 * 0.09; wire_c_per_micron[1][3] = 60e-15 / (256 * 2 * 0.09); wire_r_per_micron[1][3] = 12 / 0.09; } else if (tech == 65) { //Aggressive projections wire_pitch[0][0] = 2.5 * g_ip->F_sz_um; aspect_ratio[0][0] = 2.7; wire_width = wire_pitch[0][0] / 2; wire_thickness = aspect_ratio[0][0] * wire_width; wire_spacing = wire_pitch[0][0] - wire_width; barrier_thickness = 0; dishing_thickness = 0; alpha_scatter = 1; wire_r_per_micron[0][0] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][0] = 0.405; miller_value[0][0] = 1.5; horiz_dielectric_constant[0][0] = 2.303; vert_dielectric_constant[0][0] = 3.9; fringe_cap = 0.115e-15; wire_c_per_micron[0][0] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][0] , miller_value[0][0] , horiz_dielectric_constant[0][0] , vert_dielectric_constant[0][0] , fringe_cap); wire_pitch[0][1] = 4 * g_ip->F_sz_um; wire_width = wire_pitch[0][1] / 2; aspect_ratio[0][1] = 2.7; wire_thickness = aspect_ratio[0][1] * wire_width; wire_spacing = wire_pitch[0][1] - wire_width; wire_r_per_micron[0][1] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][1] = 0.405; miller_value[0][1] = 1.5; horiz_dielectric_constant[0][1] = 2.303; vert_dielectric_constant[0][1] = 3.9; wire_c_per_micron[0][1] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][1], miller_value[0][1], horiz_dielectric_constant[0][1], vert_dielectric_constant[0][1], fringe_cap); wire_pitch[0][2] = 8 * g_ip->F_sz_um; aspect_ratio[0][2] = 2.8; wire_width = wire_pitch[0][2] / 2; wire_thickness = aspect_ratio[0][2] * wire_width; wire_spacing = wire_pitch[0][2] - wire_width; wire_r_per_micron[0][2] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][2] = 0.81; miller_value[0][2] = 1.5; horiz_dielectric_constant[0][2] = 2.303; vert_dielectric_constant[0][2] = 3.9; wire_c_per_micron[0][2] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][2], miller_value[0][2], horiz_dielectric_constant[0][2], vert_dielectric_constant[0][2], fringe_cap); //Conservative projections wire_pitch[1][0] = 2.5 * g_ip->F_sz_um; aspect_ratio[1][0] = 2.0; wire_width = wire_pitch[1][0] / 2; wire_thickness = aspect_ratio[1][0] * wire_width; wire_spacing = wire_pitch[1][0] - wire_width; barrier_thickness = 0.006; dishing_thickness = 0; alpha_scatter = 1; wire_r_per_micron[1][0] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][0] = 0.405; miller_value[1][0] = 1.5; horiz_dielectric_constant[1][0] = 2.734; vert_dielectric_constant[1][0] = 3.9; fringe_cap = 0.115e-15; wire_c_per_micron[1][0] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][0], miller_value[1][0], horiz_dielectric_constant[1][0], vert_dielectric_constant[1][0], fringe_cap); wire_pitch[1][1] = 4 * g_ip->F_sz_um; wire_width = wire_pitch[1][1] / 2; aspect_ratio[1][1] = 2.0; wire_thickness = aspect_ratio[1][1] * wire_width; wire_spacing = wire_pitch[1][1] - wire_width; wire_r_per_micron[1][1] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][1] = 0.405; miller_value[1][1] = 1.5; horiz_dielectric_constant[1][1] = 2.734; vert_dielectric_constant[1][1] = 3.9; wire_c_per_micron[1][1] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][1], miller_value[1][1], horiz_dielectric_constant[1][1], vert_dielectric_constant[1][1], fringe_cap); wire_pitch[1][2] = 8 * g_ip->F_sz_um; aspect_ratio[1][2] = 2.2; wire_width = wire_pitch[1][2] / 2; wire_thickness = aspect_ratio[1][2] * wire_width; wire_spacing = wire_pitch[1][2] - wire_width; dishing_thickness = 0.1 * wire_thickness; wire_r_per_micron[1][2] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][2] = 0.77; miller_value[1][2] = 1.5; horiz_dielectric_constant[1][2] = 2.734; vert_dielectric_constant[1][2] = 3.9; wire_c_per_micron[1][2] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][2], miller_value[1][2], horiz_dielectric_constant[1][2], vert_dielectric_constant[1][2], fringe_cap); //Nominal projections for commodity DRAM wordline/bitline wire_pitch[1][3] = 2 * 0.065; wire_c_per_micron[1][3] = 52.5e-15 / (256 * 2 * 0.065); wire_r_per_micron[1][3] = 12 / 0.065; } else if (tech == 45) { //Aggressive projections. wire_pitch[0][0] = 2.5 * g_ip->F_sz_um; aspect_ratio[0][0] = 3.0; wire_width = wire_pitch[0][0] / 2; wire_thickness = aspect_ratio[0][0] * wire_width; wire_spacing = wire_pitch[0][0] - wire_width; barrier_thickness = 0; dishing_thickness = 0; alpha_scatter = 1; wire_r_per_micron[0][0] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][0] = 0.315; miller_value[0][0] = 1.5; horiz_dielectric_constant[0][0] = 1.958; vert_dielectric_constant[0][0] = 3.9; fringe_cap = 0.115e-15; wire_c_per_micron[0][0] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][0] , miller_value[0][0] , horiz_dielectric_constant[0][0] , vert_dielectric_constant[0][0] , fringe_cap); wire_pitch[0][1] = 4 * g_ip->F_sz_um; wire_width = wire_pitch[0][1] / 2; aspect_ratio[0][1] = 3.0; wire_thickness = aspect_ratio[0][1] * wire_width; wire_spacing = wire_pitch[0][1] - wire_width; wire_r_per_micron[0][1] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][1] = 0.315; miller_value[0][1] = 1.5; horiz_dielectric_constant[0][1] = 1.958; vert_dielectric_constant[0][1] = 3.9; wire_c_per_micron[0][1] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][1], miller_value[0][1], horiz_dielectric_constant[0][1], vert_dielectric_constant[0][1], fringe_cap); wire_pitch[0][2] = 8 * g_ip->F_sz_um; aspect_ratio[0][2] = 3.0; wire_width = wire_pitch[0][2] / 2; wire_thickness = aspect_ratio[0][2] * wire_width; wire_spacing = wire_pitch[0][2] - wire_width; wire_r_per_micron[0][2] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][2] = 0.63; miller_value[0][2] = 1.5; horiz_dielectric_constant[0][2] = 1.958; vert_dielectric_constant[0][2] = 3.9; wire_c_per_micron[0][2] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][2], miller_value[0][2], horiz_dielectric_constant[0][2], vert_dielectric_constant[0][2], fringe_cap); //Conservative projections wire_pitch[1][0] = 2.5 * g_ip->F_sz_um; aspect_ratio[1][0] = 2.0; wire_width = wire_pitch[1][0] / 2; wire_thickness = aspect_ratio[1][0] * wire_width; wire_spacing = wire_pitch[1][0] - wire_width; barrier_thickness = 0.004; dishing_thickness = 0; alpha_scatter = 1; wire_r_per_micron[1][0] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][0] = 0.315; miller_value[1][0] = 1.5; horiz_dielectric_constant[1][0] = 2.46; vert_dielectric_constant[1][0] = 3.9; fringe_cap = 0.115e-15; wire_c_per_micron[1][0] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][0], miller_value[1][0], horiz_dielectric_constant[1][0], vert_dielectric_constant[1][0], fringe_cap); wire_pitch[1][1] = 4 * g_ip->F_sz_um; wire_width = wire_pitch[1][1] / 2; aspect_ratio[1][1] = 2.0; wire_thickness = aspect_ratio[1][1] * wire_width; wire_spacing = wire_pitch[1][1] - wire_width; wire_r_per_micron[1][1] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][1] = 0.315; miller_value[1][1] = 1.5; horiz_dielectric_constant[1][1] = 2.46; vert_dielectric_constant[1][1] = 3.9; fringe_cap = 0.115e-15; wire_c_per_micron[1][1] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][1], miller_value[1][1], horiz_dielectric_constant[1][1], vert_dielectric_constant[1][1], fringe_cap); wire_pitch[1][2] = 8 * g_ip->F_sz_um; aspect_ratio[1][2] = 2.2; wire_width = wire_pitch[1][2] / 2; wire_thickness = aspect_ratio[1][2] * wire_width; wire_spacing = wire_pitch[1][2] - wire_width; dishing_thickness = 0.1 * wire_thickness; wire_r_per_micron[1][2] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][2] = 0.55; miller_value[1][2] = 1.5; horiz_dielectric_constant[1][2] = 2.46; vert_dielectric_constant[1][2] = 3.9; wire_c_per_micron[1][2] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][2], miller_value[1][2], horiz_dielectric_constant[1][2], vert_dielectric_constant[1][2], fringe_cap); //Nominal projections for commodity DRAM wordline/bitline wire_pitch[1][3] = 2 * 0.045; wire_c_per_micron[1][3] = 37.5e-15 / (256 * 2 * 0.045); wire_r_per_micron[1][3] = 12 / 0.045; } else if (tech == 32) { //Aggressive projections. wire_pitch[0][0] = 2.5 * g_ip->F_sz_um; aspect_ratio[0][0] = 3.0; wire_width = wire_pitch[0][0] / 2; wire_thickness = aspect_ratio[0][0] * wire_width; wire_spacing = wire_pitch[0][0] - wire_width; barrier_thickness = 0; dishing_thickness = 0; alpha_scatter = 1; wire_r_per_micron[0][0] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][0] = 0.21; miller_value[0][0] = 1.5; horiz_dielectric_constant[0][0] = 1.664; vert_dielectric_constant[0][0] = 3.9; fringe_cap = 0.115e-15; wire_c_per_micron[0][0] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][0], miller_value[0][0], horiz_dielectric_constant[0][0], vert_dielectric_constant[0][0], fringe_cap); wire_pitch[0][1] = 4 * g_ip->F_sz_um; wire_width = wire_pitch[0][1] / 2; aspect_ratio[0][1] = 3.0; wire_thickness = aspect_ratio[0][1] * wire_width; wire_spacing = wire_pitch[0][1] - wire_width; wire_r_per_micron[0][1] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][1] = 0.21; miller_value[0][1] = 1.5; horiz_dielectric_constant[0][1] = 1.664; vert_dielectric_constant[0][1] = 3.9; wire_c_per_micron[0][1] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][1], miller_value[0][1], horiz_dielectric_constant[0][1], vert_dielectric_constant[0][1], fringe_cap); wire_pitch[0][2] = 8 * g_ip->F_sz_um; aspect_ratio[0][2] = 3.0; wire_width = wire_pitch[0][2] / 2; wire_thickness = aspect_ratio[0][2] * wire_width; wire_spacing = wire_pitch[0][2] - wire_width; wire_r_per_micron[0][2] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][2] = 0.42; miller_value[0][2] = 1.5; horiz_dielectric_constant[0][2] = 1.664; vert_dielectric_constant[0][2] = 3.9; wire_c_per_micron[0][2] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][2], miller_value[0][2], horiz_dielectric_constant[0][2], vert_dielectric_constant[0][2], fringe_cap); //Conservative projections wire_pitch[1][0] = 2.5 * g_ip->F_sz_um; aspect_ratio[1][0] = 2.0; wire_width = wire_pitch[1][0] / 2; wire_thickness = aspect_ratio[1][0] * wire_width; wire_spacing = wire_pitch[1][0] - wire_width; barrier_thickness = 0.003; dishing_thickness = 0; alpha_scatter = 1; wire_r_per_micron[1][0] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][0] = 0.21; miller_value[1][0] = 1.5; horiz_dielectric_constant[1][0] = 2.214; vert_dielectric_constant[1][0] = 3.9; fringe_cap = 0.115e-15; wire_c_per_micron[1][0] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][0], miller_value[1][0], horiz_dielectric_constant[1][0], vert_dielectric_constant[1][0], fringe_cap); wire_pitch[1][1] = 4 * g_ip->F_sz_um; aspect_ratio[1][1] = 2.0; wire_width = wire_pitch[1][1] / 2; wire_thickness = aspect_ratio[1][1] * wire_width; wire_spacing = wire_pitch[1][1] - wire_width; wire_r_per_micron[1][1] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][1] = 0.21; miller_value[1][1] = 1.5; horiz_dielectric_constant[1][1] = 2.214; vert_dielectric_constant[1][1] = 3.9; wire_c_per_micron[1][1] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][1], miller_value[1][1], horiz_dielectric_constant[1][1], vert_dielectric_constant[1][1], fringe_cap); wire_pitch[1][2] = 8 * g_ip->F_sz_um; aspect_ratio[1][2] = 2.2; wire_width = wire_pitch[1][2] / 2; wire_thickness = aspect_ratio[1][2] * wire_width; wire_spacing = wire_pitch[1][2] - wire_width; dishing_thickness = 0.1 * wire_thickness; wire_r_per_micron[1][2] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][2] = 0.385; miller_value[1][2] = 1.5; horiz_dielectric_constant[1][2] = 2.214; vert_dielectric_constant[1][2] = 3.9; wire_c_per_micron[1][2] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][2], miller_value[1][2], horiz_dielectric_constant[1][2], vert_dielectric_constant[1][2], fringe_cap); //Nominal projections for commodity DRAM wordline/bitline wire_pitch[1][3] = 2 * 0.032;//micron wire_c_per_micron[1][3] = 31e-15 / (256 * 2 * 0.032);//F/micron wire_r_per_micron[1][3] = 12 / 0.032;//ohm/micron } else if (tech == 22) { //Aggressive projections. wire_pitch[0][0] = 2.5 * g_ip->F_sz_um;//local aspect_ratio[0][0] = 3.0; wire_width = wire_pitch[0][0] / 2; wire_thickness = aspect_ratio[0][0] * wire_width; wire_spacing = wire_pitch[0][0] - wire_width; barrier_thickness = 0; dishing_thickness = 0; alpha_scatter = 1; wire_r_per_micron[0][0] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][0] = 0.15; miller_value[0][0] = 1.5; horiz_dielectric_constant[0][0] = 1.414; vert_dielectric_constant[0][0] = 3.9; fringe_cap = 0.115e-15; wire_c_per_micron[0][0] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][0], miller_value[0][0], horiz_dielectric_constant[0][0], vert_dielectric_constant[0][0], fringe_cap); wire_pitch[0][1] = 4 * g_ip->F_sz_um;//semi-global wire_width = wire_pitch[0][1] / 2; aspect_ratio[0][1] = 3.0; wire_thickness = aspect_ratio[0][1] * wire_width; wire_spacing = wire_pitch[0][1] - wire_width; wire_r_per_micron[0][1] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][1] = 0.15; miller_value[0][1] = 1.5; horiz_dielectric_constant[0][1] = 1.414; vert_dielectric_constant[0][1] = 3.9; wire_c_per_micron[0][1] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][1], miller_value[0][1], horiz_dielectric_constant[0][1], vert_dielectric_constant[0][1], fringe_cap); wire_pitch[0][2] = 8 * g_ip->F_sz_um;//global aspect_ratio[0][2] = 3.0; wire_width = wire_pitch[0][2] / 2; wire_thickness = aspect_ratio[0][2] * wire_width; wire_spacing = wire_pitch[0][2] - wire_width; wire_r_per_micron[0][2] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][2] = 0.3; miller_value[0][2] = 1.5; horiz_dielectric_constant[0][2] = 1.414; vert_dielectric_constant[0][2] = 3.9; wire_c_per_micron[0][2] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][2], miller_value[0][2], horiz_dielectric_constant[0][2], vert_dielectric_constant[0][2], fringe_cap); // //************************* // wire_pitch[0][4] = 16 * g_ip.F_sz_um;//global // aspect_ratio = 3.0; // wire_width = wire_pitch[0][4] / 2; // wire_thickness = aspect_ratio * wire_width; // wire_spacing = wire_pitch[0][4] - wire_width; // wire_r_per_micron[0][4] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, // wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); // ild_thickness = 0.3; // wire_c_per_micron[0][4] = wire_capacitance(wire_width, wire_thickness, wire_spacing, // ild_thickness, miller_value, horiz_dielectric_constant, vert_dielectric_constant, // fringe_cap); // // wire_pitch[0][5] = 24 * g_ip.F_sz_um;//global // aspect_ratio = 3.0; // wire_width = wire_pitch[0][5] / 2; // wire_thickness = aspect_ratio * wire_width; // wire_spacing = wire_pitch[0][5] - wire_width; // wire_r_per_micron[0][5] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, // wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); // ild_thickness = 0.3; // wire_c_per_micron[0][5] = wire_capacitance(wire_width, wire_thickness, wire_spacing, // ild_thickness, miller_value, horiz_dielectric_constant, vert_dielectric_constant, // fringe_cap); // // wire_pitch[0][6] = 32 * g_ip.F_sz_um;//global // aspect_ratio = 3.0; // wire_width = wire_pitch[0][6] / 2; // wire_thickness = aspect_ratio * wire_width; // wire_spacing = wire_pitch[0][6] - wire_width; // wire_r_per_micron[0][6] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, // wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); // ild_thickness = 0.3; // wire_c_per_micron[0][6] = wire_capacitance(wire_width, wire_thickness, wire_spacing, // ild_thickness, miller_value, horiz_dielectric_constant, vert_dielectric_constant, // fringe_cap); //************************* //Conservative projections wire_pitch[1][0] = 2.5 * g_ip->F_sz_um; aspect_ratio[1][0] = 2.0; wire_width = wire_pitch[1][0] / 2; wire_thickness = aspect_ratio[1][0] * wire_width; wire_spacing = wire_pitch[1][0] - wire_width; barrier_thickness = 0.003; dishing_thickness = 0; alpha_scatter = 1.05; wire_r_per_micron[1][0] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][0] = 0.15; miller_value[1][0] = 1.5; horiz_dielectric_constant[1][0] = 2.104; vert_dielectric_constant[1][0] = 3.9; fringe_cap = 0.115e-15; wire_c_per_micron[1][0] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][0], miller_value[1][0], horiz_dielectric_constant[1][0], vert_dielectric_constant[1][0], fringe_cap); wire_pitch[1][1] = 4 * g_ip->F_sz_um; wire_width = wire_pitch[1][1] / 2; aspect_ratio[1][1] = 2.0; wire_thickness = aspect_ratio[1][1] * wire_width; wire_spacing = wire_pitch[1][1] - wire_width; wire_r_per_micron[1][1] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][1] = 0.15; miller_value[1][1] = 1.5; horiz_dielectric_constant[1][1] = 2.104; vert_dielectric_constant[1][1] = 3.9; wire_c_per_micron[1][1] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][1], miller_value[1][1], horiz_dielectric_constant[1][1], vert_dielectric_constant[1][1], fringe_cap); wire_pitch[1][2] = 8 * g_ip->F_sz_um; aspect_ratio[1][2] = 2.2; wire_width = wire_pitch[1][2] / 2; wire_thickness = aspect_ratio[1][2] * wire_width; wire_spacing = wire_pitch[1][2] - wire_width; dishing_thickness = 0.1 * wire_thickness; wire_r_per_micron[1][2] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][2] = 0.275; miller_value[1][2] = 1.5; horiz_dielectric_constant[1][2] = 2.104; vert_dielectric_constant[1][2] = 3.9; wire_c_per_micron[1][2] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][2], miller_value[1][2], horiz_dielectric_constant[1][2], vert_dielectric_constant[1][2], fringe_cap); //Nominal projections for commodity DRAM wordline/bitline wire_pitch[1][3] = 2 * 0.022;//micron wire_c_per_micron[1][3] = 31e-15 / (256 * 2 * 0.022);//F/micron wire_r_per_micron[1][3] = 12 / 0.022;//ohm/micron //****************** // wire_pitch[1][4] = 16 * g_ip.F_sz_um; // aspect_ratio = 2.2; // wire_width = wire_pitch[1][4] / 2; // wire_thickness = aspect_ratio * wire_width; // wire_spacing = wire_pitch[1][4] - wire_width; // dishing_thickness = 0.1 * wire_thickness; // wire_r_per_micron[1][4] = wire_resistance(CU_RESISTIVITY, wire_width, // wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); // ild_thickness = 0.275; // wire_c_per_micron[1][4] = wire_capacitance(wire_width, wire_thickness, wire_spacing, // ild_thickness, miller_value, horiz_dielectric_constant, vert_dielectric_constant, // fringe_cap); // // wire_pitch[1][5] = 24 * g_ip.F_sz_um; // aspect_ratio = 2.2; // wire_width = wire_pitch[1][5] / 2; // wire_thickness = aspect_ratio * wire_width; // wire_spacing = wire_pitch[1][5] - wire_width; // dishing_thickness = 0.1 * wire_thickness; // wire_r_per_micron[1][5] = wire_resistance(CU_RESISTIVITY, wire_width, // wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); // ild_thickness = 0.275; // wire_c_per_micron[1][5] = wire_capacitance(wire_width, wire_thickness, wire_spacing, // ild_thickness, miller_value, horiz_dielectric_constant, vert_dielectric_constant, // fringe_cap); // // wire_pitch[1][6] = 32 * g_ip.F_sz_um; // aspect_ratio = 2.2; // wire_width = wire_pitch[1][6] / 2; // wire_thickness = aspect_ratio * wire_width; // wire_spacing = wire_pitch[1][6] - wire_width; // dishing_thickness = 0.1 * wire_thickness; // wire_r_per_micron[1][6] = wire_resistance(CU_RESISTIVITY, wire_width, // wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); // ild_thickness = 0.275; // wire_c_per_micron[1][6] = wire_capacitance(wire_width, wire_thickness, wire_spacing, // ild_thickness, miller_value, horiz_dielectric_constant, vert_dielectric_constant, // fringe_cap); } else if (tech == 16) { //Aggressive projections. wire_pitch[0][0] = 2.5 * g_ip->F_sz_um;//local aspect_ratio[0][0] = 3.0; wire_width = wire_pitch[0][0] / 2; wire_thickness = aspect_ratio[0][0] * wire_width; wire_spacing = wire_pitch[0][0] - wire_width; barrier_thickness = 0; dishing_thickness = 0; alpha_scatter = 1; wire_r_per_micron[0][0] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][0] = 0.108; miller_value[0][0] = 1.5; horiz_dielectric_constant[0][0] = 1.202; vert_dielectric_constant[0][0] = 3.9; fringe_cap = 0.115e-15; wire_c_per_micron[0][0] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][0], miller_value[0][0], horiz_dielectric_constant[0][0], vert_dielectric_constant[0][0], fringe_cap); wire_pitch[0][1] = 4 * g_ip->F_sz_um;//semi-global aspect_ratio[0][1] = 3.0; wire_width = wire_pitch[0][1] / 2; wire_thickness = aspect_ratio[0][1] * wire_width; wire_spacing = wire_pitch[0][1] - wire_width; wire_r_per_micron[0][1] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][1] = 0.108; miller_value[0][1] = 1.5; horiz_dielectric_constant[0][1] = 1.202; vert_dielectric_constant[0][1] = 3.9; wire_c_per_micron[0][1] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][1], miller_value[0][1], horiz_dielectric_constant[0][1], vert_dielectric_constant[0][1], fringe_cap); wire_pitch[0][2] = 8 * g_ip->F_sz_um;//global aspect_ratio[0][2] = 3.0; wire_width = wire_pitch[0][2] / 2; wire_thickness = aspect_ratio[0][2] * wire_width; wire_spacing = wire_pitch[0][2] - wire_width; wire_r_per_micron[0][2] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[0][2] = 0.216; miller_value[0][2] = 1.5; horiz_dielectric_constant[0][2] = 1.202; vert_dielectric_constant[0][2] = 3.9; wire_c_per_micron[0][2] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[0][2], miller_value[0][2], horiz_dielectric_constant[0][2], vert_dielectric_constant[0][2], fringe_cap); // //************************* // wire_pitch[0][4] = 16 * g_ip.F_sz_um;//global // aspect_ratio = 3.0; // wire_width = wire_pitch[0][4] / 2; // wire_thickness = aspect_ratio * wire_width; // wire_spacing = wire_pitch[0][4] - wire_width; // wire_r_per_micron[0][4] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, // wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); // ild_thickness = 0.3; // wire_c_per_micron[0][4] = wire_capacitance(wire_width, wire_thickness, wire_spacing, // ild_thickness, miller_value, horiz_dielectric_constant, vert_dielectric_constant, // fringe_cap); // // wire_pitch[0][5] = 24 * g_ip.F_sz_um;//global // aspect_ratio = 3.0; // wire_width = wire_pitch[0][5] / 2; // wire_thickness = aspect_ratio * wire_width; // wire_spacing = wire_pitch[0][5] - wire_width; // wire_r_per_micron[0][5] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, // wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); // ild_thickness = 0.3; // wire_c_per_micron[0][5] = wire_capacitance(wire_width, wire_thickness, wire_spacing, // ild_thickness, miller_value, horiz_dielectric_constant, vert_dielectric_constant, // fringe_cap); // // wire_pitch[0][6] = 32 * g_ip.F_sz_um;//global // aspect_ratio = 3.0; // wire_width = wire_pitch[0][6] / 2; // wire_thickness = aspect_ratio * wire_width; // wire_spacing = wire_pitch[0][6] - wire_width; // wire_r_per_micron[0][6] = wire_resistance(BULK_CU_RESISTIVITY, wire_width, // wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); // ild_thickness = 0.3; // wire_c_per_micron[0][6] = wire_capacitance(wire_width, wire_thickness, wire_spacing, // ild_thickness, miller_value, horiz_dielectric_constant, vert_dielectric_constant, // fringe_cap); //************************* //Conservative projections wire_pitch[1][0] = 2.5 * g_ip->F_sz_um; aspect_ratio[1][0] = 2.0; wire_width = wire_pitch[1][0] / 2; wire_thickness = aspect_ratio[1][0] * wire_width; wire_spacing = wire_pitch[1][0] - wire_width; barrier_thickness = 0.002; dishing_thickness = 0; alpha_scatter = 1.05; wire_r_per_micron[1][0] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][0] = 0.108; miller_value[1][0] = 1.5; horiz_dielectric_constant[1][0] = 1.998; vert_dielectric_constant[1][0] = 3.9; fringe_cap = 0.115e-15; wire_c_per_micron[1][0] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][0], miller_value[1][0], horiz_dielectric_constant[1][0], vert_dielectric_constant[1][0], fringe_cap); wire_pitch[1][1] = 4 * g_ip->F_sz_um; wire_width = wire_pitch[1][1] / 2; aspect_ratio[1][1] = 2.0; wire_thickness = aspect_ratio[1][1] * wire_width; wire_spacing = wire_pitch[1][1] - wire_width; wire_r_per_micron[1][1] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][1] = 0.108; miller_value[1][1] = 1.5; horiz_dielectric_constant[1][1] = 1.998; vert_dielectric_constant[1][1] = 3.9; wire_c_per_micron[1][1] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][1], miller_value[1][1], horiz_dielectric_constant[1][1], vert_dielectric_constant[1][1], fringe_cap); wire_pitch[1][2] = 8 * g_ip->F_sz_um; aspect_ratio[1][2] = 2.2; wire_width = wire_pitch[1][2] / 2; wire_thickness = aspect_ratio[1][2] * wire_width; wire_spacing = wire_pitch[1][2] - wire_width; dishing_thickness = 0.1 * wire_thickness; wire_r_per_micron[1][2] = wire_resistance(CU_RESISTIVITY, wire_width, wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); ild_thickness[1][2] = 0.198; miller_value[1][2] = 1.5; horiz_dielectric_constant[1][2] = 1.998; vert_dielectric_constant[1][2] = 3.9; wire_c_per_micron[1][2] = wire_capacitance(wire_width, wire_thickness, wire_spacing, ild_thickness[1][2], miller_value[1][2], horiz_dielectric_constant[1][2], vert_dielectric_constant[1][2], fringe_cap); //Nominal projections for commodity DRAM wordline/bitline wire_pitch[1][3] = 2 * 0.016;//micron wire_c_per_micron[1][3] = 31e-15 / (256 * 2 * 0.016);//F/micron wire_r_per_micron[1][3] = 12 / 0.016;//ohm/micron //****************** // wire_pitch[1][4] = 16 * g_ip.F_sz_um; // aspect_ratio = 2.2; // wire_width = wire_pitch[1][4] / 2; // wire_thickness = aspect_ratio * wire_width; // wire_spacing = wire_pitch[1][4] - wire_width; // dishing_thickness = 0.1 * wire_thickness; // wire_r_per_micron[1][4] = wire_resistance(CU_RESISTIVITY, wire_width, // wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); // ild_thickness = 0.275; // wire_c_per_micron[1][4] = wire_capacitance(wire_width, wire_thickness, wire_spacing, // ild_thickness, miller_value, horiz_dielectric_constant, vert_dielectric_constant, // fringe_cap); // // wire_pitch[1][5] = 24 * g_ip.F_sz_um; // aspect_ratio = 2.2; // wire_width = wire_pitch[1][5] / 2; // wire_thickness = aspect_ratio * wire_width; // wire_spacing = wire_pitch[1][5] - wire_width; // dishing_thickness = 0.1 * wire_thickness; // wire_r_per_micron[1][5] = wire_resistance(CU_RESISTIVITY, wire_width, // wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); // ild_thickness = 0.275; // wire_c_per_micron[1][5] = wire_capacitance(wire_width, wire_thickness, wire_spacing, // ild_thickness, miller_value, horiz_dielectric_constant, vert_dielectric_constant, // fringe_cap); // // wire_pitch[1][6] = 32 * g_ip.F_sz_um; // aspect_ratio = 2.2; // wire_width = wire_pitch[1][6] / 2; // wire_thickness = aspect_ratio * wire_width; // wire_spacing = wire_pitch[1][6] - wire_width; // dishing_thickness = 0.1 * wire_thickness; // wire_r_per_micron[1][6] = wire_resistance(CU_RESISTIVITY, wire_width, // wire_thickness, barrier_thickness, dishing_thickness, alpha_scatter); // ild_thickness = 0.275; // wire_c_per_micron[1][6] = wire_capacitance(wire_width, wire_thickness, wire_spacing, // ild_thickness, miller_value, horiz_dielectric_constant, vert_dielectric_constant, // fringe_cap); } g_tp.wire_local.pitch += curr_alpha * wire_pitch[g_ip->ic_proj_type][(ram_cell_tech_type == comm_dram)?3:0]; g_tp.wire_local.R_per_um += curr_alpha * wire_r_per_micron[g_ip->ic_proj_type][(ram_cell_tech_type == comm_dram)?3:0]; g_tp.wire_local.C_per_um += curr_alpha * wire_c_per_micron[g_ip->ic_proj_type][(ram_cell_tech_type == comm_dram)?3:0]; g_tp.wire_local.aspect_ratio += curr_alpha * aspect_ratio[g_ip->ic_proj_type][(ram_cell_tech_type == comm_dram)?3:0]; g_tp.wire_local.ild_thickness += curr_alpha * ild_thickness[g_ip->ic_proj_type][(ram_cell_tech_type == comm_dram)?3:0]; g_tp.wire_local.miller_value += curr_alpha * miller_value[g_ip->ic_proj_type][(ram_cell_tech_type == comm_dram)?3:0]; g_tp.wire_local.horiz_dielectric_constant += curr_alpha* horiz_dielectric_constant[g_ip->ic_proj_type][(ram_cell_tech_type == comm_dram)?3:0]; g_tp.wire_local.vert_dielectric_constant += curr_alpha* vert_dielectric_constant [g_ip->ic_proj_type][(ram_cell_tech_type == comm_dram)?3:0]; g_tp.wire_inside_mat.pitch += curr_alpha * wire_pitch[g_ip->ic_proj_type][g_ip->wire_is_mat_type]; g_tp.wire_inside_mat.R_per_um += curr_alpha* wire_r_per_micron[g_ip->ic_proj_type][g_ip->wire_is_mat_type]; g_tp.wire_inside_mat.C_per_um += curr_alpha* wire_c_per_micron[g_ip->ic_proj_type][g_ip->wire_is_mat_type]; g_tp.wire_inside_mat.aspect_ratio += curr_alpha * aspect_ratio[g_ip->ic_proj_type][g_ip->wire_is_mat_type]; g_tp.wire_inside_mat.ild_thickness += curr_alpha * ild_thickness[g_ip->ic_proj_type][g_ip->wire_is_mat_type]; g_tp.wire_inside_mat.miller_value += curr_alpha * miller_value[g_ip->ic_proj_type][g_ip->wire_is_mat_type]; g_tp.wire_inside_mat.horiz_dielectric_constant += curr_alpha* horiz_dielectric_constant[g_ip->ic_proj_type][g_ip->wire_is_mat_type]; g_tp.wire_inside_mat.vert_dielectric_constant += curr_alpha* vert_dielectric_constant [g_ip->ic_proj_type][g_ip->wire_is_mat_type]; g_tp.wire_outside_mat.pitch += curr_alpha * wire_pitch[g_ip->ic_proj_type][g_ip->wire_os_mat_type]; g_tp.wire_outside_mat.R_per_um += curr_alpha*wire_r_per_micron[g_ip->ic_proj_type][g_ip->wire_os_mat_type]; g_tp.wire_outside_mat.C_per_um += curr_alpha*wire_c_per_micron[g_ip->ic_proj_type][g_ip->wire_os_mat_type]; g_tp.wire_outside_mat.aspect_ratio += curr_alpha * aspect_ratio[g_ip->ic_proj_type][g_ip->wire_os_mat_type]; g_tp.wire_outside_mat.ild_thickness += curr_alpha * ild_thickness[g_ip->ic_proj_type][g_ip->wire_os_mat_type]; g_tp.wire_outside_mat.miller_value += curr_alpha * miller_value[g_ip->ic_proj_type][g_ip->wire_os_mat_type]; g_tp.wire_outside_mat.horiz_dielectric_constant += curr_alpha* horiz_dielectric_constant[g_ip->ic_proj_type][g_ip->wire_os_mat_type]; g_tp.wire_outside_mat.vert_dielectric_constant += curr_alpha* vert_dielectric_constant [g_ip->ic_proj_type][g_ip->wire_os_mat_type]; g_tp.unit_len_wire_del = g_tp.wire_inside_mat.R_per_um * g_tp.wire_inside_mat.C_per_um / 2; g_tp.sense_delay += curr_alpha *SENSE_AMP_D; g_tp.sense_dy_power += curr_alpha *SENSE_AMP_P; // g_tp.horiz_dielectric_constant += horiz_dielectric_constant; // g_tp.vert_dielectric_constant += vert_dielectric_constant; // g_tp.aspect_ratio += aspect_ratio; // g_tp.miller_value += miller_value; // g_tp.ild_thickness += ild_thickness; } g_tp.fringe_cap = fringe_cap; double rd = tr_R_on(g_tp.min_w_nmos_, NCH, 1); double p_to_n_sizing_r = pmos_to_nmos_sz_ratio(); double c_load = gate_C(g_tp.min_w_nmos_ * (1 + p_to_n_sizing_r), 0.0); double tf = rd * c_load; g_tp.kinv = horowitz(0, tf, 0.5, 0.5, RISE); double KLOAD = 1; c_load = KLOAD * (drain_C_(g_tp.min_w_nmos_, NCH, 1, 1, g_tp.cell_h_def) + drain_C_(g_tp.min_w_nmos_ * p_to_n_sizing_r, PCH, 1, 1, g_tp.cell_h_def) + gate_C(g_tp.min_w_nmos_ * 4 * (1 + p_to_n_sizing_r), 0.0)); tf = rd * c_load; g_tp.FO4 = horowitz(0, tf, 0.5, 0.5, RISE); }
mlebeane/wattwatcher
fast_mcpat/cacti/technology.cc
C++
bsd-3-clause
143,090
# -*- coding: utf-8 -*- from functools import update_wrapper import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils import six from django.utils.translation import ugettext_lazy as _ from cms import constants from cms.utils.compat.urls import urljoin __all__ = ['get_cms_setting'] class VERIFIED: pass # need a unique identifier for CMS_LANGUAGES def default(name): def decorator(wrapped): def wrapper(): if hasattr(settings, name): return getattr(settings, name) return wrapped() update_wrapper(wrapper, wrapped) return wrapped return decorator DEFAULTS = { 'TEMPLATE_INHERITANCE': True, 'PLACEHOLDER_CONF': {}, 'PERMISSION': False, # Whether to use raw ID lookups for users when PERMISSION is True 'RAW_ID_USERS': False, 'PUBLIC_FOR': 'all', 'CONTENT_CACHE_DURATION': 60, 'APPHOOKS': [], 'TOOLBARS': [], 'SITE_CHOICES_CACHE_KEY': 'CMS:site_choices', 'PAGE_CHOICES_CACHE_KEY': 'CMS:page_choices', 'MEDIA_PATH': 'cms/', 'PAGE_MEDIA_PATH': 'cms_page_media/', 'TITLE_CHARACTER': '+', 'PAGE_CACHE': True, 'PLACEHOLDER_CACHE': True, 'PLUGIN_CACHE': True, 'CACHE_PREFIX': 'cms-', 'PLUGIN_PROCESSORS': [], 'PLUGIN_CONTEXT_PROCESSORS': [], 'UNIHANDECODE_VERSION': None, 'UNIHANDECODE_DECODERS': ['ja', 'zh', 'kr', 'vn', 'diacritic'], 'UNIHANDECODE_DEFAULT_DECODER': 'diacritic', 'MAX_PAGE_PUBLISH_REVERSIONS': 10, 'MAX_PAGE_HISTORY_REVERSIONS': 15, 'TOOLBAR_URL__EDIT_ON': 'edit', 'TOOLBAR_URL__EDIT_OFF': 'edit_off', 'TOOLBAR_URL__BUILD': 'build', 'ADMIN_NAMESPACE': 'admin', } def get_cache_durations(): return { 'menus': getattr(settings, 'MENU_CACHE_DURATION', 60 * 60), 'content': get_cms_setting('CONTENT_CACHE_DURATION'), 'permissions': 60 * 60, } @default('CMS_MEDIA_ROOT') def get_media_root(): return os.path.join(settings.MEDIA_ROOT, get_cms_setting('MEDIA_PATH')) @default('CMS_MEDIA_URL') def get_media_url(): return urljoin(settings.MEDIA_URL, get_cms_setting('MEDIA_PATH')) @default('CMS_TOOLBAR_URL__EDIT_ON') def get_toolbar_url__edit_on(): return get_cms_setting('TOOLBAR_URL__EDIT_ON') @default('CMS_TOOLBAR_URL__EDIT_OFF') def get_toolbar_url__edit_off(): return get_cms_setting('TOOLBAR_URL__EDIT_OFF') @default('CMS_TOOLBAR_URL__BUILD') def get_toolbar_url__build(): return get_cms_setting('TOOLBAR_URL__BUILD') def get_templates(): from cms.utils.django_load import load_from_file if getattr(settings, 'CMS_TEMPLATES_DIR', False): tpldir = getattr(settings, 'CMS_TEMPLATES_DIR', False) # CMS_TEMPLATES_DIR can either be a string poiting to the templates directory # or a dictionary holding 'site: template dir' entries if isinstance(tpldir, dict): tpldir = tpldir[settings.SITE_ID] # We must extract the relative path of CMS_TEMPLATES_DIR to the neares # valid templates directory. Here we mimick what the filesystem and # app_directories template loaders do prefix = '' # Relative to TEMPLATE_DIRS for filesystem loader for basedir in settings.TEMPLATE_DIRS: if tpldir.find(basedir) == 0: prefix = tpldir.replace(basedir + os.sep, '') break # Relative to 'templates' directory that app_directory scans if not prefix: components = tpldir.split(os.sep) try: prefix = os.path.join(*components[components.index('templates') + 1:]) except ValueError: # If templates is not found we use the directory name as prefix # and hope for the best prefix = os.path.basename(tpldir) config_path = os.path.join(tpldir, '__init__.py') # Try to load templates list and names from the template module # If module file is not present skip configuration and just dump the filenames as templates if config_path: template_module = load_from_file(config_path) templates = [(os.path.join(prefix, data[0].strip()), data[1]) for data in template_module.TEMPLATES.items()] else: templates = list((os.path.join(prefix, tpl), tpl) for tpl in os.listdir(tpldir)) else: templates = list(getattr(settings, 'CMS_TEMPLATES', [])) if get_cms_setting('TEMPLATE_INHERITANCE'): templates.append((constants.TEMPLATE_INHERITANCE_MAGIC, _(constants.TEMPLATE_INHERITANCE_LABEL))) return templates def _ensure_languages_settings(languages): valid_language_keys = ['code', 'name', 'fallbacks', 'hide_untranslated', 'redirect_on_fallback', 'public'] required_language_keys = ['code', 'name'] simple_defaults = ['public', 'redirect_on_fallback', 'hide_untranslated'] if not isinstance(languages, dict): raise ImproperlyConfigured( "CMS_LANGUAGES must be a dictionary with site IDs and 'default'" " as keys. Please check the format.") defaults = languages.pop('default', {}) default_fallbacks = defaults.get('fallbacks') needs_fallbacks = [] for key in defaults: if key not in valid_language_keys: raise ImproperlyConfigured("CMS_LANGUAGES has an invalid property in the default properties: %s" % key) for key in simple_defaults: if key not in defaults: defaults[key] = True for site, language_list in languages.items(): if not isinstance(site, six.integer_types): raise ImproperlyConfigured( "CMS_LANGUAGES can only be filled with integers (site IDs) and 'default'" " for default values. %s is not a valid key." % site) for language_object in language_list: for required_key in required_language_keys: if required_key not in language_object: raise ImproperlyConfigured("CMS_LANGUAGES has a language which is missing the required key %r " "in site %r" % (key, site)) language_code = language_object['code'] for key in language_object: if key not in valid_language_keys: raise ImproperlyConfigured( "CMS_LANGUAGES has invalid key %r in language %r in site %r" % (key, language_code, site) ) if 'fallbacks' not in language_object: if default_fallbacks: language_object['fallbacks'] = default_fallbacks else: needs_fallbacks.append((site, language_object)) for key in simple_defaults: if key not in language_object: language_object[key] = defaults[key] site_fallbacks = {} for site, language_object in needs_fallbacks: if site not in site_fallbacks: site_fallbacks[site] = [lang['code'] for lang in languages[site] if lang['public']] language_object['fallbacks'] = [lang_code for lang_code in site_fallbacks[site] if lang_code != language_object['code']] languages['default'] = defaults languages[VERIFIED] = True # this will be busted by SettingsOverride and cause a re-check return languages def get_languages(): if not isinstance(settings.SITE_ID, six.integer_types): raise ImproperlyConfigured( "SITE_ID must be an integer" ) if not settings.USE_I18N: return _ensure_languages_settings( {settings.SITE_ID: [{'code': settings.LANGUAGE_CODE, 'name': settings.LANGUAGE_CODE}]}) if settings.LANGUAGE_CODE not in dict(settings.LANGUAGES): raise ImproperlyConfigured( 'LANGUAGE_CODE "%s" must have a matching entry in LANGUAGES' % settings.LANGUAGE_CODE ) languages = getattr(settings, 'CMS_LANGUAGES', { settings.SITE_ID: [{'code': code, 'name': _(name)} for code, name in settings.LANGUAGES] }) if VERIFIED in languages: return languages return _ensure_languages_settings(languages) def get_unihandecode_host(): host = getattr(settings, 'CMS_UNIHANDECODE_HOST', None) if not host: return host if host.endswith('/'): return host else: return host + '/' COMPLEX = { 'CACHE_DURATIONS': get_cache_durations, 'MEDIA_ROOT': get_media_root, 'MEDIA_URL': get_media_url, # complex because not prefixed by CMS_ 'TEMPLATES': get_templates, 'LANGUAGES': get_languages, 'UNIHANDECODE_HOST': get_unihandecode_host, 'CMS_TOOLBAR_URL__EDIT_ON': get_toolbar_url__edit_on, 'CMS_TOOLBAR_URL__EDIT_OFF': get_toolbar_url__edit_off, 'CMS_TOOLBAR_URL__BUILD': get_toolbar_url__build, } def get_cms_setting(name): if name in COMPLEX: return COMPLEX[name]() else: return getattr(settings, 'CMS_%s' % name, DEFAULTS[name]) def get_site_id(site): from django.contrib.sites.models import Site if isinstance(site, Site): return site.id try: return int(site) except (TypeError, ValueError): pass return settings.SITE_ID
samirasnoun/django_cms_gallery_image
cms/utils/conf.py
Python
bsd-3-clause
9,303
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/message_loop.h" namespace aura { class DispatcherWin : public base::MessageLoop::Dispatcher { public: DispatcherWin() {} virtual ~DispatcherWin() {} // Overridden from MessageLoop::Dispatcher: virtual bool Dispatch(const base::NativeEvent& event) OVERRIDE; private: DISALLOW_COPY_AND_ASSIGN(DispatcherWin); }; bool DispatcherWin::Dispatch(const base::NativeEvent& msg) { TranslateMessage(&msg); DispatchMessage(&msg); return true; } MessageLoop::Dispatcher* CreateDispatcher() { return new DispatcherWin; } } // namespace aura
JoKaWare/GViews
ui/aura/dispatcher_win.cc
C++
bsd-3-clause
805
<?php /* Prototype : int mb_stripos(string haystack, string needle [, int offset [, string encoding]]) * Description: Finds position of first occurrence of a string within another, case insensitive * Source code: ext/mbstring/mbstring.c * Alias to functions: */ /* * Pass mb_stripos different data types as $haystack arg to test behaviour */ echo "*** Testing mb_stripos() : usage variations ***\n"; // Initialise function arguments not being substituted $needle = b'string_val'; $offset = 0; $encoding = 'utf-8'; //get an unset variable $unset_var = 10; unset ($unset_var); // get a class class classA { public function __toString() { return "Class A object"; } } // heredoc string $heredoc = <<<EOT hello world EOT; // get a resource variable $fp = fopen(__FILE__, "r"); // unexpected values to be passed to $haystack argument $inputs = array( // int data /*1*/ 0, 1, 12345, -2345, // float data /*5*/ 10.5, -10.5, 12.3456789000e10, 12.3456789000E-10, .5, // null data /*10*/ NULL, null, // boolean data /*12*/ true, false, TRUE, FALSE, // empty data /*16*/ "", '', // string data /*18*/ "string", 'string', $heredoc, // object data /*21*/ new classA(), // undefined data /*22*/ @$undefined_var, // unset data /*23*/ @$unset_var, // resource variable /*24*/ $fp ); // loop through each element of $inputs to check the behavior of mb_stripos() $iterator = 1; foreach($inputs as $input) { echo "\n-- Iteration $iterator --\n"; var_dump( mb_stripos($input, $needle, $offset, $encoding)); $iterator++; }; fclose($fp); echo "Done"; ?>
JSchwehn/php
testdata/fuzzdir/corpus/ext_mbstring_tests_mb_stripos_variation1.php
PHP
bsd-3-clause
1,760
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Runs Apple's SunSpider JavaScript benchmark.""" import collections import json import os from telemetry.core import util from telemetry.page import page_measurement from telemetry.page import page_set class SunSpiderMeasurement(page_measurement.PageMeasurement): def CreatePageSet(self, _, options): return page_set.PageSet.FromDict({ 'serving_dirs': ['../../../chrome/test/data/sunspider/'], 'pages': [ { 'url': 'file:///../../../chrome/test/data/sunspider/' 'sunspider-1.0/driver.html' } ] }, os.path.abspath(__file__)) def MeasurePage(self, _, tab, results): js_is_done = """ window.location.pathname.indexOf('results.html') >= 0""" def _IsDone(): return tab.EvaluateJavaScript(js_is_done) util.WaitFor(_IsDone, 300, poll_interval=5) js_get_results = 'JSON.stringify(output);' js_results = json.loads(tab.EvaluateJavaScript(js_get_results)) r = collections.defaultdict(list) totals = [] # js_results is: [{'foo': v1, 'bar': v2}, # {'foo': v3, 'bar': v4}, # ...] for result in js_results: total = 0 for key, value in result.iteritems(): r[key].append(value) total += value totals.append(total) for key, values in r.iteritems(): results.Add(key, 'ms', values, data_type='unimportant') results.Add('Total', 'ms', totals)
jing-bao/pa-chromium
tools/perf/perf_tools/sunspider.py
Python
bsd-3-clause
1,597
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync/test/fake_server/fake_server_http_post_provider.h" #include <utility> #include "base/bind.h" #include "base/location.h" #include "base/threading/thread_restrictions.h" #include "base/time/time.h" #include "components/sync/test/fake_server/fake_server.h" #include "net/base/net_errors.h" namespace fake_server { // static std::atomic_bool FakeServerHttpPostProvider::network_enabled_(true); FakeServerHttpPostProviderFactory::FakeServerHttpPostProviderFactory( const base::WeakPtr<FakeServer>& fake_server, scoped_refptr<base::SequencedTaskRunner> fake_server_task_runner) : fake_server_(fake_server), fake_server_task_runner_(fake_server_task_runner) {} FakeServerHttpPostProviderFactory::~FakeServerHttpPostProviderFactory() = default; scoped_refptr<syncer::HttpPostProviderInterface> FakeServerHttpPostProviderFactory::Create() { return new FakeServerHttpPostProvider(fake_server_, fake_server_task_runner_); } FakeServerHttpPostProvider::FakeServerHttpPostProvider( const base::WeakPtr<FakeServer>& fake_server, scoped_refptr<base::SequencedTaskRunner> fake_server_task_runner) : fake_server_(fake_server), fake_server_task_runner_(fake_server_task_runner), synchronous_post_completion_( base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED), aborted_(false) {} FakeServerHttpPostProvider::~FakeServerHttpPostProvider() = default; void FakeServerHttpPostProvider::SetExtraRequestHeaders(const char* headers) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // TODO(pvalenzuela): Add assertions on this value. extra_request_headers_.assign(headers); } void FakeServerHttpPostProvider::SetURL(const GURL& url) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); request_url_ = url; } void FakeServerHttpPostProvider::SetPostPayload(const char* content_type, int content_length, const char* content) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); request_content_type_.assign(content_type); request_content_.assign(content, content_length); } bool FakeServerHttpPostProvider::MakeSynchronousPost(int* net_error_code, int* http_status_code) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!network_enabled_) { response_.clear(); *net_error_code = net::ERR_INTERNET_DISCONNECTED; *http_status_code = 0; return false; } synchronous_post_completion_.Reset(); aborted_ = false; // It is assumed that a POST is being made to /command. int post_status_code = -1; std::string post_response; bool result = fake_server_task_runner_->PostTask( FROM_HERE, base::BindOnce( &FakeServerHttpPostProvider::HandleCommandOnFakeServerThread, base::RetainedRef(this), base::Unretained(&post_status_code), base::Unretained(&post_response))); if (!result) { response_.clear(); *net_error_code = net::ERR_UNEXPECTED; *http_status_code = 0; return false; } { base::ScopedAllowBaseSyncPrimitivesForTesting allow_wait; synchronous_post_completion_.Wait(); } if (aborted_) { *net_error_code = net::ERR_ABORTED; return false; } // Zero means success. *net_error_code = 0; *http_status_code = post_status_code; response_ = post_response; return true; } int FakeServerHttpPostProvider::GetResponseContentLength() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return response_.length(); } const char* FakeServerHttpPostProvider::GetResponseContent() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return response_.c_str(); } const std::string FakeServerHttpPostProvider::GetResponseHeaderValue( const std::string& name) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return std::string(); } void FakeServerHttpPostProvider::Abort() { // Note: This may be called on any thread, so no |sequence_checker_| here. // The sync thread could be blocked in MakeSynchronousPost(), waiting // for HandleCommandOnFakeServerThread() to be processed and completed. // This causes an immediate unblocking which will be returned as // net::ERR_ABORTED. aborted_ = true; synchronous_post_completion_.Signal(); } // static void FakeServerHttpPostProvider::DisableNetwork() { // Note: This may be called on any thread. network_enabled_ = false; } // static void FakeServerHttpPostProvider::EnableNetwork() { // Note: This may be called on any thread. network_enabled_ = true; } void FakeServerHttpPostProvider::HandleCommandOnFakeServerThread( int* http_status_code, std::string* response) { DCHECK(fake_server_task_runner_->RunsTasksInCurrentSequence()); if (!fake_server_ || aborted_) { // Command explicitly aborted or server destroyed. return; } *http_status_code = fake_server_->HandleCommand(request_content_, response); synchronous_post_completion_.Signal(); } } // namespace fake_server
scheib/chromium
components/sync/test/fake_server/fake_server_http_post_provider.cc
C++
bsd-3-clause
5,309
# -*- coding: utf-8 -*- """ Local settings - Run in Debug mode {% if cookiecutter.use_mailhog == 'y' and cookiecutter.use_docker == 'y' %} - Use mailhog for emails {% else %} - Use console backend for emails {% endif %} - Add Django Debug Toolbar - Add django-extensions as app """ import socket import os from .common import * # noqa # DEBUG # ------------------------------------------------------------------------------ DEBUG = env.bool('DJANGO_DEBUG', default=True) TEMPLATES[0]['OPTIONS']['debug'] = DEBUG # SECRET CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key # Note: This key only used for development and testing. SECRET_KEY = env('DJANGO_SECRET_KEY', default='CHANGEME!!!') # Mail settings # ------------------------------------------------------------------------------ EMAIL_PORT = 1025 {% if cookiecutter.use_mailhog == 'y' and cookiecutter.use_docker == 'y' %} EMAIL_HOST = env("EMAIL_HOST", default='mailhog') {% else %} EMAIL_HOST = 'localhost' EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.console.EmailBackend') {% endif %} # CACHING # ------------------------------------------------------------------------------ CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': '' } } # django-debug-toolbar # ------------------------------------------------------------------------------ MIDDLEWARE += ('debug_toolbar.middleware.DebugToolbarMiddleware',) INSTALLED_APPS += ('debug_toolbar', ) INTERNAL_IPS = ['127.0.0.1', '10.0.2.2', ] # tricks to have debug toolbar when developing with docker if os.environ.get('USE_DOCKER') == 'yes': ip = socket.gethostbyname(socket.gethostname()) INTERNAL_IPS += [ip[:-1] + "1"] DEBUG_TOOLBAR_CONFIG = { 'DISABLE_PANELS': [ 'debug_toolbar.panels.redirects.RedirectsPanel', ], 'SHOW_TEMPLATE_CONTEXT': True, } # django-extensions # ------------------------------------------------------------------------------ INSTALLED_APPS += ('django_extensions', ) # TESTING # ------------------------------------------------------------------------------ TEST_RUNNER = 'django.test.runner.DiscoverRunner' {% if cookiecutter.use_celery == 'y' %} ########## CELERY # In development, all tasks will be executed locally by blocking until the task returns CELERY_ALWAYS_EAGER = True ########## END CELERY {% endif %} # Your local stuff: Below this line define 3rd party library settings # ------------------------------------------------------------------------------
schacki/cookiecutter-django
{{cookiecutter.project_slug}}/config/settings/local.py
Python
bsd-3-clause
2,678
<?php /* Prototype : string sprintf(string $format [, mixed $arg1 [, mixed ...]]) * Description: Return a formatted string * Source code: ext/standard/formatted_print.c */ echo "*** Testing sprintf() : basic functionality - using bool format ***\n"; // Initialise all required variables $format = "format"; $format1 = "%b"; $format2 = "%b %b"; $format3 = "%b %b %b"; $arg1 = TRUE; $arg2 = FALSE; $arg3 = true; // Calling sprintf() with default arguments var_dump( sprintf($format) ); // Calling sprintf() with two arguments var_dump( sprintf($format1, $arg1) ); // Calling sprintf() with three arguments var_dump( sprintf($format2, $arg1, $arg2) ); // Calling sprintf() with four arguments var_dump( sprintf($format3, $arg1, $arg2, $arg3) ); echo "Done"; ?>
JSchwehn/php
testdata/fuzzdir/corpus/ext_standard_tests_strings_sprintf_basic4.php
PHP
bsd-3-clause
771
# (C) Datadog, Inc. 2014-2016 # (C) Cory Watson <cory@stripe.com> 2015-2016 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) # stdlib from collections import defaultdict from urlparse import urlparse import re # 3rd party import requests # project from checks import AgentCheck DEFAULT_MAX_METRICS = 350 PATH = "path" ALIAS = "alias" TYPE = "type" TAGS = "tags" GAUGE = "gauge" RATE = "rate" COUNTER = "counter" DEFAULT_TYPE = GAUGE SUPPORTED_TYPES = { GAUGE: AgentCheck.gauge, RATE: AgentCheck.rate, COUNTER: AgentCheck.increment, } DEFAULT_METRIC_NAMESPACE = "go_expvar" # See http://golang.org/pkg/runtime/#MemStats DEFAULT_GAUGE_MEMSTAT_METRICS = [ # General statistics "Alloc", "TotalAlloc", # Main allocation heap statistics "HeapAlloc", "HeapSys", "HeapIdle", "HeapInuse", "HeapReleased", "HeapObjects", ] DEFAULT_RATE_MEMSTAT_METRICS = [ # General statistics "Lookups", "Mallocs", "Frees", # Garbage collector statistics "PauseTotalNs", "NumGC", ] DEFAULT_METRICS = [{PATH: "memstats/%s" % path, TYPE: GAUGE} for path in DEFAULT_GAUGE_MEMSTAT_METRICS] +\ [{PATH: "memstats/%s" % path, TYPE: RATE} for path in DEFAULT_RATE_MEMSTAT_METRICS] GO_EXPVAR_URL_PATH = "/debug/vars" class GoExpvar(AgentCheck): def __init__(self, name, init_config, agentConfig, instances=None): AgentCheck.__init__(self, name, init_config, agentConfig, instances) self._last_gc_count = defaultdict(int) def _get_data(self, url, instance): ssl_params = { 'ssl': instance.get('ssl'), 'ssl_keyfile': instance.get('ssl_keyfile'), 'ssl_certfile': instance.get('ssl_certfile'), 'ssl_verify': instance.get('ssl_verify'), } for key, param in ssl_params.items(): if param is None: del ssl_params[key] # Load SSL configuration, if available. # ssl_verify can be a bool or a string (http://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification) if isinstance(ssl_params.get('ssl_verify'), bool) or isinstance(ssl_params.get('ssl_verify'), basestring): verify = ssl_params.get('ssl_verify') else: verify = None if ssl_params.get('ssl_certfile') and ssl_params.get('ssl_keyfile'): cert = (ssl_params.get('ssl_certfile'), ssl_params.get('ssl_keyfile')) elif ssl_params.get('ssl_certfile'): cert = ssl_params.get('ssl_certfile') else: cert = None resp = requests.get( url, timeout=10, verify=verify, cert=cert ) resp.raise_for_status() return resp.json() def _load(self, instance): url = instance.get('expvar_url') if not url: raise Exception('GoExpvar instance missing "expvar_url" value.') parsed_url = urlparse(url) # if no path is specified we use the default one if not parsed_url.path: url = parsed_url._replace(path=GO_EXPVAR_URL_PATH).geturl() tags = instance.get('tags', []) tags.append("expvar_url:%s" % url) data = self._get_data(url, instance) metrics = DEFAULT_METRICS + instance.get("metrics", []) max_metrics = instance.get("max_returned_metrics", DEFAULT_MAX_METRICS) namespace = instance.get('namespace', DEFAULT_METRIC_NAMESPACE) return data, tags, metrics, max_metrics, url, namespace def get_gc_collection_histogram(self, data, tags, url, namespace): num_gc = data.get("memstats", {}).get("NumGC") pause_hist = data.get("memstats", {}).get("PauseNs") last_gc_count = self._last_gc_count[url] if last_gc_count == num_gc: # No GC has run. Do nothing return start = last_gc_count % 256 end = (num_gc + 255) % 256 + 1 if start < end: values = pause_hist[start:end] else: values = pause_hist[start:] + pause_hist[:end] self._last_gc_count[url] = num_gc for value in values: self.histogram( self.normalize("memstats.PauseNs", namespace, fix_case=True), value, tags=tags) def check(self, instance): data, tags, metrics, max_metrics, url, namespace = self._load(instance) self.get_gc_collection_histogram(data, tags, url, namespace) self.parse_expvar_data(data, tags, metrics, max_metrics, namespace) def parse_expvar_data(self, data, tags, metrics, max_metrics, namespace): ''' Report all the metrics based on the configuration in instance If a metric is not well configured or is not present in the payload, continue processing metrics but log the information to the info page ''' count = 0 for metric in metrics: path = metric.get(PATH) metric_type = metric.get(TYPE, DEFAULT_TYPE) metric_tags = list(metric.get(TAGS, [])) metric_tags += tags alias = metric.get(ALIAS) if not path: self.warning("Metric %s has no path" % metric) continue if metric_type not in SUPPORTED_TYPES: self.warning("Metric type %s not supported for this check" % metric_type) continue keys = path.split("/") values = self.deep_get(data, keys) if len(values) == 0: self.warning("No results matching path %s" % path) continue tag_by_path = alias is not None for traversed_path, value in values: actual_path = ".".join(traversed_path) path_tag = ["path:%s" % actual_path] if tag_by_path else [] metric_name = alias or self.normalize(actual_path, namespace, fix_case=True) try: float(value) except ValueError: self.log.warning("Unreportable value for path %s: %s" % (path, value)) continue if count >= max_metrics: self.warning("Reporting more metrics than the allowed maximum. " "Please contact support@datadoghq.com for more information.") return SUPPORTED_TYPES[metric_type](self, metric_name, value, metric_tags + path_tag) count += 1 def deep_get(self, content, keys, traversed_path=None): ''' Allow to retrieve content nested inside a several layers deep dict/list Examples: -content: { "key1": { "key2" : [ { "name" : "object1", "value" : 42 }, { "name" : "object2", "value" : 72 } ] } } -keys: ["key1", "key2", "1", "value"] would return [(["key1", "key2", "1", "value"], 72)] -keys: ["key1", "key2", "1", "*"] would return [(["key1", "key2", "1", "value"], 72), (["key1", "key2", "1", "name"], "object2")] -keys: ["key1", "key2", "*", "value"] would return [(["key1", "key2", "1", "value"], 72), (["key1", "key2", "0", "value"], 42)] ''' if traversed_path is None: traversed_path = [] if keys == []: return [(traversed_path, content)] key = keys[0] regex = "".join(["^", key, "$"]) try: key_rex = re.compile(regex) except Exception: self.warning("Cannot compile regex: %s" % regex) return [] results = [] for new_key, new_content in self.items(content): if key_rex.match(new_key): results.extend(self.deep_get(new_content, keys[1:], traversed_path + [str(new_key)])) return results def items(self, object): if isinstance(object, list): for new_key, new_content in enumerate(object): yield str(new_key), new_content elif isinstance(object, dict): for new_key, new_content in object.iteritems(): yield str(new_key), new_content else: self.log.warning("Could not parse this object, check the json" "served by the expvar")
varlib1/servermall
go_expvar/check.py
Python
bsd-3-clause
8,833
class CreateFireStations < ActiveRecord::Migration def change create_table :fire_stations do |t| t.string :address t.point :latlon, :geographic => true t.integer :zip t.timestamps end end end
cityofaustin/preparedly
db/migrate/20120426235805_create_fire_stations.rb
Ruby
bsd-3-clause
229
class Spree::PagesController < Spree::BaseController def show @page = current_page raise ActionController::RoutingError.new("No route matches [GET] #{request.path}") if @page.nil? if @page.root? @posts = Spree::Post.live.limit(5) if SpreeEssentials.has?(:blog) @articles = Spree::Article.live.limit(5) if SpreeEssentials.has?(:news) render :template => 'spree/pages/home' end end private def accurate_title @page.meta_title end end
hakhanhphuc/spree_essential_cms
app/controllers/spree/pages_controller.rb
Ruby
bsd-3-clause
497
var analytics = require('analytics') var d3 = require('d3') var hogan = require('hogan.js') var log = require('./client/log')('help-me-choose') var modal = require('./client/modal') var RouteModal = require('route-modal') var routeResource = require('route-resource') var routeSummarySegments = require('route-summary-segments') var session = require('session') var toCapitalCase = require('to-capital-case') var optionTemplate = hogan.compile(require('./option.html')) var routeTemplate = hogan.compile(require('./route.html')) var primaryFilter = 'totalCost' var secondaryFilter = 'productiveTime' var filters = { travelTime: function (a) { return a.time }, totalCost: function (a) { return a.cost }, walkDistance: function (a) { return a.walkDistance }, calories: function (a) { return -a.calories }, productiveTime: function (a) { return -a.productiveTime }, none: function (a) { return 0 } } /** * Expose `Modal` */ var Modal = module.exports = modal({ closable: true, width: '768px', template: require('./template.html') }, function (view, routes) { view.primaryFilter = view.find('#primary-filter') view.secondaryFilter = view.find('#secondary-filter') view.primaryFilter.querySelector('[value="none"]').remove() view.primaryFilter.value = primaryFilter view.secondaryFilter.value = secondaryFilter view.oneWay = true view.daily = true view.refresh() }) /** * Refresh */ Modal.prototype.refresh = function (e) { if (e) e.preventDefault() log('refreshing') primaryFilter = this.primaryFilter.value secondaryFilter = this.secondaryFilter.value var i var thead = this.find('thead') var tbody = this.find('tbody') // Remove rows tbody.innerHTML = '' // Remove all colors var headers = thead.querySelectorAll('th') for (i = 0; i < headers.length; i++) { headers[i].classList.remove('primaryFilter') headers[i].classList.remove('secondaryFilter') } var phead = thead.querySelector('.' + primaryFilter) if (phead) phead.classList.add('primaryFilter') var shead = thead.querySelector('.' + secondaryFilter) if (shead) shead.classList.add('secondaryFilter') // Get the indexes var primaryFn = filters[primaryFilter] var secondaryFn = filters[secondaryFilter] // Get the multiplier var multiplier = this.oneWay ? 1 : 2 multiplier *= this.daily ? 1 : 365 // Get the route data var routes = this.model.map(function (r, index) { return getRouteData(r, multiplier, index) }) // Sort by secondary first routes = rankRoutes(routes, primaryFn, secondaryFn) // Render for (i = 0; i < routes.length; i++) { var route = routes[i] tbody.innerHTML += this.renderRoute(route) var row = tbody.childNodes[i] var pcell = row.querySelector('.' + primaryFilter) var scell = row.querySelector('.' + secondaryFilter) if (pcell) pcell.style.backgroundColor = toRGBA(route.primaryColor, 0.25) if (scell) scell.style.backgroundColor = toRGBA(route.secondaryColor, 0.25) } // Track the results analytics.track('Viewed "Help Me Choose"', { plan: session.plan().generateQuery(), primaryFilter: primaryFilter, secondaryFilter: secondaryFilter, multiplier: multiplier }) } /** * Append option */ Modal.prototype.renderRoute = function (data) { data.calories = data.calories ? parseInt(data.calories, 10).toLocaleString() + ' cals' : 'None' data.cost = data.cost ? '$' + data.cost.toFixed(2) : 'Free' data.emissions = data.emissions ? parseInt(data.emissions, 10) : 'None' data.walkDistance = data.walkDistance ? data.walkDistance + ' mi' : 'None' if (data.productiveTime) { if (data.productiveTime > 120) { data.productiveTime = parseInt(data.productiveTime / 60, 10).toLocaleString() + ' hrs' } else { data.productiveTime = parseInt(data.productiveTime, 10).toLocaleString() + ' min' } } else { data.productiveTime = 'None' } return routeTemplate.render(data) } /** * Filters */ Modal.prototype.filters = function () { var options = '' for (var f in filters) { options += optionTemplate.render({ name: toCapitalCase(f).toLowerCase(), value: f }) } return options } /** * Select this option */ Modal.prototype.selectRoute = function (e) { e.preventDefault() if (e.target.tagName !== 'BUTTON') return var index = e.target.getAttribute('data-index') var route = this.model[index] var plan = session.plan() var tags = route.tags(plan) var self = this routeResource.findByTags(tags, function (err, resources) { if (err) log.error(err) var routeModal = new RouteModal(route, null, { context: 'help-me-choose', resources: resources }) self.hide() routeModal.show() routeModal.on('next', function () { routeModal.hide() }) }) } /** * Multipliers */ Modal.prototype.setOneWay = function (e) { this.oneWay = true this.setMultiplier(e) } Modal.prototype.setRoundTrip = function (e) { this.oneWay = false this.setMultiplier(e) } Modal.prototype.setDaily = function (e) { this.daily = true this.setMultiplier(e) } Modal.prototype.setYearly = function (e) { this.daily = false this.setMultiplier(e) } Modal.prototype.setMultiplier = function (e) { e.preventDefault() var button = e.target var parent = button.parentNode var buttons = parent.getElementsByTagName('button') for (var i = 0; i < buttons.length; i++) { buttons[i].classList.remove('active') } button.classList.add('active') this.refresh() } /** * Rank & sort the routes */ function rankRoutes (routes, primary, secondary) { var primaryDomain = [d3.min(routes, primary), d3.max(routes, primary)] var secondaryDomain = [d3.min(routes, secondary), d3.max(routes, secondary)] var primaryScale = d3.scale.linear() .domain(primaryDomain) .range([0, routes.length * 2]) var secondaryScale = d3.scale.linear() .domain(secondaryDomain) .range([1, routes.length]) var primaryColor = d3.scale.linear() .domain(primaryDomain) .range(['#f5a81c', '#fff']) var secondaryColor = d3.scale.linear() .domain(secondaryDomain) .range(['#8ec449', '#fff']) routes = routes.map(function (r) { r.primaryRank = primaryScale(primary(r)) r.primaryColor = primaryColor(primary(r)) r.secondaryRank = secondaryScale(secondary(r)) r.secondaryColor = secondaryColor(secondary(r)) r.rank = r.primaryRank + r.secondaryRank return r }) routes.sort(function (a, b) { return a.rank - b.rank }) // lowest number first return routes } /** * RGB to transparent */ function toRGBA (rgb, opacity) { var c = d3.rgb(rgb) return 'rgba(' + c.r + ',' + c.g + ',' + c.b + ',' + opacity + ')' } /** * Get route data */ function getRouteData (route, multiplier, index) { var data = { segments: routeSummarySegments(route, { inline: true }), index: index, time: route.average(), frequency: 0, cost: route.cost(), walkDistance: route.walkDistances(), calories: route.totalCalories(), productiveTime: route.timeInTransit(), emissions: route.emissions(), score: route.score(), rank: 0 } if (multiplier > 1) { ['cost', 'calories', 'productiveTime', 'emissions'].forEach(function (type) { data[type] = data[type] * multiplier }) } return data }
miraculixx/modeify
client/help-me-choose-view/index.js
JavaScript
bsd-3-clause
7,412
goog.provide('goog.testing.PseudoRandom'); goog.require('goog.Disposable'); goog.testing.PseudoRandom = function(opt_seed, opt_install) { goog.Disposable.call(this); this.seed_ = opt_seed || goog.testing.PseudoRandom.seedUniquifier_ ++ + goog.now(); if(opt_install) { this.install(); } }; goog.inherits(goog.testing.PseudoRandom, goog.Disposable); goog.testing.PseudoRandom.seedUniquifier_ = 0; goog.testing.PseudoRandom.A = 48271; goog.testing.PseudoRandom.M = 2147483647; goog.testing.PseudoRandom.Q = 44488; goog.testing.PseudoRandom.R = 3399; goog.testing.PseudoRandom.ONE_OVER_M = 1.0 / goog.testing.PseudoRandom.M; goog.testing.PseudoRandom.prototype.installed_; goog.testing.PseudoRandom.prototype.mathRandom_; goog.testing.PseudoRandom.prototype.install = function() { if(! this.installed_) { this.mathRandom_ = Math.random; Math.random = goog.bind(this.random, this); this.installed_ = true; } }; goog.testing.PseudoRandom.prototype.disposeInternal = function() { goog.testing.PseudoRandom.superClass_.disposeInternal.call(this); this.uninstall(); }; goog.testing.PseudoRandom.prototype.uninstall = function() { if(this.installed_) { Math.random = this.mathRandom_; this.installed_ = false; } }; goog.testing.PseudoRandom.prototype.random = function() { var hi = this.seed_ / goog.testing.PseudoRandom.Q; var lo = this.seed_ % goog.testing.PseudoRandom.Q; var test = goog.testing.PseudoRandom.A * lo - goog.testing.PseudoRandom.R * hi; if(test > 0) { this.seed_ = test; } else { this.seed_ = test + goog.testing.PseudoRandom.M; } return this.seed_ * goog.testing.PseudoRandom.ONE_OVER_M; };
johnjbarton/qpp
traceur/test/closurebaseline/third_party/closure-library/closure/goog/testing/pseudorandom.js
JavaScript
bsd-3-clause
1,713
# Copyright (c) 2017,2018 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """ =============================== Sigma to Pressure Interpolation =============================== By using `metpy.calc.log_interp`, data with sigma as the vertical coordinate can be interpolated to isobaric coordinates. """ import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt from netCDF4 import Dataset, num2date from metpy.cbook import get_test_data from metpy.interpolate import log_interpolate_1d from metpy.plots import add_metpy_logo, add_timestamp from metpy.units import units ###################################### # **Data** # # The data for this example comes from the outer domain of a WRF-ARW model forecast # initialized at 1200 UTC on 03 June 1980. Model data courtesy Matthew Wilson, Valparaiso # University Department of Geography and Meteorology. data = Dataset(get_test_data('wrf_example.nc', False)) lat = data.variables['lat'][:] lon = data.variables['lon'][:] time = data.variables['time'] vtimes = num2date(time[:], time.units) temperature = units.Quantity(data.variables['temperature'][:], 'degC') pressure = units.Quantity(data.variables['pressure'][:], 'Pa') hgt = units.Quantity(data.variables['height'][:], 'meter') #################################### # Array of desired pressure levels plevs = [700.] * units.hPa ##################################### # **Interpolate The Data** # # Now that the data is ready, we can interpolate to the new isobaric levels. The data is # interpolated from the irregular pressure values for each sigma level to the new input # mandatory isobaric levels. `mpcalc.log_interp` will interpolate over a specified dimension # with the `axis` argument. In this case, `axis=1` will correspond to interpolation on the # vertical axis. The interpolated data is output in a list, so we will pull out each # variable for plotting. height, temp = log_interpolate_1d(plevs, pressure, hgt, temperature, axis=1) #################################### # **Plotting the Data for 700 hPa.** # Set up our projection crs = ccrs.LambertConformal(central_longitude=-100.0, central_latitude=45.0) # Set the forecast hour FH = 1 # Create the figure and grid for subplots fig = plt.figure(figsize=(17, 12)) add_metpy_logo(fig, 470, 320, size='large') # Plot 700 hPa ax = plt.subplot(111, projection=crs) ax.add_feature(cfeature.COASTLINE.with_scale('50m'), linewidth=0.75) ax.add_feature(cfeature.STATES, linewidth=0.5) # Plot the heights cs = ax.contour(lon, lat, height[FH, 0, :, :], transform=ccrs.PlateCarree(), colors='k', linewidths=1.0, linestyles='solid') cs.clabel(fontsize=10, inline=1, inline_spacing=7, fmt='%i', rightside_up=True, use_clabeltext=True) # Contour the temperature cf = ax.contourf(lon, lat, temp[FH, 0, :, :], range(-20, 20, 1), cmap=plt.cm.RdBu_r, transform=ccrs.PlateCarree()) cb = fig.colorbar(cf, orientation='horizontal', aspect=65, shrink=0.5, pad=0.05, extendrect='True') cb.set_label('Celsius', size='x-large') ax.set_extent([-106.5, -90.4, 34.5, 46.75], crs=ccrs.PlateCarree()) # Make the axis title ax.set_title(f'{plevs[0]:~.0f} Heights (m) and Temperature (C)', loc='center', fontsize=10) # Set the figure title fig.suptitle(f'WRF-ARW Forecast VALID: {vtimes[FH]} UTC', fontsize=14) add_timestamp(ax, vtimes[FH], y=0.02, high_contrast=True) plt.show()
metpy/MetPy
v1.1/_downloads/0f93e682cc461be360e2fd037bf1fb7e/sigma_to_pressure_interpolation.py
Python
bsd-3-clause
3,493
<?php // autoload_real.php @generated by Composer class ComposerAutoloaderInit074aee1d4233eb5f2c56ebdb549dbef4 { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInit074aee1d4233eb5f2c56ebdb549dbef4', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(); spl_autoload_unregister(array('ComposerAutoloaderInit074aee1d4233eb5f2c56ebdb549dbef4', 'loadClassLoader')); $map = require __DIR__ . '/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $loader->set($namespace, $path); } $map = require __DIR__ . '/autoload_psr4.php'; foreach ($map as $namespace => $path) { $loader->setPsr4($namespace, $path); } $classMap = require __DIR__ . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } $loader->register(true); $includeFiles = require __DIR__ . '/autoload_files.php'; foreach ($includeFiles as $file) { composerRequire074aee1d4233eb5f2c56ebdb549dbef4($file); } return $loader; } } function composerRequire074aee1d4233eb5f2c56ebdb549dbef4($file) { require $file; }
kidbai/d4t
vendor/composer/autoload_real.php
PHP
bsd-3-clause
1,585
# # cocos2d # http://cocos2d.org # from __future__ import division, print_function, unicode_literals import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) from cocos.director import director from cocos.layer import Layer, ColorLayer from cocos.scene import Scene from cocos.scenes.transitions import * from cocos.actions import * from cocos.sprite import Sprite import pyglet from pyglet import gl, font from pyglet.window import key class ControlLayer(Layer): is_event_handler = True #: enable pyglet's events def __init__( self ): super(ControlLayer, self).__init__() self.text_title = pyglet.text.Label("Transition Demos", font_size=32, x=5, y=director.get_window_size()[1], anchor_x=font.Text.LEFT, anchor_y=font.Text.TOP ) self.text_subtitle = pyglet.text.Label( transition_list[current_transition].__name__, font_size=18, multiline=True, width=600, x=5, y=director.get_window_size()[1] - 80, anchor_x=font.Text.LEFT, anchor_y=font.Text.TOP ) self.text_help = pyglet.text.Label("Press LEFT / RIGHT for prev/next test, ENTER to restart test", font_size=16, x=director.get_window_size()[0] // 2, y=20, anchor_x=font.Text.CENTER, anchor_y=font.Text.CENTER) def draw( self ): self.text_title.draw() self.text_subtitle.draw() self.text_help.draw() def on_key_press( self, k , m ): global current_transition, control_p if k == key.LEFT: current_transition = (current_transition-1)%len(transition_list) elif k == key.RIGHT: current_transition = (current_transition+1)%len(transition_list) elif k == key.ENTER: director.replace( transition_list[current_transition]( (control_list[(control_p+1)%len(control_list)] ), 1.25) ) control_p = (control_p + 1) % len(control_list) return True if k in (key.LEFT, key.RIGHT ): self.text_subtitle.text = transition_list[current_transition].__name__ class GrossiniLayer(Layer): def __init__( self ): super( GrossiniLayer, self ).__init__() g = Sprite( 'grossini.png') g.position = (320,240) rot = RotateBy( 360, 4 ) g.do( Repeat( rot + Reverse(rot) ) ) self.add( g ) class GrossiniLayer2(Layer): def __init__( self ): super( GrossiniLayer2, self ).__init__() rot = Rotate( 360, 5 ) g1 = Sprite( 'grossinis_sister1.png' ) g1.position = (490,240) g2 = Sprite( 'grossinis_sister2.png' ) g2.position = (140,240) g1.do( Repeat( rot + Reverse(rot) ) ) g2.do( Repeat( rot + Reverse(rot) ) ) self.add( g1 ) self.add( g2 ) if __name__ == "__main__": director.init(resizable=True) # director.window.set_fullscreen(True) transition_list = [ # ActionTransitions RotoZoomTransition, JumpZoomTransition, SplitColsTransition, SplitRowsTransition, MoveInLTransition, MoveInRTransition, MoveInBTransition, MoveInTTransition, SlideInLTransition, SlideInRTransition, SlideInBTransition, SlideInTTransition, FlipX3DTransition, FlipY3DTransition, FlipAngular3DTransition, ShuffleTransition, ShrinkGrowTransition, CornerMoveTransition, EnvelopeTransition, FadeTRTransition, FadeBLTransition, FadeUpTransition, FadeDownTransition, TurnOffTilesTransition, FadeTransition, ZoomTransition, ] current_transition = 0 g = GrossiniLayer() g2 = GrossiniLayer2() c2 = ColorLayer(128,16,16,255) c1 = ColorLayer(0,255,255,255) control1 = ControlLayer() control2 = ControlLayer() controlScene1 = Scene( c2, g, control2 ) controlScene2 = Scene( c1, g2, control2 ) control_p = 0 control_list = [controlScene1, controlScene2] director.run( controlScene1 )
Alwnikrotikz/los-cocos
samples/demo_transitions.py
Python
bsd-3-clause
4,303
class PlasmaException(Exception): pass class IncompleteAtomicData(PlasmaException): def __init__(self, atomic_data_name): message = ('The current plasma calculation requires {0}, ' 'which is not provided by the given atomic data'.format( atomic_data_name)) super(PlasmaException, self).__init__(message) class PlasmaMissingModule(PlasmaException): pass class PlasmaIsolatedModule(PlasmaException): pass class NotInitializedModule(PlasmaException): pass class PlasmaIonizationError(PlasmaException): pass class PlasmaConfigContradiction(PlasmaException): pass
rajul/tardis
tardis/plasma/exceptions.py
Python
bsd-3-clause
640
#pragma once #include <memory> #include <arbor/context.hpp> #include "distributed_context.hpp" #include "threading/threading.hpp" #include "gpu_context.hpp" namespace arb { // execution_context is a simple container for the state relating to // execution resources. // Specifically, it has handles for the distributed context, gpu // context and thread pool. // // Note: the public API uses an opaque handle arb::context for // execution_context, to hide implementation details of the // container and its constituent contexts from the public API. struct execution_context { distributed_context_handle distributed; task_system_handle thread_pool; gpu_context_handle gpu; execution_context(const proc_allocation& resources = proc_allocation{}); // Use a template for constructing with a specific distributed context. // Specialised implementations are implemented in execution_context.cpp. template <typename Comm> execution_context(const proc_allocation& resources, Comm comm); }; } // namespace arb
halfflat/nestmc-proto
arbor/execution_context.hpp
C++
bsd-3-clause
1,041
<?php /** * This file is part of phpUnderControl. * * PHP Version 5.2.0 * * Copyright (c) 2007-2011, Manuel Pichler <mapi@phpundercontrol.org>. * 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 Manuel Pichler nor the names of his * 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 OWNER 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. * * @category QualityAssurance * @package Graph * @author Manuel Pichler <mapi@phpundercontrol.org> * @copyright 2007-2011 Manuel Pichler. All rights reserved. * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @version SVN: $Id$ * @link http://www.phpundercontrol.org/ */ /** * Object factory for the different chart types. * * @category QualityAssurance * @package Graph * @author Manuel Pichler <mapi@phpundercontrol.org> * @copyright 2007-2011 Manuel Pichler. All rights reserved. * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @version Release: @package_version@ * @link http://www.phpundercontrol.org/ */ class phpucChartFactory { /** * The number entries to display in a chart. * * @var integer */ private $numberOfEntries = 0; /** * Constructs a new chart factory instance. * * @param integer $numberOfEntries Optional argument which defines the * maximum number of entries that should be shown by a chart. */ public function __construct( $numberOfEntries = 0 ) { $this->numberOfEntries = $numberOfEntries; } /** * Creates a chart instance depending on the given <b>$input</b> settings. * * @param phpucAbstractInput $input The input data source. * * @return ezcGraphChart */ public function createChart( phpucAbstractInput $input ) { switch ( $input->type ) { case phpucChartI::TYPE_DOT: $chart = new phpucDotChart(); break; case phpucChartI::TYPE_LINE: $chart = new phpucLineChart(); break; case phpucChartI::TYPE_PIE: $chart = new phpucPieChart(); break; case phpucChartI::TYPE_TIME: $chart = new phpucTimeChart(); break; } $chart->setNumberOfEntries( $this->numberOfEntries ); $chart->setInput( $input ); return $chart; } }
phpundercontrol/phpUnderControl-UNMAINTAINED
src/Graph/ChartFactory.php
PHP
bsd-3-clause
3,807
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit script for mojo See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into depot_tools. """ import os.path import re # NOTE: The EDK allows all external paths, so doesn't need a whitelist. _PACKAGE_WHITELISTED_EXTERNAL_PATHS = { "SDK": ["//build/module_args/mojo.gni", "//build/module_args/dart.gni", "//testing/gtest", "//third_party/cython", "//third_party/khronos"], "services": ["//build/module_args/mojo.gni", "//testing/gtest"], } # These files are not part of the exported package. _PACKAGE_IGNORED_BUILD_FILES = { "SDK": {}, "EDK": {}, "services": {"mojo/services/BUILD.gn"}, } _PACKAGE_PATH_PREFIXES = {"SDK": "mojo/public/", "EDK": "mojo/edk/", "services": "mojo/services"} # TODO(etiennej): python_binary_source_set added due to crbug.com/443147 _PACKAGE_SOURCE_SET_TYPES = {"SDK": ["mojo_sdk_source_set", "python_binary_source_set"], "EDK": ["mojo_edk_source_set"], "services": ["mojo_sdk_source_set"]} _ILLEGAL_EXTERNAL_PATH_WARNING_MESSAGE = \ "Found disallowed external paths within SDK buildfiles." _ILLEGAL_SERVICES_ABSOLUTE_PATH_WARNING_MESSAGE = \ "Found references to services' public buildfiles via absolute paths " \ "within services' public buildfiles." _ILLEGAL_EDK_ABSOLUTE_PATH_WARNING_MESSAGE = \ "Found references to the EDK via absolute paths within EDK buildfiles." _ILLEGAL_SDK_ABSOLUTE_PATH_WARNING_MESSAGE_TEMPLATE = \ "Found references to the SDK via absolute paths within %s buildfiles." _ILLEGAL_SDK_ABSOLUTE_PATH_WARNING_MESSAGES = { "SDK": _ILLEGAL_SDK_ABSOLUTE_PATH_WARNING_MESSAGE_TEMPLATE % "SDK", "EDK": _ILLEGAL_SDK_ABSOLUTE_PATH_WARNING_MESSAGE_TEMPLATE % "EDK", "services": _ILLEGAL_SDK_ABSOLUTE_PATH_WARNING_MESSAGE_TEMPLATE % "services' public", } _INCORRECT_SOURCE_SET_TYPE_WARNING_MESSAGE_TEMPLATE = \ "All source sets in %s must be constructed via %s." _INCORRECT_SOURCE_SET_TYPE_WARNING_MESSAGES = { "SDK": _INCORRECT_SOURCE_SET_TYPE_WARNING_MESSAGE_TEMPLATE % ("the SDK", _PACKAGE_SOURCE_SET_TYPES["SDK"]), "EDK": _INCORRECT_SOURCE_SET_TYPE_WARNING_MESSAGE_TEMPLATE % ("the EDK", _PACKAGE_SOURCE_SET_TYPES["EDK"]), "services": _INCORRECT_SOURCE_SET_TYPE_WARNING_MESSAGE_TEMPLATE % ("services' client libs", _PACKAGE_SOURCE_SET_TYPES["services"]), } def _IsBuildFileWithinPackage(f, package): """Returns whether |f| specifies a GN build file within |package|.""" assert package in _PACKAGE_PATH_PREFIXES package_path_prefix = _PACKAGE_PATH_PREFIXES[package] if not f.LocalPath().startswith(package_path_prefix): return False if (not f.LocalPath().endswith("/BUILD.gn") and not f.LocalPath().endswith(".gni")): return False if f.LocalPath() in _PACKAGE_IGNORED_BUILD_FILES[package]: return False return True def _AffectedBuildFilesWithinPackage(input_api, package): """Returns all the affected build files within |package|.""" return [f for f in input_api.AffectedFiles() if _IsBuildFileWithinPackage(f, package)] def _FindIllegalAbsolutePathsInBuildFiles(input_api, package): """Finds illegal absolute paths within the build files in |input_api.AffectedFiles()| that are within |package|. An illegal absolute path within the SDK or a service's SDK is one that is to the SDK itself or a non-whitelisted external path. An illegal absolute path within the EDK is one that is to the SDK or the EDK. Returns any such references in a list of (file_path, line_number, referenced_path) tuples.""" illegal_references = [] for f in _AffectedBuildFilesWithinPackage(input_api, package): for line_num, line in f.ChangedContents(): # Determine if this is a reference to an absolute path. m = re.search(r'"(//[^"]*)"', line) if not m: continue referenced_path = m.group(1) if not referenced_path.startswith("//mojo"): # In the EDK, all external absolute paths are allowed. if package == "EDK": continue # Determine if this is a whitelisted external path. if referenced_path in _PACKAGE_WHITELISTED_EXTERNAL_PATHS[package]: continue illegal_references.append((f.LocalPath(), line_num, referenced_path)) return illegal_references def _PathReferenceInBuildFileWarningItem(build_file, line_num, referenced_path): """Returns a string expressing a warning item that |referenced_path| is referenced at |line_num| in |build_file|.""" return "%s, line %d (%s)" % (build_file, line_num, referenced_path) def _IncorrectSourceSetTypeWarningItem(build_file, line_num): """Returns a string expressing that the error occurs at |line_num| in |build_file|.""" return "%s, line %d" % (build_file, line_num) def _CheckNoIllegalAbsolutePathsInBuildFiles(input_api, output_api, package): """Makes sure that the BUILD.gn files within |package| do not reference the SDK/EDK via absolute paths, and do not reference disallowed external dependencies.""" sdk_references = [] edk_references = [] external_deps_references = [] services_references = [] # Categorize any illegal references. illegal_references = _FindIllegalAbsolutePathsInBuildFiles(input_api, package) for build_file, line_num, referenced_path in illegal_references: reference_string = _PathReferenceInBuildFileWarningItem(build_file, line_num, referenced_path) if referenced_path.startswith("//mojo/public"): sdk_references.append(reference_string) elif package == "SDK": external_deps_references.append(reference_string) elif package == "services": if referenced_path.startswith("//mojo/services"): services_references.append(reference_string) else: external_deps_references.append(reference_string) elif referenced_path.startswith("//mojo/edk"): edk_references.append(reference_string) # Package up categorized illegal references into results. results = [] if sdk_references: results.extend([output_api.PresubmitError( _ILLEGAL_SDK_ABSOLUTE_PATH_WARNING_MESSAGES[package], items=sdk_references)]) if external_deps_references: assert package == "SDK" or package == "services" results.extend([output_api.PresubmitError( _ILLEGAL_EXTERNAL_PATH_WARNING_MESSAGE, items=external_deps_references)]) if services_references: assert package == "services" results.extend([output_api.PresubmitError( _ILLEGAL_SERVICES_ABSOLUTE_PATH_WARNING_MESSAGE, items=services_references)]) if edk_references: assert package == "EDK" results.extend([output_api.PresubmitError( _ILLEGAL_EDK_ABSOLUTE_PATH_WARNING_MESSAGE, items=edk_references)]) return results def _CheckSourceSetsAreOfCorrectType(input_api, output_api, package): """Makes sure that the BUILD.gn files always use the correct wrapper type for |package|, which can be one of ["SDK", "EDK"], to construct source_set targets.""" assert package in _PACKAGE_SOURCE_SET_TYPES required_source_set_type = _PACKAGE_SOURCE_SET_TYPES[package] problems = [] for f in _AffectedBuildFilesWithinPackage(input_api, package): for line_num, line in f.ChangedContents(): m = re.search(r"[a-z_]*source_set\(", line) if not m: continue source_set_type = m.group(0)[:-1] if source_set_type in required_source_set_type: continue problems.append(_IncorrectSourceSetTypeWarningItem(f.LocalPath(), line_num)) if not problems: return [] return [output_api.PresubmitError( _INCORRECT_SOURCE_SET_TYPE_WARNING_MESSAGES[package], items=problems)] def _CheckChangePylintsClean(input_api, output_api): # Additional python module paths (we're in src/mojo/); not everyone needs # them, but it's easiest to add them to everyone's path. # For ply and jinja2: third_party_path = os.path.join( input_api.PresubmitLocalPath(), "..", "third_party") # For the bindings generator: mojo_public_bindings_pylib_path = os.path.join( input_api.PresubmitLocalPath(), "public", "tools", "bindings", "pylib") # For the python bindings: mojo_python_bindings_path = os.path.join( input_api.PresubmitLocalPath(), "public", "python") # For the python bindings tests: mojo_python_bindings_tests_path = os.path.join( input_api.PresubmitLocalPath(), "python", "tests") # For the roll tools scripts: mojo_roll_tools_path = os.path.join( input_api.PresubmitLocalPath(), "tools", "roll") # For all mojo/tools scripts: mopy_path = os.path.join(input_api.PresubmitLocalPath(), "tools") # For all mojo/devtools scripts: devtools_path = os.path.join(input_api.PresubmitLocalPath(), "devtools") # TODO(vtl): Don't lint these files until the (many) problems are fixed # (possibly by deleting/rewriting some files). temporary_black_list = ( r".*\bpublic[\\\/]tools[\\\/]bindings[\\\/]pylib[\\\/]mojom[\\\/]" r"generate[\\\/].+\.py$", r".*\bpublic[\\\/]tools[\\\/]bindings[\\\/]generators[\\\/].+\.py$") black_list = input_api.DEFAULT_BLACK_LIST + temporary_black_list + ( # Imported from Android tools, we might want not to fix the warnings # raised for it to make it easier to compare the code with the original. r".*\bdevtools[\\\/]common[\\\/]android_stack_parser[\\\/].+\.py$",) results = [] pylint_extra_paths = [ third_party_path, mojo_public_bindings_pylib_path, mojo_python_bindings_path, mojo_python_bindings_tests_path, mojo_roll_tools_path, mopy_path, devtools_path ] results.extend(input_api.canned_checks.RunPylint( input_api, output_api, extra_paths_list=pylint_extra_paths, black_list=black_list)) return results def _BuildFileChecks(input_api, output_api): """Performs checks on SDK, EDK, and services' public buildfiles.""" results = [] for package in ["SDK", "EDK", "services"]: results.extend(_CheckNoIllegalAbsolutePathsInBuildFiles(input_api, output_api, package)) results.extend(_CheckSourceSetsAreOfCorrectType(input_api, output_api, package)) return results def _CommonChecks(input_api, output_api): """Checks common to both upload and commit.""" results = [] results.extend(_BuildFileChecks(input_api, output_api)) return results def CheckChangeOnUpload(input_api, output_api): results = [] results.extend(_CommonChecks(input_api, output_api)) results.extend(_CheckChangePylintsClean(input_api, output_api)) return results def CheckChangeOnCommit(input_api, output_api): results = [] results.extend(_CommonChecks(input_api, output_api)) return results
zhangxq5012/sky_engine
mojo/PRESUBMIT.py
Python
bsd-3-clause
11,467
/* * Copyright (c) 2015, University of Oslo * * 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 HISP project 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 OWNER 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 org.hisp.dhis.android.sdk.utils; /** * @author Araz Abishov <araz.abishov.gsoc@gmail.com>. */ public final class StringUtils { private StringBuilder mBuilder; private StringUtils() { mBuilder = new StringBuilder(); } public static StringUtils create() { return new StringUtils(); } public <T> StringUtils append(T item) { mBuilder.append(item); return this; } public String build() { return mBuilder.toString(); } }
arthurgwatidzo/dhis2-android-sdk
app/src/main/java/org/hisp/dhis/android/sdk/utils/StringUtils.java
Java
bsd-3-clause
2,060
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react.uimanager; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import java.util.ArrayList; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import com.facebook.react.animation.Animation; import com.facebook.react.animation.AnimationRegistry; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.SoftAssertions; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.uimanager.debug.NotThreadSafeViewHierarchyUpdateDebugListener; import com.facebook.systrace.Systrace; import com.facebook.systrace.SystraceMessage; /** * This class acts as a buffer for command executed on {@link NativeViewHierarchyManager} or on * {@link AnimationRegistry}. It expose similar methods as mentioned classes but instead of * executing commands immediately it enqueues those operations in a queue that is then flushed from * {@link UIManagerModule} once JS batch of ui operations is finished. This is to make sure that we * execute all the JS operation coming from a single batch a single loop of the main (UI) android * looper. * * TODO(7135923): Pooling of operation objects * TODO(5694019): Consider a better data structure for operations queue to save on allocations */ public class UIViewOperationQueue { private final int[] mMeasureBuffer = new int[4]; /** * A mutation or animation operation on the view hierarchy. */ protected interface UIOperation { void execute(); } /** * A spec for an operation on the native View hierarchy. */ private abstract class ViewOperation implements UIOperation { public int mTag; public ViewOperation(int tag) { mTag = tag; } } private final class RemoveRootViewOperation extends ViewOperation { public RemoveRootViewOperation(int tag) { super(tag); } @Override public void execute() { mNativeViewHierarchyManager.removeRootView(mTag); } } private final class UpdatePropertiesOperation extends ViewOperation { private final CatalystStylesDiffMap mProps; private UpdatePropertiesOperation(int tag, CatalystStylesDiffMap props) { super(tag); mProps = props; } @Override public void execute() { mNativeViewHierarchyManager.updateProperties(mTag, mProps); } } /** * Operation for updating native view's position and size. The operation is not created directly * by a {@link UIManagerModule} call from JS. Instead it gets inflated using computed position * and size values by CSSNode hierarchy. */ private final class UpdateLayoutOperation extends ViewOperation { private final int mParentTag, mX, mY, mWidth, mHeight; public UpdateLayoutOperation( int parentTag, int tag, int x, int y, int width, int height) { super(tag); mParentTag = parentTag; mX = x; mY = y; mWidth = width; mHeight = height; } @Override public void execute() { mNativeViewHierarchyManager.updateLayout(mParentTag, mTag, mX, mY, mWidth, mHeight); } } private final class CreateViewOperation extends ViewOperation { private final ThemedReactContext mThemedContext; private final String mClassName; private final @Nullable CatalystStylesDiffMap mInitialProps; public CreateViewOperation( ThemedReactContext themedContext, int tag, String className, @Nullable CatalystStylesDiffMap initialProps) { super(tag); mThemedContext = themedContext; mClassName = className; mInitialProps = initialProps; } @Override public void execute() { mNativeViewHierarchyManager.createView( mThemedContext, mTag, mClassName, mInitialProps); } } private final class ManageChildrenOperation extends ViewOperation { private final @Nullable int[] mIndicesToRemove; private final @Nullable ViewAtIndex[] mViewsToAdd; private final @Nullable int[] mTagsToDelete; public ManageChildrenOperation( int tag, @Nullable int[] indicesToRemove, @Nullable ViewAtIndex[] viewsToAdd, @Nullable int[] tagsToDelete) { super(tag); mIndicesToRemove = indicesToRemove; mViewsToAdd = viewsToAdd; mTagsToDelete = tagsToDelete; } @Override public void execute() { mNativeViewHierarchyManager.manageChildren( mTag, mIndicesToRemove, mViewsToAdd, mTagsToDelete); } } private final class UpdateViewExtraData extends ViewOperation { private final Object mExtraData; public UpdateViewExtraData(int tag, Object extraData) { super(tag); mExtraData = extraData; } @Override public void execute() { mNativeViewHierarchyManager.updateViewExtraData(mTag, mExtraData); } } private final class ChangeJSResponderOperation extends ViewOperation { private final int mInitialTag; private final boolean mBlockNativeResponder; private final boolean mClearResponder; public ChangeJSResponderOperation( int tag, int initialTag, boolean clearResponder, boolean blockNativeResponder) { super(tag); mInitialTag = initialTag; mClearResponder = clearResponder; mBlockNativeResponder = blockNativeResponder; } @Override public void execute() { if (!mClearResponder) { mNativeViewHierarchyManager.setJSResponder(mTag, mInitialTag, mBlockNativeResponder); } else { mNativeViewHierarchyManager.clearJSResponder(); } } } private final class DispatchCommandOperation extends ViewOperation { private final int mCommand; private final @Nullable ReadableArray mArgs; public DispatchCommandOperation(int tag, int command, @Nullable ReadableArray args) { super(tag); mCommand = command; mArgs = args; } @Override public void execute() { mNativeViewHierarchyManager.dispatchCommand(mTag, mCommand, mArgs); } } private final class ShowPopupMenuOperation extends ViewOperation { private final ReadableArray mItems; private final Callback mSuccess; public ShowPopupMenuOperation( int tag, ReadableArray items, Callback success) { super(tag); mItems = items; mSuccess = success; } @Override public void execute() { mNativeViewHierarchyManager.showPopupMenu(mTag, mItems, mSuccess); } } /** * A spec for animation operations (add/remove) */ private static abstract class AnimationOperation implements UIViewOperationQueue.UIOperation { protected final int mAnimationID; public AnimationOperation(int animationID) { mAnimationID = animationID; } } private class RegisterAnimationOperation extends AnimationOperation { private final Animation mAnimation; private RegisterAnimationOperation(Animation animation) { super(animation.getAnimationID()); mAnimation = animation; } @Override public void execute() { mAnimationRegistry.registerAnimation(mAnimation); } } private class AddAnimationOperation extends AnimationOperation { private final int mReactTag; private final Callback mSuccessCallback; private AddAnimationOperation(int reactTag, int animationID, Callback successCallback) { super(animationID); mReactTag = reactTag; mSuccessCallback = successCallback; } @Override public void execute() { Animation animation = mAnimationRegistry.getAnimation(mAnimationID); if (animation != null) { mNativeViewHierarchyManager.startAnimationForNativeView( mReactTag, animation, mSuccessCallback); } else { // node or animation not found // TODO(5712813): cleanup callback in JS callbacks table in case of an error throw new IllegalViewOperationException("Animation with id " + mAnimationID + " was not found"); } } } private final class RemoveAnimationOperation extends AnimationOperation { private RemoveAnimationOperation(int animationID) { super(animationID); } @Override public void execute() { Animation animation = mAnimationRegistry.getAnimation(mAnimationID); if (animation != null) { animation.cancel(); } } } private class SetLayoutAnimationEnabledOperation implements UIOperation { private final boolean mEnabled; private SetLayoutAnimationEnabledOperation(final boolean enabled) { mEnabled = enabled; } @Override public void execute() { mNativeViewHierarchyManager.setLayoutAnimationEnabled(mEnabled); } } private class ConfigureLayoutAnimationOperation implements UIOperation { private final ReadableMap mConfig; private ConfigureLayoutAnimationOperation(final ReadableMap config) { mConfig = config; } @Override public void execute() { mNativeViewHierarchyManager.configureLayoutAnimation(mConfig); } } private final class MeasureOperation implements UIOperation { private final int mReactTag; private final Callback mCallback; private MeasureOperation( final int reactTag, final Callback callback) { super(); mReactTag = reactTag; mCallback = callback; } @Override public void execute() { try { mNativeViewHierarchyManager.measure(mReactTag, mMeasureBuffer); } catch (NoSuchNativeViewException e) { // Invoke with no args to signal failure and to allow JS to clean up the callback // handle. mCallback.invoke(); return; } float x = PixelUtil.toDIPFromPixel(mMeasureBuffer[0]); float y = PixelUtil.toDIPFromPixel(mMeasureBuffer[1]); float width = PixelUtil.toDIPFromPixel(mMeasureBuffer[2]); float height = PixelUtil.toDIPFromPixel(mMeasureBuffer[3]); mCallback.invoke(0, 0, width, height, x, y); } } private ArrayList<UIOperation> mOperations = new ArrayList<>(); private final class FindTargetForTouchOperation implements UIOperation { private final int mReactTag; private final float mTargetX; private final float mTargetY; private final Callback mCallback; private FindTargetForTouchOperation( final int reactTag, final float targetX, final float targetY, final Callback callback) { super(); mReactTag = reactTag; mTargetX = targetX; mTargetY = targetY; mCallback = callback; } @Override public void execute() { try { mNativeViewHierarchyManager.measure( mReactTag, mMeasureBuffer); } catch (IllegalViewOperationException e) { mCallback.invoke(); return; } // Because React coordinates are relative to root container, and measure() operates // on screen coordinates, we need to offset values using root container location. final float containerX = (float) mMeasureBuffer[0]; final float containerY = (float) mMeasureBuffer[1]; final int touchTargetReactTag = mNativeViewHierarchyManager.findTargetTagForTouch( mReactTag, mTargetX, mTargetY); try { mNativeViewHierarchyManager.measure( touchTargetReactTag, mMeasureBuffer); } catch (IllegalViewOperationException e) { mCallback.invoke(); return; } float x = PixelUtil.toDIPFromPixel(mMeasureBuffer[0] - containerX); float y = PixelUtil.toDIPFromPixel(mMeasureBuffer[1] - containerY); float width = PixelUtil.toDIPFromPixel(mMeasureBuffer[2]); float height = PixelUtil.toDIPFromPixel(mMeasureBuffer[3]); mCallback.invoke(touchTargetReactTag, x, y, width, height); } } private final class SendAccessibilityEvent extends ViewOperation { private final int mEventType; private SendAccessibilityEvent(int tag, int eventType) { super(tag); mEventType = eventType; } @Override public void execute() { mNativeViewHierarchyManager.sendAccessibilityEvent(mTag, mEventType); } } private final NativeViewHierarchyManager mNativeViewHierarchyManager; private final AnimationRegistry mAnimationRegistry; private final Object mDispatchRunnablesLock = new Object(); private final DispatchUIFrameCallback mDispatchUIFrameCallback; private final ReactApplicationContext mReactApplicationContext; @GuardedBy("mDispatchRunnablesLock") private final ArrayList<Runnable> mDispatchUIRunnables = new ArrayList<>(); private @Nullable NotThreadSafeViewHierarchyUpdateDebugListener mViewHierarchyUpdateDebugListener; public UIViewOperationQueue( ReactApplicationContext reactContext, NativeViewHierarchyManager nativeViewHierarchyManager) { mNativeViewHierarchyManager = nativeViewHierarchyManager; mAnimationRegistry = nativeViewHierarchyManager.getAnimationRegistry(); mDispatchUIFrameCallback = new DispatchUIFrameCallback(reactContext); mReactApplicationContext = reactContext; } public void setViewHierarchyUpdateDebugListener( @Nullable NotThreadSafeViewHierarchyUpdateDebugListener listener) { mViewHierarchyUpdateDebugListener = listener; } public boolean isEmpty() { return mOperations.isEmpty(); } public void addRootView( final int tag, final SizeMonitoringFrameLayout rootView, final ThemedReactContext themedRootContext) { if (UiThreadUtil.isOnUiThread()) { mNativeViewHierarchyManager.addRootView(tag, rootView, themedRootContext); } else { final Semaphore semaphore = new Semaphore(0); mReactApplicationContext.runOnUiQueueThread( new Runnable() { @Override public void run() { mNativeViewHierarchyManager.addRootView(tag, rootView, themedRootContext); semaphore.release(); } }); try { SoftAssertions.assertCondition( semaphore.tryAcquire(5000, TimeUnit.MILLISECONDS), "Timed out adding root view"); } catch (InterruptedException e) { throw new RuntimeException(e); } } } /** * Enqueues a UIOperation to be executed in UI thread. This method should only be used by a * subclass to support UIOperations not provided by UIViewOperationQueue. */ protected void enqueueUIOperation(UIOperation operation) { mOperations.add(operation); } public void enqueueRemoveRootView(int rootViewTag) { mOperations.add(new RemoveRootViewOperation(rootViewTag)); } public void enqueueSetJSResponder( int tag, int initialTag, boolean blockNativeResponder) { mOperations.add( new ChangeJSResponderOperation( tag, initialTag, false /*clearResponder*/, blockNativeResponder)); } public void enqueueClearJSResponder() { // Tag is 0 because JSResponderHandler doesn't need one in order to clear the responder. mOperations.add(new ChangeJSResponderOperation(0, 0, true /*clearResponder*/, false)); } public void enqueueDispatchCommand( int reactTag, int commandId, ReadableArray commandArgs) { mOperations.add(new DispatchCommandOperation(reactTag, commandId, commandArgs)); } public void enqueueUpdateExtraData(int reactTag, Object extraData) { mOperations.add(new UpdateViewExtraData(reactTag, extraData)); } public void enqueueShowPopupMenu( int reactTag, ReadableArray items, Callback error, Callback success) { mOperations.add(new ShowPopupMenuOperation(reactTag, items, success)); } public void enqueueCreateView( ThemedReactContext themedContext, int viewReactTag, String viewClassName, @Nullable CatalystStylesDiffMap initialProps) { mOperations.add( new CreateViewOperation( themedContext, viewReactTag, viewClassName, initialProps)); } public void enqueueUpdateProperties(int reactTag, String className, CatalystStylesDiffMap props) { mOperations.add(new UpdatePropertiesOperation(reactTag, props)); } public void enqueueUpdateLayout( int parentTag, int reactTag, int x, int y, int width, int height) { mOperations.add( new UpdateLayoutOperation(parentTag, reactTag, x, y, width, height)); } public void enqueueManageChildren( int reactTag, @Nullable int[] indicesToRemove, @Nullable ViewAtIndex[] viewsToAdd, @Nullable int[] tagsToDelete) { mOperations.add( new ManageChildrenOperation(reactTag, indicesToRemove, viewsToAdd, tagsToDelete)); } public void enqueueRegisterAnimation(Animation animation) { mOperations.add(new RegisterAnimationOperation(animation)); } public void enqueueAddAnimation( final int reactTag, final int animationID, final Callback onSuccess) { mOperations.add(new AddAnimationOperation(reactTag, animationID, onSuccess)); } public void enqueueRemoveAnimation(int animationID) { mOperations.add(new RemoveAnimationOperation(animationID)); } public void enqueueSetLayoutAnimationEnabled( final boolean enabled) { mOperations.add(new SetLayoutAnimationEnabledOperation(enabled)); } public void enqueueConfigureLayoutAnimation( final ReadableMap config, final Callback onSuccess, final Callback onError) { mOperations.add(new ConfigureLayoutAnimationOperation(config)); } public void enqueueMeasure( final int reactTag, final Callback callback) { mOperations.add( new MeasureOperation(reactTag, callback)); } public void enqueueFindTargetForTouch( final int reactTag, final float targetX, final float targetY, final Callback callback) { mOperations.add( new FindTargetForTouchOperation(reactTag, targetX, targetY, callback)); } public void enqueueSendAccessibilityEvent(int tag, int eventType) { mOperations.add(new SendAccessibilityEvent(tag, eventType)); } /* package */ void dispatchViewUpdates(final int batchId) { // Store the current operation queues to dispatch and create new empty ones to continue // receiving new operations final ArrayList<UIOperation> operations = mOperations.isEmpty() ? null : mOperations; if (operations != null) { mOperations = new ArrayList<>(); } if (mViewHierarchyUpdateDebugListener != null) { mViewHierarchyUpdateDebugListener.onViewHierarchyUpdateEnqueued(); } synchronized (mDispatchRunnablesLock) { mDispatchUIRunnables.add( new Runnable() { @Override public void run() { SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "DispatchUI") .arg("BatchId", batchId) .flush(); try { if (operations != null) { for (int i = 0; i < operations.size(); i++) { operations.get(i).execute(); } } if (mViewHierarchyUpdateDebugListener != null) { mViewHierarchyUpdateDebugListener.onViewHierarchyUpdateFinished(); } } finally { Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); } } }); } } /* package */ void resumeFrameCallback() { ReactChoreographer.getInstance() .postFrameCallback(ReactChoreographer.CallbackType.DISPATCH_UI, mDispatchUIFrameCallback); } /* package */ void pauseFrameCallback() { ReactChoreographer.getInstance() .removeFrameCallback(ReactChoreographer.CallbackType.DISPATCH_UI, mDispatchUIFrameCallback); } /** * Choreographer FrameCallback responsible for actually dispatching view updates on the UI thread * that were enqueued via {@link #dispatchViewUpdates(int)}. The reason we don't just enqueue * directly to the UI thread from that method is to make sure our Runnables actually run before * the next traversals happen: * * ViewRootImpl#scheduleTraversals (which is called from invalidate, requestLayout, etc) calls * Looper#postSyncBarrier which keeps any UI thread looper messages from being processed until * that barrier is removed during the next traversal. That means, depending on when we get updates * from JS and what else is happening on the UI thread, we can sometimes try to post this runnable * after ViewRootImpl has posted a barrier. * * Using a Choreographer callback (which runs immediately before traversals), we guarantee we run * before the next traversal. */ private class DispatchUIFrameCallback extends GuardedChoreographerFrameCallback { private DispatchUIFrameCallback(ReactContext reactContext) { super(reactContext); } @Override public void doFrameGuarded(long frameTimeNanos) { synchronized (mDispatchRunnablesLock) { for (int i = 0; i < mDispatchUIRunnables.size(); i++) { mDispatchUIRunnables.get(i).run(); } mDispatchUIRunnables.clear(); // Clear layout animation, as animation only apply to current UI operations batch. mNativeViewHierarchyManager.clearLayoutAnimation(); } ReactChoreographer.getInstance().postFrameCallback( ReactChoreographer.CallbackType.DISPATCH_UI, this); } } }
mihaigiurgeanu/react-native
ReactAndroid/src/main/java/com/facebook/react/uimanager/UIViewOperationQueue.java
Java
bsd-3-clause
22,305
<?php /* This program is free software; you can redistribute it and/or modify it under the terms of the Revised BSD 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 Revised BSD License for more details. Copyright 2011-2012 Cool Dude 2k - http://idb.berlios.de/ Copyright 2011-2012 Game Maker 2k - http://intdb.sourceforge.net/ Copyright 2011-2012 Kazuki Przyborowski - https://github.com/KazukiPrzyborowski $FileInfo: ean8.php - Last Update: 02/13/2012 Ver. 2.2.5 RC 1 - Author: cooldude2k $ */ $File3Name = basename($_SERVER['SCRIPT_NAME']); if ($File3Name=="ean8.php"||$File3Name=="/ean8.php") { chdir("../"); require("./upc.php"); exit(); } if(!isset($upcfunctions)) { $upcfunctions = array(); } if(!is_array($upcfunctions)) { $upcfunctions = array(); } array_push($upcfunctions, "create_ean8"); function create_ean8($upc,$imgtype="png",$outputimage=true,$resize=1,$resizetype="resize",$outfile=NULL,$hidecd=false) { if(!isset($upc)) { return false; } $upc_pieces = null; $supplement = null; if(preg_match("/([0-9]+)([ |\|]{1})([0-9]{2})$/", $upc, $upc_pieces)) { $upc = $upc_pieces[1]; $supplement = $upc_pieces[3]; } if(preg_match("/([0-9]+)([ |\|]){1}([0-9]{5})$/", $upc, $upc_pieces)) { $upc = $upc_pieces[1]; $supplement = $upc_pieces[3]; } if(!isset($upc)||!is_numeric($upc)) { return false; } if(strlen($upc)==7) { $upc = $upc.validate_ean8($upc,true); } if(strlen($upc)>8||strlen($upc)<8) { return false; } if(!isset($resize)||!preg_match("/^([0-9]*[\.]?[0-9])/", $resize)||$resize<1) { $resize = 1; } if($resizetype!="resample"&&$resizetype!="resize") { $resizetype = "resize"; } if(validate_ean8($upc)===false) { preg_match("/^(\d{7})/", $upc, $pre_matches); $upc = $pre_matches[1].validate_ean8($pre_matches[1],true); } if($imgtype!="png"&&$imgtype!="gif"&&$imgtype!="xbm"&&$imgtype!="wbmp") { $imgtype = "png"; } preg_match("/(\d{4})(\d{4})/", $upc, $upc_matches); if(count($upc_matches)<=0) { return false; } $LeftDigit = str_split($upc_matches[1]); preg_match("/(\d{2})(\d{2})/", $upc_matches[1], $upc_matches_new); $LeftLeftDigit = $upc_matches_new[1]; $LeftRightDigit = $upc_matches_new[2]; $RightDigit = str_split($upc_matches[2]); preg_match("/(\d{2})(\d{2})/", $upc_matches[2], $upc_matches_new); $RightLeftDigit = $upc_matches_new[1]; $RightRightDigit = $upc_matches_new[2]; if($imgtype=="png") { if($outputimage==true) { header("Content-Type: image/png"); } } if($imgtype=="gif") { if($outputimage==true) { header("Content-Type: image/gif"); } } if($imgtype=="xbm") { if($outputimage==true) { header("Content-Type: image/x-xbitmap"); } } if($imgtype=="wbmp") { if($outputimage==true) { header("Content-Type: image/vnd.wap.wbmp"); } } $addonsize = 0; if(strlen($supplement)==2) { $addonsize = 29; } if(strlen($supplement)==5) { $addonsize = 56; } $upc_img = imagecreatetruecolor(83 + $addonsize, 62); imagefilledrectangle($upc_img, 0, 0, 83 + $addonsize, 62, 0xFFFFFF); imageinterlace($upc_img, true); $background_color = imagecolorallocate($upc_img, 255, 255, 255); $text_color = imagecolorallocate($upc_img, 0, 0, 0); $alt_text_color = imagecolorallocate($upc_img, 255, 255, 255); imagestring($upc_img, 2, 12, 47, $LeftLeftDigit, $text_color); imagestring($upc_img, 2, 25, 47, $LeftRightDigit, $text_color); imagestring($upc_img, 2, 45, 47, $RightLeftDigit, $text_color); imagestring($upc_img, 2, 58, 47, $RightRightDigit, $text_color); imageline($upc_img, 0, 10, 0, 47, $alt_text_color); imageline($upc_img, 1, 10, 1, 47, $alt_text_color); imageline($upc_img, 2, 10, 2, 47, $alt_text_color); imageline($upc_img, 3, 10, 3, 47, $alt_text_color); imageline($upc_img, 4, 10, 4, 47, $alt_text_color); imageline($upc_img, 5, 10, 5, 47, $alt_text_color); imageline($upc_img, 6, 10, 6, 47, $alt_text_color); imageline($upc_img, 7, 10, 7, 53, $text_color); imageline($upc_img, 8, 10, 8, 53, $alt_text_color); imageline($upc_img, 9, 10, 9, 53, $text_color); $NumZero = 0; $LineStart = 10; while ($NumZero < count($LeftDigit)) { $LineSize = 47; $left_text_color_l = array(0, 0, 0, 0, 0, 0, 0); $left_text_color_g = array(1, 1, 1, 1, 1, 1, 1); if($LeftDigit[$NumZero]==0) { $left_text_color_l = array(0, 0, 0, 1, 1, 0, 1); $left_text_color_g = array(0, 1, 0, 0, 1, 1, 1); } if($LeftDigit[$NumZero]==1) { $left_text_color_l = array(0, 0, 1, 1, 0, 0, 1); $left_text_color_g = array(0, 1, 1, 0, 0, 1, 1); } if($LeftDigit[$NumZero]==2) { $left_text_color_l = array(0, 0, 1, 0, 0, 1, 1); $left_text_color_g = array(0, 0, 1, 1, 0, 1, 1); } if($LeftDigit[$NumZero]==3) { $left_text_color_l = array(0, 1, 1, 1, 1, 0, 1); $left_text_color_g = array(0, 1, 0, 0, 0, 0, 1); } if($LeftDigit[$NumZero]==4) { $left_text_color_l = array(0, 1, 0, 0, 0, 1, 1); $left_text_color_g = array(0, 0, 1, 1, 1, 0, 1); } if($LeftDigit[$NumZero]==5) { $left_text_color_l = array(0, 1, 1, 0, 0, 0, 1); $left_text_color_g = array(0, 1, 1, 1, 0, 0, 1); } if($LeftDigit[$NumZero]==6) { $left_text_color_l = array(0, 1, 0, 1, 1, 1, 1); $left_text_color_g = array(0, 0, 0, 0, 1, 0, 1); } if($LeftDigit[$NumZero]==7) { $left_text_color_l = array(0, 1, 1, 1, 0, 1, 1); $left_text_color_g = array(0, 0, 1, 0, 0, 0, 1); } if($LeftDigit[$NumZero]==8) { $left_text_color_l = array(0, 1, 1, 0, 1, 1, 1); $left_text_color_g = array(0, 0, 0, 1, 0, 0, 1); } if($LeftDigit[$NumZero]==9) { $left_text_color_l = array(0, 0, 0, 1, 0, 1, 1); $left_text_color_g = array(0, 0, 1, 0, 1, 1, 1); } $left_text_color = $left_text_color_l; if($upc_matches[1]==1) { if($NumZero==2) { $left_text_color = $left_text_color_g; } if($NumZero==4) { $left_text_color = $left_text_color_g; } if($NumZero==5) { $left_text_color = $left_text_color_g; } } if($upc_matches[1]==2) { if($NumZero==2) { $left_text_color = $left_text_color_g; } if($NumZero==3) { $left_text_color = $left_text_color_g; } if($NumZero==5) { $left_text_color = $left_text_color_g; } } if($upc_matches[1]==3) { if($NumZero==2) { $left_text_color = $left_text_color_g; } if($NumZero==3) { $left_text_color = $left_text_color_g; } if($NumZero==4) { $left_text_color = $left_text_color_g; } } if($upc_matches[1]==4) { if($NumZero==1) { $left_text_color = $left_text_color_g; } if($NumZero==4) { $left_text_color = $left_text_color_g; } if($NumZero==5) { $left_text_color = $left_text_color_g; } } if($upc_matches[1]==5) { if($NumZero==1) { $left_text_color = $left_text_color_g; } if($NumZero==2) { $left_text_color = $left_text_color_g; } if($NumZero==5) { $left_text_color = $left_text_color_g; } } if($upc_matches[1]==6) { if($NumZero==1) { $left_text_color = $left_text_color_g; } if($NumZero==2) { $left_text_color = $left_text_color_g; } if($NumZero==3) { $left_text_color = $left_text_color_g; } } if($upc_matches[1]==7) { if($NumZero==1) { $left_text_color = $left_text_color_g; } if($NumZero==3) { $left_text_color = $left_text_color_g; } if($NumZero==5) { $left_text_color = $left_text_color_g; } } if($upc_matches[1]==8) { if($NumZero==1) { $left_text_color = $left_text_color_g; } if($NumZero==3) { $left_text_color = $left_text_color_g; } if($NumZero==4) { $left_text_color = $left_text_color_g; } } if($upc_matches[1]==9) { if($NumZero==1) { $left_text_color = $left_text_color_g; } if($NumZero==2) { $left_text_color = $left_text_color_g; } if($NumZero==4) { $left_text_color = $left_text_color_g; } } $InnerUPCNum = 0; while ($InnerUPCNum < count($left_text_color)) { if($left_text_color[$InnerUPCNum]==1) { imageline($upc_img, $LineStart, 10, $LineStart, $LineSize, $text_color); } if($left_text_color[$InnerUPCNum]==0) { imageline($upc_img, $LineStart, 10, $LineStart, $LineSize, $alt_text_color); } $LineStart += 1; ++$InnerUPCNum; } ++$NumZero; } imageline($upc_img, 38, 10, 38, 53, $alt_text_color); imageline($upc_img, 39, 10, 39, 53, $text_color); imageline($upc_img, 40, 10, 40, 53, $alt_text_color); imageline($upc_img, 41, 10, 41, 53, $text_color); imageline($upc_img, 42, 10, 42, 53, $alt_text_color); $NumZero = 0; $LineStart = 43; while ($NumZero < count($RightDigit)) { $LineSize = 47; $right_text_color = array(0, 0, 0, 0, 0, 0, 0); if($RightDigit[$NumZero]==0) { $right_text_color = array(1, 1, 1, 0, 0, 1, 0); } if($RightDigit[$NumZero]==1) { $right_text_color = array(1, 1, 0, 0, 1, 1, 0); } if($RightDigit[$NumZero]==2) { $right_text_color = array(1, 1, 0, 1, 1, 0, 0); } if($RightDigit[$NumZero]==3) { $right_text_color = array(1, 0, 0, 0, 0, 1, 0); } if($RightDigit[$NumZero]==4) { $right_text_color = array(1, 0, 1, 1, 1, 0, 0); } if($RightDigit[$NumZero]==5) { $right_text_color = array(1, 0, 0, 1, 1, 1, 0); } if($RightDigit[$NumZero]==6) { $right_text_color = array(1, 0, 1, 0, 0, 0, 0); } if($RightDigit[$NumZero]==7) { $right_text_color = array(1, 0, 0, 0, 1, 0, 0); } if($RightDigit[$NumZero]==8) { $right_text_color = array(1, 0, 0, 1, 0, 0, 0); } if($RightDigit[$NumZero]==9) { $right_text_color = array(1, 1, 1, 0, 1, 0, 0); } $InnerUPCNum = 0; while ($InnerUPCNum < count($right_text_color)) { if($right_text_color[$InnerUPCNum]==1) { imageline($upc_img, $LineStart, 10, $LineStart, $LineSize, $text_color); } if($right_text_color[$InnerUPCNum]==0) { imageline($upc_img, $LineStart, 10, $LineStart, $LineSize, $alt_text_color); } $LineStart += 1; ++$InnerUPCNum; } ++$NumZero; } imageline($upc_img, 71, 10, 71, 53, $text_color); imageline($upc_img, 72, 10, 72, 53, $alt_text_color); imageline($upc_img, 73, 10, 73, 53, $text_color); imageline($upc_img, 74, 10, 74, 47, $alt_text_color); imageline($upc_img, 75, 10, 75, 47, $alt_text_color); imageline($upc_img, 76, 10, 76, 47, $alt_text_color); imageline($upc_img, 77, 10, 77, 47, $alt_text_color); imageline($upc_img, 78, 10, 78, 47, $alt_text_color); imageline($upc_img, 79, 10, 79, 47, $alt_text_color); imageline($upc_img, 80, 10, 80, 47, $alt_text_color); imageline($upc_img, 81, 10, 81, 47, $alt_text_color); imageline($upc_img, 82, 10, 82, 47, $alt_text_color); if(strlen($supplement)==2) { create_ean2($supplement,83,$upc_img); } if(strlen($supplement)==5) { create_ean5($supplement,83,$upc_img); } if($resize>1) { $new_upc_img = imagecreatetruecolor((83 + $addonsize) * $resize, 62 * $resize); imagefilledrectangle($new_upc_img, 0, 0, 83 + $addonsize, 62, 0xFFFFFF); imageinterlace($new_upc_img, true); if($resizetype=="resize") { imagecopyresized($new_upc_img, $upc_img, 0, 0, 0, 0, (83 + $addonsize) * $resize, 62 * $resize, 83 + $addonsize, 62); } if($resizetype=="resample") { imagecopyresampled($new_upc_img, $upc_img, 0, 0, 0, 0, (83 + $addonsize) * $resize, 62 * $resize, 83 + $addonsize, 62); } imagedestroy($upc_img); $upc_img = $new_upc_img; } if($imgtype=="png") { if($outputimage==true) { imagepng($upc_img); } if($outfile!=null) { imagepng($upc_img,$outfile); } } if($imgtype=="gif") { if($outputimage==true) { imagegif($upc_img); } if($outfile!=null) { imagegif($upc_img,$outfile); } } if($imgtype=="xbm") { if($outputimage==true) { imagexbm($upc_img,NULL); } if($outfile!=null) { imagexbm($upc_img,$outfile); } } if($imgtype=="wbmp") { if($outputimage==true) { imagewbmp($upc_img); } if($outfile!=null) { imagewbmp($upc_img,$outfile); } } imagedestroy($upc_img); return true; } ?>
GameMaker2k/UPC-Database
inc/ean8.php
PHP
bsd-3-clause
11,580
using System.Globalization; using System.Collections.Generic; using ServiceStack.Common; using ServiceStack.Common.Web; using ServiceStack.ServiceHost; using ServiceStack.Configuration; using ServiceStack.FluentValidation; using ServiceStack.Text; using System; using System.Net; using System.Security.Cryptography; using System.Text; using ServiceStack.WebHost.Endpoints.Extensions; using HttpResponseExtensions = ServiceStack.WebHost.Endpoints.Extensions.HttpResponseExtensions; namespace ServiceStack.ServiceInterface.Auth { public class DigestAuthProvider : AuthProvider { class DigestAuthValidator : AbstractValidator<Auth> { public DigestAuthValidator() { RuleFor(x => x.UserName).NotEmpty(); RuleFor(x => x.Password).NotEmpty(); } } public static string Name = AuthService.DigestProvider; public static string Realm = "/auth/" + AuthService.DigestProvider; public static int NonceTimeOut = 600; public string PrivateKey; public IResourceManager AppSettings { get; set; } public DigestAuthProvider() { this.Provider = Name; PrivateKey = Guid.NewGuid().ToString(); this.AuthRealm = Realm; } public DigestAuthProvider(IResourceManager appSettings, string authRealm, string oAuthProvider) : base(appSettings, authRealm, oAuthProvider) { } public DigestAuthProvider(IResourceManager appSettings) : base(appSettings, Realm, Name) { } public virtual bool TryAuthenticate(IServiceBase authService, string userName, string password) { var authRepo = authService.TryResolve<IUserAuthRepository>(); if (authRepo == null) { Log.WarnFormat("Tried to authenticate without a registered IUserAuthRepository"); return false; } var session = authService.GetSession(); var digestInfo = authService.RequestContext.Get<IHttpRequest>().GetDigestAuth(); UserAuth userAuth = null; if (authRepo.TryAuthenticate(digestInfo,PrivateKey,NonceTimeOut, session.Sequence, out userAuth)) { session.PopulateWith(userAuth); session.IsAuthenticated = true; session.Sequence = digestInfo["nc"]; session.UserAuthId = userAuth.Id.ToString(CultureInfo.InvariantCulture); session.ProviderOAuthAccess = authRepo.GetUserOAuthProviders(session.UserAuthId) .ConvertAll(x => (IOAuthTokens)x); return true; } return false; } public override bool IsAuthorized(IAuthSession session, IOAuthTokens tokens, Auth request = null) { if (request != null) { if (!LoginMatchesSession(session, request.UserName)) return false; } return !session.UserAuthName.IsNullOrEmpty(); } public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { //new CredentialsAuthValidator().ValidateAndThrow(request); return Authenticate(authService, session, request.UserName, request.Password); } protected object Authenticate(IServiceBase authService, IAuthSession session, string userName, string password) { if (!LoginMatchesSession(session, userName)) { authService.RemoveSession(); session = authService.GetSession(); } if (TryAuthenticate(authService, userName, password)) { if (session.UserAuthName == null) session.UserAuthName = userName; OnAuthenticated(authService, session, null, null); return new AuthResponse { UserName = userName, SessionId = session.Id, }; } throw HttpError.Unauthorized("Invalid UserName or Password"); } public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo) { var userSession = session as AuthUserSession; if (userSession != null) { LoadUserAuthInfo(userSession, tokens, authInfo); } var authRepo = authService.TryResolve<IUserAuthRepository>(); if (authRepo != null) { if (tokens != null) { authInfo.ForEach((x, y) => tokens.Items[x] = y); session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens); } foreach (var oAuthToken in session.ProviderOAuthAccess) { var authProvider = AuthService.GetAuthProvider(oAuthToken.Provider); if (authProvider == null) continue; var userAuthProvider = authProvider as OAuthProvider; if (userAuthProvider != null) { userAuthProvider.LoadUserOAuthProvider(session, oAuthToken); } } //var httpRes = authService.RequestContext.Get<IHttpResponse>(); //if (httpRes != null) //{ // httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId); //} } authService.SaveSession(session, SessionExpiry); session.OnAuthenticated(authService, session, tokens, authInfo); } public override void OnFailedAuthentication(IAuthSession session, IHttpRequest httpReq, IHttpResponse httpRes) { var digestHelper = new DigestAuthFunctions(); httpRes.StatusCode = (int)HttpStatusCode.Unauthorized; httpRes.AddHeader(HttpHeaders.WwwAuthenticate, "{0} realm=\"{1}\", nonce=\"{2}\", qop=\"auth\"".Fmt(Provider, AuthRealm,digestHelper.GetNonce(httpReq.UserHostAddress,PrivateKey))); httpRes.EndRequest(); } } }
fanta-mnix/ServiceStack
src/ServiceStack.ServiceInterface/Auth/DigestAuthProvider.cs
C#
bsd-3-clause
6,338
<?php namespace mageekguy\atoum\fs; use mageekguy\atoum\fs\path\exception; class path { protected $drive = ''; protected $components = ''; protected $directorySeparator = DIRECTORY_SEPARATOR; public function __construct($value, $directorySeparator = null) { $this ->setDriveAndComponents($value) ->directorySeparator = (string) $directorySeparator ?: DIRECTORY_SEPARATOR ; } public function __toString() { $components = $this->components; if ($this->directorySeparator === '\\') { $components = str_replace('/', '\\', $components); } return $this->drive . $components; } public function getDirectorySeparator() { return $this->directorySeparator; } public function relativizeFrom(path $reference) { $this->resolve(); $resolvedReferencePath = $reference->getResolvedPath(); $this->drive = null; switch (true) { case $this->components === '/': $this->components = '.' . $this->components; break; case $this->components === $resolvedReferencePath->components: $this->components = '.'; break; case $this->isSubPathOf($resolvedReferencePath): $this->components = './' . ltrim(substr($this->components, strlen($resolvedReferencePath->components)), '/'); break; default: $relativePath = ''; while ($this->isNotSubPathOf($resolvedReferencePath)) { $relativePath .= '../'; $resolvedReferencePath = $resolvedReferencePath->getParentDirectoryPath(); } $this->components = static::getComponents($relativePath) . '/' . ltrim(substr($this->components, strlen($resolvedReferencePath->components)), '/'); } return $this; } public function exists() { return (file_exists((string) $this) === true); } public function resolve() { if ($this->isAbsolute() === false) { $this->absolutize(); } $components = []; foreach (explode('/', ltrim($this->components, '/')) as $component) { switch ($component) { case '.': break; case '..': if (count($components) <= 0) { throw new exception('Unable to resolve path \'' . $this . '\''); } array_pop($components); break; default: $components[] = $component; } } $this->components = '/' . implode('/', $components); return $this; } public function isSubPathOf(path $path) { $this->resolve(); $resolvedPath = $path->getResolvedPath(); return ($this->components !== $resolvedPath->components && ($resolvedPath->isRoot() === true || strpos($this->components, $resolvedPath->components . '/') === 0)); } public function isNotSubPathOf(path $path) { return ($this->isSubPathOf($path) === false); } public function isRoot() { return static::pathIsRoot($this->getResolvedPath()->components); } public function isAbsolute() { return static::pathIsAbsolute($this->components); } public function absolutize() { if ($this->isAbsolute() === false) { $this->setDriveAndComponents(getcwd() . DIRECTORY_SEPARATOR . $this->components); } return $this; } public function getRealPath() { $absolutePath = $this->getAbsolutePath(); $files = ''; $realPath = realpath((string) $absolutePath); if ($realPath === false) { while ($realPath === false && $absolutePath->isRoot() === false) { $files = '/' . basename((string) $absolutePath) . $files; $absolutePath = $absolutePath->getParentDirectoryPath(); $realPath = realpath((string) $absolutePath); } } if ($realPath === false) { throw new exception('Unable to get real path for \'' . $this . '\''); } return $absolutePath->setDriveAndComponents($realPath . $files); } public function getParentDirectoryPath() { $parentDirectory = clone $this; $parentDirectory->components = self::getComponents(dirname($parentDirectory->components)); return $parentDirectory; } public function getRealParentDirectoryPath() { $realParentDirectoryPath = $this->getParentDirectoryPath(); while ($realParentDirectoryPath->exists() === false && $realParentDirectoryPath->isRoot() === false) { $realParentDirectoryPath = $realParentDirectoryPath->getParentDirectoryPath(); } if ($realParentDirectoryPath->exists() === false) { throw new exception('Unable to find real parent directory for \'' . $this . '\''); } return $realParentDirectoryPath; } public function getRelativePathFrom(path $reference) { $clone = clone $this; return $clone->relativizeFrom($reference); } public function getResolvedPath() { $clone = clone $this; return $clone->resolve(); } public function getAbsolutePath() { $clone = clone $this; return $clone->absolutize(); } public function createParentDirectory() { $parentDirectory = $this->getParentDirectoryPath(); if (file_exists((string) $parentDirectory) === false && @mkdir($parentDirectory, 0777, true) === false) { throw new exception('Unable to create directory \'' . $parentDirectory . '\''); } return $this; } public function putContents($data) { if (@file_put_contents($this->createParentDirectory(), $data) === false) { throw new exception('Unable to put data \'' . $data . '\' in file \'' . $this . '\''); } return $this; } protected function setDriveAndComponents($value) { $drive = null; if (preg_match('#^[a-z]:#i', $value, $matches) == true) { $drive = $matches[0]; $value = substr($value, 2); } $this->drive = $drive; $this->components = self::getComponents($value); return $this; } protected static function pathIsRoot($path) { return ($path === '/'); } protected static function pathIsAbsolute($path) { return (substr($path, 0, 1) === '/'); } protected static function getComponents($path) { $path = str_replace('\\', '/', $path); if (static::pathIsRoot($path) === false) { $path = rtrim($path, '/'); } return preg_replace('#/{2,}#', '/', $path); } }
jubianchi/atoum
classes/fs/path.php
PHP
bsd-3-clause
7,037
from energenie import switch_off switch_off()
rjw57/energenie
examples/simple/off.py
Python
bsd-3-clause
47
require "og/store/sql/utils" module Og module SqliteUtils include SqlUtils # works fine without any quote. #-- # Is this verified? #++ def quote_column(val) return val end alias_method :quote_table, :quote_column end end
oxywtf/og
lib/og/adapter/sqlite/utils.rb
Ruby
bsd-3-clause
255
""" WSGI config for {{ cookiecutter.project_name }} project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os {% if cookiecutter.use_newrelic == 'y' -%} if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production': import newrelic.agent newrelic.agent.initialize() {%- endif %} from django.core.wsgi import get_wsgi_application {% if cookiecutter.use_sentry == 'y' -%} if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production': from raven.contrib.django.raven_compat.middleware.wsgi import Sentry {%- endif %} # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. application = get_wsgi_application() {% if cookiecutter.use_sentry == 'y' -%} if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production': application = Sentry(application) {%- endif %} {% if cookiecutter.use_newrelic == 'y' -%} if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production': application = newrelic.agent.WSGIApplicationWrapper(application) {%- endif %} # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
aeikenberry/cookiecutter-django-rest-babel
{{cookiecutter.project_slug}}/config/wsgi.py
Python
bsd-3-clause
2,232
<?php require_once('connect.inc'); require_once('table.inc'); $references = array(); if (!(mysqli_real_query($link, "SELECT id, label FROM test ORDER BY id ASC LIMIT 2")) || !($res = mysqli_store_result($link))) printf("[001] [%d] %s\n", mysqli_errno($link), mysqli_error($link)); $idx = 0; while ($row = mysqli_fetch_assoc($res)) { /* mysqlnd: force separation - create copies */ $references[$idx] = array( 'id' => &$row['id'], 'label' => $row['label'] . ''); $references[$idx++]['id'] += 0; } mysqli_close($link); mysqli_data_seek($res, 0); while ($row = mysqli_fetch_assoc($res)) { /* mysqlnd: force separation - create copies */ $references[$idx] = array( 'id' => &$row['id'], 'label' => $row['label'] . ''); $references[$idx++]['id'] += 0; } mysqli_free_result($res); if (!$link = my_mysqli_connect($host, $user, $passwd, $db, $port, $socket)) printf("[002] Cannot connect to the server using host=%s, user=%s, passwd=***, dbname=%s, port=%s, socket=%s\n", $host, $user, $db, $port, $socket); if (!(mysqli_real_query($link, "SELECT id, label FROM test ORDER BY id ASC LIMIT 2")) || !($res = mysqli_use_result($link))) printf("[003] [%d] %s\n", mysqli_errno($link), mysqli_error($link)); while ($row = mysqli_fetch_assoc($res)) { /* mysqlnd: force separation - create copies*/ $references[$idx] = array( 'id' => &$row['id'], 'label' => $row['label'] . ''); $references[$idx]['id2'] = &$references[$idx]['id']; $references[$idx]['id'] += 1; $references[$idx++]['id2'] += 1; } $references[$idx++] = &$res; mysqli_free_result($res); @debug_zval_dump($references); if (!(mysqli_real_query($link, "SELECT id, label FROM test ORDER BY id ASC LIMIT 1")) || !($res = mysqli_use_result($link))) printf("[004] [%d] %s\n", mysqli_errno($link), mysqli_error($link)); $tmp = array(); while ($row = mysqli_fetch_assoc($res)) { $tmp[] = $row; } $tmp = unserialize(serialize($tmp)); debug_zval_dump($tmp); mysqli_free_result($res); mysqli_close($link); print "done!"; ?>
stephens2424/php
testdata/fuzzdir/corpus/ext_mysqli_tests_mysqli_result_references.php
PHP
bsd-3-clause
2,068
// // Mono.Security.Cryptography.SymmetricTransform implementation // // Authors: // Thomas Neidhart (tome@sbox.tugraz.at) // Sebastien Pouliot <sebastien@ximian.com> // // Portions (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004-2008 Novell, Inc (http://www.novell.com) // // 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. // using System; using System.Security.Cryptography; namespace Mono.Security.Cryptography { // This class implement most of the common code required for symmetric // algorithm transforms, like: // - CipherMode: Builds CBC and CFB on top of (descendant supplied) ECB // - PaddingMode, transform properties, multiple blocks, reuse... // // Descendants MUST: // - intialize themselves (like key expansion, ...) // - override the ECB (Electronic Code Book) method which will only be // called using BlockSize byte[] array. internal abstract class SymmetricTransform : ICryptoTransform { protected SymmetricAlgorithm algo; protected bool encrypt; protected int BlockSizeByte; protected byte[] temp; protected byte[] temp2; private byte[] workBuff; private byte[] workout; protected PaddingMode padmode; // Silverlight 2.0 does not support any feedback mode protected int FeedBackByte; private bool m_disposed = false; protected bool lastBlock; public SymmetricTransform (SymmetricAlgorithm symmAlgo, bool encryption, byte[] rgbIV) { algo = symmAlgo; encrypt = encryption; BlockSizeByte = (algo.BlockSize >> 3); if (rgbIV == null) { rgbIV = KeyBuilder.IV (BlockSizeByte); } else { rgbIV = (byte[]) rgbIV.Clone (); } // compare the IV length with the "currently selected" block size and *ignore* IV that are too big if (rgbIV.Length < BlockSizeByte) { string msg = string.Format ("IV is too small ({0} bytes), it should be {1} bytes long.", rgbIV.Length, BlockSizeByte); throw new CryptographicException (msg); } padmode = algo.Padding; // mode buffers temp = new byte [BlockSizeByte]; Buffer.BlockCopy (rgbIV, 0, temp, 0, System.Math.Min (BlockSizeByte, rgbIV.Length)); temp2 = new byte [BlockSizeByte]; FeedBackByte = (algo.FeedbackSize >> 3); // transform buffers workBuff = new byte [BlockSizeByte]; workout = new byte [BlockSizeByte]; } ~SymmetricTransform () { Dispose (false); } void IDisposable.Dispose () { Dispose (true); GC.SuppressFinalize (this); // Finalization is now unnecessary } // MUST be overriden by classes using unmanaged ressources // the override method must call the base class protected virtual void Dispose (bool disposing) { if (!m_disposed) { if (disposing) { // dispose managed object: zeroize and free Array.Clear (temp, 0, BlockSizeByte); temp = null; Array.Clear (temp2, 0, BlockSizeByte); temp2 = null; } m_disposed = true; } } public virtual bool CanTransformMultipleBlocks { get { return true; } } public virtual bool CanReuseTransform { get { return false; } } public virtual int InputBlockSize { get { return BlockSizeByte; } } public virtual int OutputBlockSize { get { return BlockSizeByte; } } // note: Each block MUST be BlockSizeValue in size!!! // i.e. Any padding must be done before calling this method protected virtual void Transform (byte[] input, byte[] output) { switch (algo.Mode) { case CipherMode.ECB: ECB (input, output); break; case CipherMode.CBC: CBC (input, output); break; case CipherMode.CFB: CFB (input, output); break; case CipherMode.OFB: OFB (input, output); break; case CipherMode.CTS: CTS (input, output); break; default: throw new NotImplementedException ("Unkown CipherMode" + algo.Mode.ToString ()); } } // Electronic Code Book (ECB) protected abstract void ECB (byte[] input, byte[] output); // Cipher-Block-Chaining (CBC) protected virtual void CBC (byte[] input, byte[] output) { if (encrypt) { for (int i = 0; i < BlockSizeByte; i++) temp[i] ^= input[i]; ECB (temp, output); Buffer.BlockCopy (output, 0, temp, 0, BlockSizeByte); } else { Buffer.BlockCopy (input, 0, temp2, 0, BlockSizeByte); ECB (input, output); for (int i = 0; i < BlockSizeByte; i++) output[i] ^= temp[i]; Buffer.BlockCopy (temp2, 0, temp, 0, BlockSizeByte); } } // Cipher-FeedBack (CFB) // this is how *CryptoServiceProvider implements CFB // only AesCryptoServiceProvider support CFB > 8 // RijndaelManaged is incompatible with this implementation (and overrides it in it's own transform) protected virtual void CFB (byte[] input, byte[] output) { if (encrypt) { for (int x = 0; x < BlockSizeByte; x++) { // temp is first initialized with the IV ECB (temp, temp2); output [x] = (byte) (temp2 [0] ^ input [x]); Buffer.BlockCopy (temp, 1, temp, 0, BlockSizeByte - 1); Buffer.BlockCopy (output, x, temp, BlockSizeByte - 1, 1); } } else { for (int x = 0; x < BlockSizeByte; x++) { // we do not really decrypt this data! encrypt = true; // temp is first initialized with the IV ECB (temp, temp2); encrypt = false; Buffer.BlockCopy (temp, 1, temp, 0, BlockSizeByte - 1); Buffer.BlockCopy (input, x, temp, BlockSizeByte - 1, 1); output [x] = (byte) (temp2 [0] ^ input [x]); } } } // Output-FeedBack (OFB) protected virtual void OFB (byte[] input, byte[] output) { throw new CryptographicException ("OFB isn't supported by the framework"); } // Cipher Text Stealing (CTS) protected virtual void CTS (byte[] input, byte[] output) { throw new CryptographicException ("CTS isn't supported by the framework"); } private void CheckInput (byte[] inputBuffer, int inputOffset, int inputCount) { if (inputBuffer == null) throw new ArgumentNullException ("inputBuffer"); if (inputOffset < 0) throw new ArgumentOutOfRangeException ("inputOffset", "< 0"); if (inputCount < 0) throw new ArgumentOutOfRangeException ("inputCount", "< 0"); // ordered to avoid possible integer overflow if (inputOffset > inputBuffer.Length - inputCount) throw new ArgumentException ("inputBuffer", ("Overflow")); } // this method may get called MANY times so this is the one to optimize public virtual int TransformBlock (byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { if (m_disposed) throw new ObjectDisposedException ("Object is disposed"); CheckInput (inputBuffer, inputOffset, inputCount); // check output parameters if (outputBuffer == null) throw new ArgumentNullException ("outputBuffer"); if (outputOffset < 0) throw new ArgumentOutOfRangeException ("outputOffset", "< 0"); // ordered to avoid possible integer overflow int len = outputBuffer.Length - inputCount - outputOffset; if (!encrypt && (0 > len) && ((padmode == PaddingMode.None) || (padmode == PaddingMode.Zeros))) { throw new CryptographicException ("outputBuffer", ("Overflow")); } else if (KeepLastBlock) { if (0 > len + BlockSizeByte) { throw new CryptographicException ("outputBuffer", ("Overflow")); } } else { if (0 > len) { // there's a special case if this is the end of the decryption process if (inputBuffer.Length - inputOffset - outputBuffer.Length == BlockSizeByte) inputCount = outputBuffer.Length - outputOffset; else throw new CryptographicException ("outputBuffer", ("Overflow")); } } return InternalTransformBlock (inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); } private bool KeepLastBlock { get { return ((!encrypt) && (padmode != PaddingMode.None) && (padmode != PaddingMode.Zeros)); } } private int InternalTransformBlock (byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { int offs = inputOffset; int full; // this way we don't do a modulo every time we're called // and we may save a division if (inputCount != BlockSizeByte) { if ((inputCount % BlockSizeByte) != 0) throw new CryptographicException ("Invalid input block size."); full = inputCount / BlockSizeByte; } else full = 1; if (KeepLastBlock) full--; int total = 0; if (lastBlock) { Transform (workBuff, workout); Buffer.BlockCopy (workout, 0, outputBuffer, outputOffset, BlockSizeByte); outputOffset += BlockSizeByte; total += BlockSizeByte; lastBlock = false; } for (int i = 0; i < full; i++) { Buffer.BlockCopy (inputBuffer, offs, workBuff, 0, BlockSizeByte); Transform (workBuff, workout); Buffer.BlockCopy (workout, 0, outputBuffer, outputOffset, BlockSizeByte); offs += BlockSizeByte; outputOffset += BlockSizeByte; total += BlockSizeByte; } if (KeepLastBlock) { Buffer.BlockCopy (inputBuffer, offs, workBuff, 0, BlockSizeByte); lastBlock = true; } return total; } RandomNumberGenerator _rng; private void Random (byte[] buffer, int start, int length) { if (_rng == null) { _rng = RandomNumberGenerator.Create (); } byte[] random = new byte [length]; _rng.GetBytes (random); Buffer.BlockCopy (random, 0, buffer, start, length); } private void ThrowBadPaddingException (PaddingMode padding, int length, int position) { string msg = String.Format ( ("Bad {0} padding."), padding); if (length >= 0) msg += String.Format ( (" Invalid length {0}."), length); if (position >= 0) msg += String.Format ( (" Error found at position {0}."), position); throw new CryptographicException (msg); } protected virtual byte[] FinalEncrypt (byte[] inputBuffer, int inputOffset, int inputCount) { // are there still full block to process ? int full = (inputCount / BlockSizeByte) * BlockSizeByte; int rem = inputCount - full; int total = full; switch (padmode) { case PaddingMode.ANSIX923: case PaddingMode.ISO10126: case PaddingMode.PKCS7: // we need to add an extra block for padding total += BlockSizeByte; break; default: if (inputCount == 0) return new byte [0]; if (rem != 0) { if (padmode == PaddingMode.None) throw new CryptographicException ("invalid block length"); // zero padding the input (by adding a block for the partial data) byte[] paddedInput = new byte [full + BlockSizeByte]; Buffer.BlockCopy (inputBuffer, inputOffset, paddedInput, 0, inputCount); inputBuffer = paddedInput; inputOffset = 0; inputCount = paddedInput.Length; total = inputCount; } break; } byte[] res = new byte [total]; int outputOffset = 0; // process all blocks except the last (final) block while (total > BlockSizeByte) { InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset); inputOffset += BlockSizeByte; outputOffset += BlockSizeByte; total -= BlockSizeByte; } // now we only have a single last block to encrypt byte padding = (byte) (BlockSizeByte - rem); switch (padmode) { case PaddingMode.ANSIX923: // XX 00 00 00 00 00 00 07 (zero + padding length) res [res.Length - 1] = padding; Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem); // the last padded block will be transformed in-place InternalTransformBlock (res, full, BlockSizeByte, res, full); break; case PaddingMode.ISO10126: // XX 3F 52 2A 81 AB F7 07 (random + padding length) Random (res, res.Length - padding, padding - 1); res [res.Length - 1] = padding; Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem); // the last padded block will be transformed in-place InternalTransformBlock (res, full, BlockSizeByte, res, full); break; case PaddingMode.PKCS7: // XX 07 07 07 07 07 07 07 (padding length) for (int i = res.Length; --i >= (res.Length - padding);) res [i] = padding; Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem); // the last padded block will be transformed in-place InternalTransformBlock (res, full, BlockSizeByte, res, full); break; default: InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset); break; } return res; } protected virtual byte[] FinalDecrypt (byte[] inputBuffer, int inputOffset, int inputCount) { int full = inputCount; int total = inputCount; if (lastBlock) total += BlockSizeByte; byte[] res = new byte [total]; int outputOffset = 0; while (full > 0) { int len = InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset); inputOffset += BlockSizeByte; outputOffset += len; full -= BlockSizeByte; } if (lastBlock) { Transform (workBuff, workout); Buffer.BlockCopy (workout, 0, res, outputOffset, BlockSizeByte); outputOffset += BlockSizeByte; lastBlock = false; } // total may be 0 (e.g. PaddingMode.None) byte padding = ((total > 0) ? res [total - 1] : (byte) 0); switch (padmode) { case PaddingMode.ANSIX923: if ((padding == 0) || (padding > BlockSizeByte)) ThrowBadPaddingException (padmode, padding, -1); for (int i = padding - 1; i > 0; i--) { if (res [total - 1 - i] != 0x00) ThrowBadPaddingException (padmode, -1, i); } total -= padding; break; case PaddingMode.ISO10126: if ((padding == 0) || (padding > BlockSizeByte)) ThrowBadPaddingException (padmode, padding, -1); total -= padding; break; case PaddingMode.PKCS7: if ((padding == 0) || (padding > BlockSizeByte)) ThrowBadPaddingException (padmode, padding, -1); for (int i = padding - 1; i > 0; i--) { if (res [total - 1 - i] != padding) ThrowBadPaddingException (padmode, -1, i); } total -= padding; break; case PaddingMode.None: // nothing to do - it's a multiple of block size case PaddingMode.Zeros: // nothing to do - user must unpad himself break; } // return output without padding if (total > 0) { byte[] data = new byte [total]; Buffer.BlockCopy (res, 0, data, 0, total); // zeroize decrypted data (copy with padding) Array.Clear (res, 0, res.Length); return data; } else return new byte [0]; } public virtual byte[] TransformFinalBlock (byte[] inputBuffer, int inputOffset, int inputCount) { if (m_disposed) throw new ObjectDisposedException ("Object is disposed"); CheckInput (inputBuffer, inputOffset, inputCount); if (encrypt) return FinalEncrypt (inputBuffer, inputOffset, inputCount); else return FinalDecrypt (inputBuffer, inputOffset, inputCount); } } }
ngs-doo/revenj
csharp/Core/Revenj.Core/Security/Mono.Security/Mono.Security.Cryptography/SymmetricTransform.cs
C#
bsd-3-clause
16,384
using System; using System.Collections.Generic; using System.Linq; using OrchardCore.ContentManagement.Routing; namespace OrchardCore.Autoroute.Services { public class AutorouteEntries : IAutorouteEntries { private readonly Dictionary<string, AutorouteEntry> _paths; private readonly Dictionary<string, AutorouteEntry> _contentItemIds; public AutorouteEntries() { _paths = new Dictionary<string, AutorouteEntry>(); _contentItemIds = new Dictionary<string, AutorouteEntry>(StringComparer.OrdinalIgnoreCase); } public bool TryGetEntryByPath(string path, out AutorouteEntry entry) { return _contentItemIds.TryGetValue(path, out entry); } public bool TryGetEntryByContentItemId(string contentItemId, out AutorouteEntry entry) { return _paths.TryGetValue(contentItemId, out entry); } public void AddEntries(IEnumerable<AutorouteEntry> entries) { lock (this) { // Evict all entries related to a container item from autoroute entries. // This is necessary to account for deletions, disabling of an item, or disabling routing of contained items. foreach (var entry in entries.Where(x => String.IsNullOrEmpty(x.ContainedContentItemId))) { var entriesToRemove = _paths.Values.Where(x => x.ContentItemId == entry.ContentItemId && !String.IsNullOrEmpty(x.ContainedContentItemId)); foreach (var entryToRemove in entriesToRemove) { _paths.Remove(entryToRemove.ContainedContentItemId); _contentItemIds.Remove(entryToRemove.Path); } } foreach (var entry in entries) { if (_paths.TryGetValue(entry.ContentItemId, out var previousContainerEntry) && String.IsNullOrEmpty(entry.ContainedContentItemId)) { _contentItemIds.Remove(previousContainerEntry.Path); } if (!String.IsNullOrEmpty(entry.ContainedContentItemId) && _paths.TryGetValue(entry.ContainedContentItemId, out var previousContainedEntry)) { _contentItemIds.Remove(previousContainedEntry.Path); } _contentItemIds[entry.Path] = entry; if (!String.IsNullOrEmpty(entry.ContainedContentItemId)) { _paths[entry.ContainedContentItemId] = entry; } else { _paths[entry.ContentItemId] = entry; } } } } public void RemoveEntries(IEnumerable<AutorouteEntry> entries) { lock (this) { foreach (var entry in entries) { // Evict all entries related to a container item from autoroute entries. var entriesToRemove = _paths.Values.Where(x => x.ContentItemId == entry.ContentItemId && !String.IsNullOrEmpty(x.ContainedContentItemId)); foreach (var entryToRemove in entriesToRemove) { _paths.Remove(entryToRemove.ContainedContentItemId); _contentItemIds.Remove(entryToRemove.Path); } _paths.Remove(entry.ContentItemId); _contentItemIds.Remove(entry.Path); } } } } }
petedavis/Orchard2
src/OrchardCore.Modules/OrchardCore.Autoroute/Services/AutorouteEntries.cs
C#
bsd-3-clause
3,716
require File.join(File.dirname(__FILE__), '../test_helper.rb') class PaymentTest < Test::Unit::TestCase include TestHelper # Tests that a payment can be converted into XML that Xero can understand, and then converted back to a payment def test_build_and_parse_xml payment = create_test_payment # Generate the XML message payment_as_xml = payment.to_xml # Parse the XML message and retrieve the account element payment_element = REXML::XPath.first(REXML::Document.new(payment_as_xml), "/Payment") # Build a new account from the XML result_payment = XeroGateway::Payment.from_xml(payment_element) # Check the details assert_equal payment, result_payment end context "creating test payment" do should "create a test payment" do payment = create_test_payment assert_equal 'a99a9aaa-9999-99a9-9aa9-aaaaaa9a9999', payment.payment_id assert_equal 'ACCRECPAYMENT', payment.payment_type assert_equal Date.today.to_time, payment.date assert payment.updated_at.is_a? Time assert_equal 1000.0, payment.amount assert_equal '12345', payment.reference assert_equal 1.0, payment.currency_rate assert_equal 'i99i9iii-9999-99i9-9ii9-iiiiii9i9999', payment.invoice_id assert_equal 'INV-0001', payment.invoice_number assert_equal 'o99o9ooo-9999-99o9-9oo9-oooooo9o9999', payment.account_id assert payment.reconciled? end end end
armstrjare/xero_gateway
test/unit/payment_test.rb
Ruby
isc
1,445
/// <reference path="../../defs/tsd.d.ts"/> /// <reference path="./interfaces.d.ts"/> var path = require('path'); var fs = require('fs'); var _ = require('lodash'); var utils = require('./utils'); var cache = require('./cacheUtils'); var Promise = require('es6-promise').Promise; exports.grunt = require('grunt'); /////////////////////////// // Helper /////////////////////////// function executeNode(args) { return new Promise(function (resolve, reject) { exports.grunt.util.spawn({ cmd: process.execPath, args: args }, function (error, result, code) { var ret = { code: code, // New TypeScript compiler uses stdout for user code errors. Old one used stderr. output: result.stdout || result.stderr }; resolve(ret); }); }); } ///////////////////////////////////////////////////////////////// // Fast Compilation ///////////////////////////////////////////////////////////////// // Map to store if the cache was cleared after the gruntfile was parsed var cacheClearedOnce = {}; function getChangedFiles(files, targetName) { files = cache.getNewFilesForTarget(files, targetName); _.forEach(files, function (file) { exports.grunt.log.writeln(('### Fast Compile >>' + file).cyan); }); return files; } function resetChangedFiles(files, targetName) { cache.compileSuccessfull(files, targetName); } function clearCache(targetName) { cache.clearCache(targetName); cacheClearedOnce[targetName] = true; } ///////////////////////////////////////////////////////////////////// // tsc handling //////////////////////////////////////////////////////////////////// function resolveTypeScriptBinPath() { var ownRoot = path.resolve(path.dirname((module).filename), '../..'); var userRoot = path.resolve(ownRoot, '..', '..'); var binSub = path.join('node_modules', 'typescript', 'bin'); if (fs.existsSync(path.join(userRoot, binSub))) { // Using project override return path.join(userRoot, binSub); } return path.join(ownRoot, binSub); } function getTsc(binPath) { var pkg = JSON.parse(fs.readFileSync(path.resolve(binPath, '..', 'package.json')).toString()); exports.grunt.log.writeln('Using tsc v' + pkg.version); return path.join(binPath, 'tsc'); } function compileAllFiles(targetFiles, target, task, targetName) { // Make a local copy so we can modify files without having external side effects var files = _.map(targetFiles, function (file) { return file; }); var newFiles = files; if (task.fast === 'watch') { // if this is the first time its running after this file was loaded if (cacheClearedOnce[exports.grunt.task.current.target] === undefined) { // Then clear the cache for this target clearCache(targetName); } } if (task.fast !== 'never') { if (target.out) { exports.grunt.log.writeln('Fast compile will not work when --out is specified. Ignoring fast compilation'.cyan); } else { newFiles = getChangedFiles(files, targetName); if (newFiles.length !== 0) { files = newFiles; // If outDir is specified but no baseDir is specified we need to determine one if (target.outDir && !target.baseDir) { target.baseDir = utils.findCommonPath(files, '/'); } } else { exports.grunt.log.writeln('No file changes were detected. Skipping Compile'.green); return new Promise(function (resolve) { var ret = { code: 0, fileCount: 0, output: 'No files compiled as no change detected' }; resolve(ret); }); } } } // Transform files as needed. Currently all of this logic in is one module // transformers.transformFiles(newFiles, targetFiles, target, task); // If baseDir is specified create a temp tsc file to make sure that `--outDir` works fine // see https://github.com/grunt-ts/grunt-ts/issues/77 var baseDirFile = '.baseDir.ts'; var baseDirFilePath; if (target.outDir && target.baseDir && files.length > 0) { baseDirFilePath = path.join(target.baseDir, baseDirFile); if (!fs.existsSync(baseDirFilePath)) { exports.grunt.file.write(baseDirFilePath, '// Ignore this file. See https://github.com/grunt-ts/grunt-ts/issues/77'); } files.push(baseDirFilePath); } // If reference and out are both specified. // Then only compile the updated reference file as that contains the correct order if (target.reference && target.out) { var referenceFile = path.resolve(target.reference); files = [referenceFile]; } // Quote the files to compile. Needed for command line parsing by tsc files = _.map(files, function (item) { return '"' + path.resolve(item) + '"'; }); var args = files.slice(0); // boolean options if (task.sourceMap) { args.push('--sourcemap'); } if (task.declaration) { args.push('--declaration'); } if (task.removeComments) { args.push('--removeComments'); } if (task.noImplicitAny) { args.push('--noImplicitAny'); } if (task.noResolve) { args.push('--noResolve'); } if (task.noEmitOnError) { args.push('--noEmitOnError'); } if (task.preserveConstEnums) { args.push('--preserveConstEnums'); } if (task.suppressImplicitAnyIndexErrors) { args.push('--suppressImplicitAnyIndexErrors'); } // string options args.push('--target', task.target.toUpperCase()); // check the module compile option if (task.module) { var moduleOptionString = task.module.toLowerCase(); if (moduleOptionString === 'amd' || moduleOptionString === 'commonjs') { args.push('--module', moduleOptionString); } else { console.warn('WARNING: Option "module" does only support "amd" | "commonjs"'.magenta); } } // Target options: if (target.out) { args.push('--out', target.out); } if (target.outDir) { if (target.out) { console.warn('WARNING: Option "out" and "outDir" should not be used together'.magenta); } args.push('--outDir', target.outDir); } if (target.dest && (!target.out) && (!target.outDir)) { if (utils.isJavaScriptFile(target.dest)) { args.push('--out', target.dest); } else { if (target.dest === 'src') { console.warn(('WARNING: Destination for target "' + targetName + '" is "src", which is the default. If you have' + ' forgotten to specify a "dest" parameter, please add it. If this is correct, you may wish' + ' to change the "dest" parameter to "src/" or just ignore this warning.').magenta); } if (Array.isArray(target.dest)) { if (target.dest.length === 0) { } else if (target.dest.length > 0) { console.warn((('WARNING: "dest" for target "' + targetName + '" is an array. This is not supported by the' + ' TypeScript compiler or grunt-ts.' + ((target.dest.length > 1) ? ' Only the first "dest" will be used. The' + ' remaining items will be truncated.' : ''))).magenta); args.push('--outDir', target.dest[0]); } } else { args.push('--outDir', target.dest); } } } if (task.sourceRoot) { args.push('--sourceRoot', task.sourceRoot); } if (task.mapRoot) { args.push('--mapRoot', task.mapRoot); } // Locate a compiler var tsc; if (task.compiler) { exports.grunt.log.writeln('Using the custom compiler : ' + task.compiler); tsc = task.compiler; } else { tsc = getTsc(resolveTypeScriptBinPath()); } // To debug the tsc command if (task.verbose) { console.log(args.join(' ').yellow); } else { exports.grunt.log.verbose.writeln(args.join(' ').yellow); } // Create a temp last command file and use that to guide tsc. // Reason: passing all the files on the command line causes TSC to go in an infinite loop. var tempfilename = utils.getTempFile('tscommand'); if (!tempfilename) { throw (new Error('cannot create temp file')); } fs.writeFileSync(tempfilename, args.join(' ')); // Execute command return executeNode([tsc, '@' + tempfilename]).then(function (result) { if (task.fast !== 'never' && result.code === 0) { resetChangedFiles(newFiles, targetName); } result.fileCount = files.length; fs.unlinkSync(tempfilename); exports.grunt.log.writeln(result.output); return Promise.cast(result); }, function (err) { fs.unlinkSync(tempfilename); throw err; }); } exports.compileAllFiles = compileAllFiles; //# sourceMappingURL=compile.js.map
Softpagehomeware/grunt-ts
tasks/modules/compile.js
JavaScript
mit
9,276
using System; using System.ComponentModel.DataAnnotations; namespace Models.NorthwindIB.NH { [AttributeUsage(AttributeTargets.Class)] // NEW public class CustomerValidator : ValidationAttribute { public override Boolean IsValid(Object value) { var cust = value as Customer; if (cust != null && cust.CompanyName != null && cust.CompanyName.ToLower() == "error") { ErrorMessage = "This customer is not valid!"; return false; } return true; } } [AttributeUsage(AttributeTargets.Property)] public class CustomValidator : ValidationAttribute { public override Boolean IsValid(Object value) { try { var val = (string)value; if (!string.IsNullOrEmpty(val) && val.StartsWith("Error")) { ErrorMessage = "{0} equal the word 'Error'"; return false; } return true; } catch (Exception e) { var x = e; return false; } } } [MetadataType(typeof(CustomerMetaData))] [CustomerValidator] public partial class Customer { } public class CustomerMetaData { [CustomValidator] public string ContactName { get; set; } } }
gilesbradshaw/breeze.server.net
Tests/Model_NorthwindIB_NH/Customer.extended.cs
C#
mit
1,202
require 'spec_helper' feature 'Users' do around do |ex| old_url_options = Rails.application.routes.default_url_options Rails.application.routes.default_url_options = { host: 'example.foo' } ex.run Rails.application.routes.default_url_options = old_url_options end scenario 'GET /users/sign_in creates a new user account' do visit new_user_session_path fill_in 'user_name', with: 'Name Surname' fill_in 'user_username', with: 'Great' fill_in 'user_email', with: 'name@mail.com' fill_in 'user_password_sign_up', with: 'password1234' expect { click_button 'Sign up' }.to change { User.count }.by(1) end scenario 'Successful user signin invalidates password reset token' do user = create(:user) expect(user.reset_password_token).to be_nil visit new_user_password_path fill_in 'user_email', with: user.email click_button 'Reset password' user.reload expect(user.reset_password_token).not_to be_nil login_with(user) expect(current_path).to eq root_path user.reload expect(user.reset_password_token).to be_nil end end
yuyue2013/ss
spec/features/users_spec.rb
Ruby
mit
1,114
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AdminService.Controller { using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.ServiceFabric.Data; using Microsoft.ServiceFabric.Data.Collections; using Microsoft.AspNetCore.Hosting; using Admin; [Route("api/[controller]")] public class KeysController : Controller { private readonly IReliableStateManager stateManager; public KeysController(IReliableStateManager stateManager) { this.stateManager = stateManager; } [HttpGet] [Route("key1")] public async Task<IActionResult> GetKey1Async() { string key = await GetKey(Constants.KEY1); return Ok(key); } [HttpGet] [Route("key2")] public async Task<IActionResult> GetKey2Async() { string key = await GetKey(Constants.KEY2); return Ok(key); } [HttpPost] [Route("key1")] public async Task<IActionResult> RegenerateKey1Async() { string key = await GetKey(Constants.KEY1); return Ok(key); } [HttpPost] [Route("key2")] public async Task<IActionResult> RegenereateKey2Async() { string key = await GetKey(Constants.KEY2); return Ok(key); } private async Task<string> GetKey(string keyName) { var topics = await GetTopicDictionary(); using (var tx = this.stateManager.CreateTransaction()) { var key = await topics.TryGetValueAsync(tx, keyName); if (key.HasValue) { return key.Value; } throw new Exception("No Key initialized."); } } private async Task RegenerateKey(string keyName) { var topics = await GetTopicDictionary(); using (var tx = this.stateManager.CreateTransaction()) { string newKey = GenerateNewKey(); await topics.SetAsync(tx, keyName, newKey); await tx.CommitAsync(); } } private string GenerateNewKey() { // TODO generator a valid security key. using basic placeholder for now // should also encrypt as the key is stored in plain text when stored in // statefule service return Guid.NewGuid().ToString(); } private async Task<IReliableDictionary<string, string>> GetTopicDictionary() { return await this.stateManager.GetOrAddAsync<IReliableDictionary<string, string>>(Constants.COLLECTION_KEYS); } } }
mcollier/ServiceFabricPubSub
src/ServiceFabricPubSub/Admin/Controllers/KeysController.cs
C#
mit
2,935
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Feed_Writer * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @namespace */ namespace Zend\Feed\Writer\Extension\Atom\Renderer; use Zend\Feed\Writer\Extension; /** * @uses \Zend\Feed\Writer\Extension\AbstractRenderer * @category Zend * @package Zend_Feed_Writer * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Feed extends Extension\AbstractRenderer { /** * Set to TRUE if a rendering method actually renders something. This * is used to prevent premature appending of a XML namespace declaration * until an element which requires it is actually appended. * * @var bool */ protected $_called = false; /** * Render feed * * @return void */ public function render() { /** * RSS 2.0 only. Used mainly to include Atom links and * Pubsubhubbub Hub endpoint URIs under the Atom namespace */ if (strtolower($this->getType()) == 'atom') { return; } $this->_setFeedLinks($this->_dom, $this->_base); $this->_setHubs($this->_dom, $this->_base); if ($this->_called) { $this->_appendNamespaces(); } } /** * Append namespaces to root element of feed * * @return void */ protected function _appendNamespaces() { $this->getRootElement()->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom'); } /** * Set feed link elements * * @param DOMDocument $dom * @param DOMElement $root * @return void */ protected function _setFeedLinks(\DOMDocument $dom, \DOMElement $root) { $flinks = $this->getDataContainer()->getFeedLinks(); if(!$flinks || empty($flinks)) { return; } foreach ($flinks as $type => $href) { $mime = 'application/' . strtolower($type) . '+xml'; $flink = $dom->createElement('atom:link'); $root->appendChild($flink); $flink->setAttribute('rel', 'self'); $flink->setAttribute('type', $mime); $flink->setAttribute('href', $href); } $this->_called = true; } /** * Set PuSH hubs * * @param DOMDocument $dom * @param DOMElement $root * @return void */ protected function _setHubs(\DOMDocument $dom, \DOMElement $root) { $hubs = $this->getDataContainer()->getHubs(); if (!$hubs || empty($hubs)) { return; } foreach ($hubs as $hubUrl) { $hub = $dom->createElement('atom:link'); $hub->setAttribute('rel', 'hub'); $hub->setAttribute('href', $hubUrl); $root->appendChild($hub); } $this->_called = true; } }
buzzengine/buzzengine
vendor/zend-framework/library/Zend/Feed/Writer/Extension/Atom/Renderer/Feed.php
PHP
mit
3,543
/******************************************************************************* * Copyright (c) 2015 * * 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. *******************************************************************************/ package jsettlers.algorithms.heap; import java.util.ArrayList; /** * This is a unsynchronized min heap implementation. * <p> * It can heap everything that implements {@link MinHeapable}, but every object that is added to this heap may not be added to an other heap. * * @author andreas * @param <T> */ public class MinHeap<T extends MinHeapable> { private final int MIN_CAPACITY; private final ArrayList<T> heap = new ArrayList<>(); private int size = 0; /** * Creates a new min heap. * * @param capacity * The minimal and initial capacity the heap should have. May not be null. */ public MinHeap(int capacity) { if (capacity <= 0) { throw new IllegalArgumentException("too smal initial capacity"); } MIN_CAPACITY = capacity; heap.ensureCapacity(MIN_CAPACITY); } /** * Adds a new element to the heap. * * @param e * The element to add. */ public void insert(T e) { if (heap.size() > size) { heap.set(size, e); } else { heap.add(e); } siftUp(e, size); size++; } /** * sifts up an element to reestablish the heap array consistency. * * @param e * The element to sift. */ public void siftUp(T e) { siftUp(e, e.getHeapIdx()); } /** * Sifts up an element recursively until the heap consistency is reestablished. * * @param e * The element. * @param eID * The index of the element in the heap. * @return returns if the element was sifted up at least one time */ private boolean siftUp(T e, int eID) { e.setHeapIdx(eID); int parentID = getParent(eID); T parentElement = heap.get(parentID); if (parentElement.getRank() > e.getRank()) { heap.set(parentID, e); heap.set(eID, parentElement); parentElement.setHeapIdx(eID); siftUp(e, parentID); return true; } return false; } /** * Checks whether the heap is empty. * * @return true if and only if the heap is empty. */ public final boolean isEmpty() { return size == 0; } /** * Deletes the element of the heap that has the minimal value. * <p> * If the heap is empty, no action is preformed. * * @return The deleted element, or null. */ public T deleteMin() { if (size <= 0) { return null; } size--; T result = heap.get(0); T last = heap.get(size); heap.set(0, last); siftDown(last, 0); return result; } private void siftDown(T e, int pos) { e.setHeapIdx(pos); int leftChildID = getLeftChildID(pos); if (leftChildID < size) { T leftChild = heap.get(leftChildID); int rightChildID = getRightChildID(pos); T smaller; int smallerID; if (rightChildID < size) { T rightChild = heap.get(rightChildID); if (leftChild.getRank() < rightChild.getRank()) { smaller = leftChild; smallerID = getLeftChildID(pos); } else { smaller = rightChild; smallerID = getRightChildID(pos); } } else { smaller = leftChild; smallerID = getLeftChildID(pos); } if (smaller.getRank() < e.getRank()) { heap.set(pos, smaller); smaller.setHeapIdx(pos); heap.set(smallerID, e); siftDown(e, smallerID); } } } /** * Gets the position of the second child in the array. * * @param pos * The position of the parent. * @return The position of the child. */ private final int getRightChildID(int pos) { return 2 * pos + 2; } /** * Gets the position of the first child in the array. * * @param pos * The position of the parent. * @return The position of the child. */ private final int getLeftChildID(int pos) { return 2 * pos + 1; } /** * Gets the position of the parent in the array. * * @param pos * The position of the child. * @return The position of the parent. */ private final int getParent(int pos) { return (pos - 1) / 2; } @Override public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("\t"); for (int i = 0; i < size; i++) { buffer.append(heap.get(i).getRank() + "\t"); } return buffer.toString(); } /** * Clears the heap, that means that all elements are removed. */ public final void clear() { size = 0; } /** * Gets the number of elements that are in the heap. * * @return The size of the heap. */ public final int size() { return size; } /** * Removes a given element from the heap. * * @param e * The element to remove * @throws java.lang.AssertionError */ public void remove(T e) throws java.lang.AssertionError { // int idx = getIndex(e, 0); int idx = e.getHeapIdx(); // if (idx == -1) // return; assert idx != -1 : "remove wrong element"; size--; T last = heap.get(size); heap.set(idx, last); if (!siftUp(last, idx)) { siftDown(last, idx); } } /** * Checks the heap for consistency. * * @return True if all children "know" their position. */ public boolean doFullHeapCheck() { for (int i = 0; i < size; i++) { if (heap.get(i).getHeapIdx() != i) { return false; } } return checkHeap(0); } /** * Checks the heap from a given position downwards. * * @param pos * The position to start checking. * @return true if and only if the heap is ordered the right way. */ private boolean checkHeap(int pos) { T curr = heap.get(pos); int left = getLeftChildID(pos); int right = getRightChildID(pos); if (left < size) { if (heap.get(left).getRank() < curr.getRank()) { return false; } else { return checkHeap(left); } } if (right < size) { if (heap.get(right).getRank() < curr.getRank()) { return false; } else { return checkHeap(right); } } return true; } }
Peter-Maximilian/settlers-remake
jsettlers.logic/src/main/java/jsettlers/algorithms/heap/MinHeap.java
Java
mit
6,973
/* Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.help.console"]){ dojo._hasResource["dojox.help.console"]=true; dojo.provide("dojox.help.console"); dojo.require("dojox.help._base"); dojo.mixin(dojox.help,{_plainText:function(_1){ return _1.replace(/(<[^>]*>|&[^;]{2,6};)/g,""); },_displayLocated:function(_2){ var _3={}; dojo.forEach(_2,function(_4){ _3[_4[0]]=dojo.isMoz?{toString:function(){ return "Click to view"; },item:_4[1]}:_4[1]; }); },_displayHelp:function(_5,_6){ if(_5){ var _7="Help for: "+_6.name; var _8=""; for(var i=0;i<_7.length;i++){ _8+="="; } }else{ if(!_6){ }else{ var _9=false; for(var _a in _6){ var _b=_6[_a]; if(_a=="returns"&&_6.type!="Function"&&_6.type!="Constructor"){ continue; } if(_b&&(!dojo.isArray(_b)||_b.length)){ _9=true; _b=dojo.isString(_b)?dojox.help._plainText(_b):_b; if(_a=="returns"){ var _c=dojo.map(_b.types||[],"return item.title;").join("|"); if(_b.summary){ if(_c){ _c+=": "; } _c+=dojox.help._plainText(_b.summary); } }else{ if(_a=="parameters"){ for(var j=0,_d;_d=_b[j];j++){ var _e=dojo.map(_d.types,"return item.title").join("|"); var _f=""; if(_d.optional){ _f+="Optional. "; } if(_d.repating){ _f+="Repeating. "; } _f+=dojox.help._plainText(_d.summary); if(_f){ _f=" - "+_f; for(var k=0;k<_d.name.length;k++){ _f=" "+_f; } } } }else{ } } } } if(!_9){ } } } }}); dojox.help.init(); }
bjorns/logger
src/main/webapp/js/dojox/help/console.js
JavaScript
mit
1,517
import * as React from 'react'; import Checkbox from '@material-ui/core/Checkbox'; import FormGroup from '@material-ui/core/FormGroup'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import FormControl from '@material-ui/core/FormControl'; import FormLabel from '@material-ui/core/FormLabel'; export default function FormControlLabelPosition() { return ( <FormControl component="fieldset"> <FormLabel component="legend">Label placement</FormLabel> <FormGroup aria-label="position" row> <FormControlLabel value="top" control={<Checkbox />} label="Top" labelPlacement="top" /> <FormControlLabel value="start" control={<Checkbox />} label="Start" labelPlacement="start" /> <FormControlLabel value="bottom" control={<Checkbox />} label="Bottom" labelPlacement="bottom" /> <FormControlLabel value="end" control={<Checkbox />} label="End" labelPlacement="end" /> </FormGroup> </FormControl> ); }
callemall/material-ui
docs/src/pages/components/checkboxes/FormControlLabelPosition.tsx
TypeScript
mit
1,165
package backup // Copyright (c) Microsoft and contributors. 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "net/http" ) // ProtectionIntentClient is the open API 2.0 Specs for Azure RecoveryServices Backup service type ProtectionIntentClient struct { BaseClient } // NewProtectionIntentClient creates an instance of the ProtectionIntentClient client. func NewProtectionIntentClient(subscriptionID string) ProtectionIntentClient { return NewProtectionIntentClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewProtectionIntentClientWithBaseURI creates an instance of the ProtectionIntentClient client. func NewProtectionIntentClientWithBaseURI(baseURI string, subscriptionID string) ProtectionIntentClient { return ProtectionIntentClient{NewWithBaseURI(baseURI, subscriptionID)} } // CreateOrUpdate create Intent for Enabling backup of an item. This is a synchronous operation. // Parameters: // vaultName - the name of the recovery services vault. // resourceGroupName - the name of the resource group where the recovery services vault is present. // fabricName - fabric name associated with the backup item. // intentObjectName - intent object name. // parameters - resource backed up item func (client ProtectionIntentClient) CreateOrUpdate(ctx context.Context, vaultName string, resourceGroupName string, fabricName string, intentObjectName string, parameters ProtectionIntentResource) (result ProtectionIntentResource, err error) { req, err := client.CreateOrUpdatePreparer(ctx, vaultName, resourceGroupName, fabricName, intentObjectName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "backup.ProtectionIntentClient", "CreateOrUpdate", nil, "Failure preparing request") return } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "backup.ProtectionIntentClient", "CreateOrUpdate", resp, "Failure sending request") return } result, err = client.CreateOrUpdateResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "backup.ProtectionIntentClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client ProtectionIntentClient) CreateOrUpdatePreparer(ctx context.Context, vaultName string, resourceGroupName string, fabricName string, intentObjectName string, parameters ProtectionIntentResource) (*http.Request, error) { pathParameters := map[string]interface{}{ "fabricName": autorest.Encode("path", fabricName), "intentObjectName": autorest.Encode("path", intentObjectName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vaultName": autorest.Encode("path", vaultName), } const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/backupProtectionIntent/{intentObjectName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client ProtectionIntentClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client ProtectionIntentClient) CreateOrUpdateResponder(resp *http.Response) (result ProtectionIntentResource, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Validate sends the validate request. // Parameters: // azureRegion - azure region to hit Api // parameters - enable backup validation request on Virtual Machine func (client ProtectionIntentClient) Validate(ctx context.Context, azureRegion string, parameters PreValidateEnableBackupRequest) (result PreValidateEnableBackupResponse, err error) { req, err := client.ValidatePreparer(ctx, azureRegion, parameters) if err != nil { err = autorest.NewErrorWithError(err, "backup.ProtectionIntentClient", "Validate", nil, "Failure preparing request") return } resp, err := client.ValidateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "backup.ProtectionIntentClient", "Validate", resp, "Failure sending request") return } result, err = client.ValidateResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "backup.ProtectionIntentClient", "Validate", resp, "Failure responding to request") } return } // ValidatePreparer prepares the Validate request. func (client ProtectionIntentClient) ValidatePreparer(ctx context.Context, azureRegion string, parameters PreValidateEnableBackupRequest) (*http.Request, error) { pathParameters := map[string]interface{}{ "azureRegion": autorest.Encode("path", azureRegion), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/Subscriptions/{subscriptionId}/providers/Microsoft.RecoveryServices/locations/{azureRegion}/backupPreValidateProtection", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ValidateSender sends the Validate request. The method will close the // http.Response Body if it receives an error. func (client ProtectionIntentClient) ValidateSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // ValidateResponder handles the response to the Validate request. The method always // closes the http.Response Body. func (client ProtectionIntentClient) ValidateResponder(resp *http.Response) (result PreValidateEnableBackupResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
seuffert/rclone
vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2017-07-01/backup/protectionintent.go
GO
mit
7,908
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 0.1.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ $belongsTo = $this->Bake->aliasExtractor($modelObj, 'BelongsTo'); $belongsToMany = $this->Bake->aliasExtractor($modelObj, 'BelongsToMany'); $compact = ["'" . $singularName . "'"]; ?> /** * Edit method * * @param string|null $id <?= $singularHumanName ?> id. * @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise. * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function edit($id = null) { $<?= $singularName ?> = $this-><?= $currentModelName ?>->get($id, [ 'contain' => [<?= $this->Bake->stringifyList($belongsToMany, ['indent' => false]) ?>] ]); if ($this->request->is(['patch', 'post', 'put'])) { $<?= $singularName ?> = $this-><?= $currentModelName ?>->patchEntity($<?= $singularName ?>, $this->request->getData()); if ($this-><?= $currentModelName; ?>->save($<?= $singularName ?>)) { $this->Flash->success(__('The <?= strtolower($singularHumanName) ?> has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The <?= strtolower($singularHumanName) ?> could not be saved. Please, try again.')); } <?php foreach (array_merge($belongsTo, $belongsToMany) as $assoc): $association = $modelObj->association($assoc); $otherName = $association->getTarget()->getAlias(); $otherPlural = $this->_variableName($otherName); ?> $<?= $otherPlural ?> = $this-><?= $currentModelName ?>-><?= $otherName ?>->find('list', ['limit' => 200]); <?php $compact[] = "'$otherPlural'"; endforeach; ?> $this->set(compact(<?= join(', ', $compact) ?>)); $this->set('_serialize', ['<?=$singularName?>']); }
FlopySwitzerland/nessi
tmp/bake/Bake-Element-Controller-edit-ctp.php
PHP
mit
2,438
version https://git-lfs.github.com/spec/v1 oid sha256:b386bb4d8bf9eb9e8099152a3eb963073051fb960b30cd512b6a07bd1f751d3d size 734
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.2.0/datatype/lang/datatype_it-IT.js
JavaScript
mit
128
class MergeRequestObserver < BaseObserver def after_create(merge_request) notification.new_merge_request(merge_request, current_user) end def after_close(merge_request, transition) Note.create_status_change_note(merge_request, current_user, merge_request.state) notification.close_mr(merge_request, current_user) end def after_merge(merge_request, transition) notification.merge_mr(merge_request) end def after_reopen(merge_request, transition) Note.create_status_change_note(merge_request, current_user, merge_request.state) end def after_update(merge_request) notification.reassigned_merge_request(merge_request, current_user) if merge_request.is_being_reassigned? end end
Aruiwen/gitlabhq
app/observers/merge_request_observer.rb
Ruby
mit
724
using System; using System.Text; using System.Web; using System.Web.Http.Description; namespace TheBigCatProject.Server.Areas.HelpPage { public static class ApiDescriptionExtensions { /// <summary> /// Generates an URI-friendly ID for the <see cref="ApiDescription"/>. E.g. "Get-Values-id_name" instead of "GetValues/{id}?name={name}" /// </summary> /// <param name="description">The <see cref="ApiDescription"/>.</param> /// <returns>The ID as a string.</returns> public static string GetFriendlyId(this ApiDescription description) { string path = description.RelativePath; string[] urlParts = path.Split('?'); string localPath = urlParts[0]; string queryKeyString = null; if (urlParts.Length > 1) { string query = urlParts[1]; string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys; queryKeyString = String.Join("_", queryKeys); } StringBuilder friendlyPath = new StringBuilder(); friendlyPath.AppendFormat("{0}-{1}", description.HttpMethod.Method, localPath.Replace("/", "-").Replace("{", String.Empty).Replace("}", String.Empty)); if (queryKeyString != null) { friendlyPath.AppendFormat("_{0}", queryKeyString.Replace('.', '-')); } return friendlyPath.ToString(); } } }
EmilMitev/Telerik-Academy
Single Page Applications/07. AngularJS Workshop/TheBigCatProject/TheBigCatProject.Server/Areas/HelpPage/ApiDescriptionExtensions.cs
C#
mit
1,513
package com.xeiam.xchange.taurus.dto; import si.mazi.rescu.HttpStatusExceptionSupport; import com.fasterxml.jackson.annotation.JsonProperty; public class TaurusException extends HttpStatusExceptionSupport { public TaurusException(@JsonProperty("error") Object error) { super(error.toString()); } }
cinjoff/XChange-1
xchange-taurus/src/main/java/com/xeiam/xchange/taurus/dto/TaurusException.java
Java
mit
309
using System; using System.Threading; using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Orleans.Configuration; namespace Orleans.Transactions { internal class ActiveTransactionsTracker : IDisposable { private readonly TransactionsOptions options; private readonly TransactionLog transactionLog; private readonly ILogger logger; private readonly object lockObj; private readonly Thread allocationThread; private readonly AutoResetEvent allocationEvent; private long smallestActiveTransactionId; private long highestActiveTransactionId; private long maxAllocatedTransactionId; private volatile bool disposed; public ActiveTransactionsTracker(IOptions<TransactionsOptions> configOption, TransactionLog transactionLog, ILoggerFactory loggerFactory) { this.options = configOption.Value; this.transactionLog = transactionLog; this.logger = loggerFactory.CreateLogger(nameof(ActiveTransactionsTracker)); lockObj = new object(); allocationEvent = new AutoResetEvent(true); allocationThread = new Thread(AllocateTransactionId) { IsBackground = true, Name = nameof(ActiveTransactionsTracker) }; } public void Start(long initialTransactionId) { smallestActiveTransactionId = initialTransactionId + 1; highestActiveTransactionId = initialTransactionId; maxAllocatedTransactionId = initialTransactionId; allocationThread.Start(); } public long GetNewTransactionId() { var id = Interlocked.Increment(ref highestActiveTransactionId); if (maxAllocatedTransactionId - highestActiveTransactionId <= options.AvailableTransactionIdThreshold) { // Signal the allocation thread to allocate more Ids allocationEvent.Set(); } while (id > maxAllocatedTransactionId) { // Wait until the allocation thread catches up before returning. // This should never happen if we are pre-allocating fast enough. allocationEvent.Set(); lock (lockObj) { } } return id; } public long GetSmallestActiveTransactionId() { // NOTE: this result is not strictly correct if there are NO active transactions // but for all purposes in which this is used it is still valid. // TODO: consider renaming this or handling the no active transactions case. return Interlocked.Read(ref smallestActiveTransactionId); } public long GetHighestActiveTransactionId() { // NOTE: this result is not strictly correct if there are NO active transactions // but for all purposes in which this is used it is still valid. // TODO: consider renaming this or handling the no active transactions case. lock (lockObj) { return Math.Min(highestActiveTransactionId, maxAllocatedTransactionId); } } public void PopSmallestActiveTransactionId() { Interlocked.Increment(ref smallestActiveTransactionId); } private void AllocateTransactionId(object args) { while (!this.disposed) { try { allocationEvent.WaitOne(); if (this.disposed) return; lock (lockObj) { if (maxAllocatedTransactionId - highestActiveTransactionId <= options.AvailableTransactionIdThreshold) { var batchSize = options.TransactionIdAllocationBatchSize; transactionLog.UpdateStartRecord(maxAllocatedTransactionId + batchSize).GetAwaiter().GetResult(); maxAllocatedTransactionId += batchSize; } } } catch (ThreadAbortException) { throw; } catch (Exception exception) { this.logger.Warn( OrleansTransactionsErrorCode.Transactions_IdAllocationFailed, "Ignoring exception in " + nameof(this.AllocateTransactionId), exception); } } } public void Dispose() { if (!this.disposed) { this.disposed = true; this.allocationEvent.Set(); this.allocationEvent.Dispose(); } } } }
ashkan-saeedi-mazdeh/orleans
src/Orleans.Transactions/InClusterTM/ActiveTransactionsTracker.cs
C#
mit
4,965
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "pal_config.h" #include "pal_uid.h" #include "pal_utilities.h" #include <assert.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <pwd.h> extern "C" int32_t SystemNative_GetPwUidR(uint32_t uid, Passwd* pwd, char* buf, int32_t buflen) { assert(pwd != nullptr); assert(buf != nullptr); assert(buflen >= 0); if (buflen < 0) return EINVAL; struct passwd nativePwd; struct passwd* result; int error; while ((error = getpwuid_r(uid, &nativePwd, buf, UnsignedCast(buflen), &result)) == EINTR); // positive error number returned -> failure other than entry-not-found if (error != 0) { assert(error > 0); *pwd = {}; // managed out param must be initialized return error; } // 0 returned with null result -> entry-not-found if (result == nullptr) { *pwd = {}; // managed out param must be initialized return -1; // shim convention for entry-not-found } // 0 returned with non-null result (guaranteed to be set to pwd arg) -> success assert(result == &nativePwd); pwd->Name = nativePwd.pw_name; pwd->Password = nativePwd.pw_passwd; pwd->UserId = nativePwd.pw_uid; pwd->GroupId = nativePwd.pw_gid; pwd->UserInfo = nativePwd.pw_gecos; pwd->HomeDirectory = nativePwd.pw_dir; pwd->Shell = nativePwd.pw_shell; return 0; } extern "C" uint32_t SystemNative_GetEUid() { return geteuid(); } extern "C" uint32_t SystemNative_GetEGid() { return getegid(); }
shmao/corefx
src/Native/Unix/System.Native/pal_uid.cpp
C++
mit
1,762
using System.Reflection; [assembly: AssemblyTitle("Cedar.EventStore.Tests")] [assembly: AssemblyDescription("")]
dcomartin/Cedar.EventStore
src/Cedar.EventStore.Tests/Properties/AssemblyInfo.cs
C#
mit
113
// +build linux package libcontainer import ( "fmt" "io" "io/ioutil" "os" "os/exec" "path" "path/filepath" "strings" "syscall" "time" "github.com/docker/docker/pkg/mount" "github.com/docker/docker/pkg/symlink" "github.com/opencontainers/runc/libcontainer/cgroups" "github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/label" "github.com/opencontainers/runc/libcontainer/system" libcontainerUtils "github.com/opencontainers/runc/libcontainer/utils" ) const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV // needsSetupDev returns true if /dev needs to be set up. func needsSetupDev(config *configs.Config) bool { for _, m := range config.Mounts { if m.Device == "bind" && (m.Destination == "/dev" || m.Destination == "/dev/") { return false } } return true } // setupRootfs sets up the devices, mount points, and filesystems for use inside a // new mount namespace. func setupRootfs(config *configs.Config, console *linuxConsole, pipe io.ReadWriter) (err error) { if err := prepareRoot(config); err != nil { return newSystemError(err) } setupDev := needsSetupDev(config) for _, m := range config.Mounts { for _, precmd := range m.PremountCmds { if err := mountCmd(precmd); err != nil { return newSystemError(err) } } if err := mountToRootfs(m, config.Rootfs, config.MountLabel); err != nil { return newSystemError(err) } for _, postcmd := range m.PostmountCmds { if err := mountCmd(postcmd); err != nil { return newSystemError(err) } } } if setupDev { if err := createDevices(config); err != nil { return newSystemError(err) } if err := setupPtmx(config, console); err != nil { return newSystemError(err) } if err := setupDevSymlinks(config.Rootfs); err != nil { return newSystemError(err) } } // Signal the parent to run the pre-start hooks. // The hooks are run after the mounts are setup, but before we switch to the new // root, so that the old root is still available in the hooks for any mount // manipulations. if err := syncParentHooks(pipe); err != nil { return err } if err := syscall.Chdir(config.Rootfs); err != nil { return newSystemError(err) } if config.NoPivotRoot { err = msMoveRoot(config.Rootfs) } else { err = pivotRoot(config.Rootfs, config.PivotDir) } if err != nil { return newSystemError(err) } if setupDev { if err := reOpenDevNull(); err != nil { return newSystemError(err) } } // remount dev as ro if specifed for _, m := range config.Mounts { if m.Destination == "/dev" { if m.Flags&syscall.MS_RDONLY != 0 { if err := remountReadonly(m.Destination); err != nil { return newSystemError(err) } } break } } // set rootfs ( / ) as readonly if config.Readonlyfs { if err := setReadonly(); err != nil { return newSystemError(err) } } syscall.Umask(0022) return nil } func mountCmd(cmd configs.Command) error { command := exec.Command(cmd.Path, cmd.Args[:]...) command.Env = cmd.Env command.Dir = cmd.Dir if out, err := command.CombinedOutput(); err != nil { return fmt.Errorf("%#v failed: %s: %v", cmd, string(out), err) } return nil } func mountToRootfs(m *configs.Mount, rootfs, mountLabel string) error { var ( dest = m.Destination ) if !strings.HasPrefix(dest, rootfs) { dest = filepath.Join(rootfs, dest) } switch m.Device { case "proc", "sysfs": if err := os.MkdirAll(dest, 0755); err != nil { return err } // Selinux kernels do not support labeling of /proc or /sys return mountPropagate(m, rootfs, "") case "mqueue": if err := os.MkdirAll(dest, 0755); err != nil { return err } if err := mountPropagate(m, rootfs, mountLabel); err != nil { // older kernels do not support labeling of /dev/mqueue if err := mountPropagate(m, rootfs, ""); err != nil { return err } return label.SetFileLabel(dest, mountLabel) } return nil case "tmpfs": stat, err := os.Stat(dest) if err != nil { if err := os.MkdirAll(dest, 0755); err != nil { return err } } if err := mountPropagate(m, rootfs, mountLabel); err != nil { return err } if stat != nil { if err = os.Chmod(dest, stat.Mode()); err != nil { return err } } return nil case "bind": stat, err := os.Stat(m.Source) if err != nil { // error out if the source of a bind mount does not exist as we will be // unable to bind anything to it. return err } // ensure that the destination of the bind mount is resolved of symlinks at mount time because // any previous mounts can invalidate the next mount's destination. // this can happen when a user specifies mounts within other mounts to cause breakouts or other // evil stuff to try to escape the container's rootfs. if dest, err = symlink.FollowSymlinkInScope(filepath.Join(rootfs, m.Destination), rootfs); err != nil { return err } if err := checkMountDestination(rootfs, dest); err != nil { return err } // update the mount with the correct dest after symlinks are resolved. m.Destination = dest if err := createIfNotExists(dest, stat.IsDir()); err != nil { return err } if err := mountPropagate(m, rootfs, mountLabel); err != nil { return err } // bind mount won't change mount options, we need remount to make mount options effective. // first check that we have non-default options required before attempting a remount if m.Flags&^(syscall.MS_REC|syscall.MS_REMOUNT|syscall.MS_BIND) != 0 { // only remount if unique mount options are set if err := remount(m, rootfs); err != nil { return err } } if m.Relabel != "" { if err := label.Validate(m.Relabel); err != nil { return err } shared := label.IsShared(m.Relabel) if err := label.Relabel(m.Source, mountLabel, shared); err != nil { return err } } case "cgroup": binds, err := getCgroupMounts(m) if err != nil { return err } var merged []string for _, b := range binds { ss := filepath.Base(b.Destination) if strings.Contains(ss, ",") { merged = append(merged, ss) } } tmpfs := &configs.Mount{ Source: "tmpfs", Device: "tmpfs", Destination: m.Destination, Flags: defaultMountFlags, Data: "mode=755", PropagationFlags: m.PropagationFlags, } if err := mountToRootfs(tmpfs, rootfs, mountLabel); err != nil { return err } for _, b := range binds { if err := mountToRootfs(b, rootfs, mountLabel); err != nil { return err } } // create symlinks for merged cgroups cwd, err := os.Getwd() if err != nil { return err } if err := os.Chdir(filepath.Join(rootfs, m.Destination)); err != nil { return err } for _, mc := range merged { for _, ss := range strings.Split(mc, ",") { if err := os.Symlink(mc, ss); err != nil { // if cgroup already exists, then okay(it could have been created before) if os.IsExist(err) { continue } os.Chdir(cwd) return err } } } if err := os.Chdir(cwd); err != nil { return err } if m.Flags&syscall.MS_RDONLY != 0 { // remount cgroup root as readonly mcgrouproot := &configs.Mount{ Destination: m.Destination, Flags: defaultMountFlags | syscall.MS_RDONLY, } if err := remount(mcgrouproot, rootfs); err != nil { return err } } default: if err := os.MkdirAll(dest, 0755); err != nil { return err } return mountPropagate(m, rootfs, mountLabel) } return nil } func getCgroupMounts(m *configs.Mount) ([]*configs.Mount, error) { mounts, err := cgroups.GetCgroupMounts() if err != nil { return nil, err } cgroupPaths, err := cgroups.ParseCgroupFile("/proc/self/cgroup") if err != nil { return nil, err } var binds []*configs.Mount for _, mm := range mounts { dir, err := mm.GetThisCgroupDir(cgroupPaths) if err != nil { return nil, err } relDir, err := filepath.Rel(mm.Root, dir) if err != nil { return nil, err } binds = append(binds, &configs.Mount{ Device: "bind", Source: filepath.Join(mm.Mountpoint, relDir), Destination: filepath.Join(m.Destination, strings.Join(mm.Subsystems, ",")), Flags: syscall.MS_BIND | syscall.MS_REC | m.Flags, PropagationFlags: m.PropagationFlags, }) } return binds, nil } // checkMountDestination checks to ensure that the mount destination is not over the top of /proc. // dest is required to be an abs path and have any symlinks resolved before calling this function. func checkMountDestination(rootfs, dest string) error { if libcontainerUtils.CleanPath(rootfs) == libcontainerUtils.CleanPath(dest) { return fmt.Errorf("mounting into / is prohibited") } invalidDestinations := []string{ "/proc", } // White list, it should be sub directories of invalid destinations validDestinations := []string{ // These entries can be bind mounted by files emulated by fuse, // so commands like top, free displays stats in container. "/proc/cpuinfo", "/proc/diskstats", "/proc/meminfo", "/proc/stat", "/proc/net/dev", } for _, valid := range validDestinations { path, err := filepath.Rel(filepath.Join(rootfs, valid), dest) if err != nil { return err } if path == "." { return nil } } for _, invalid := range invalidDestinations { path, err := filepath.Rel(filepath.Join(rootfs, invalid), dest) if err != nil { return err } if path == "." || !strings.HasPrefix(path, "..") { return fmt.Errorf("%q cannot be mounted because it is located inside %q", dest, invalid) } } return nil } func setupDevSymlinks(rootfs string) error { var links = [][2]string{ {"/proc/self/fd", "/dev/fd"}, {"/proc/self/fd/0", "/dev/stdin"}, {"/proc/self/fd/1", "/dev/stdout"}, {"/proc/self/fd/2", "/dev/stderr"}, } // kcore support can be toggled with CONFIG_PROC_KCORE; only create a symlink // in /dev if it exists in /proc. if _, err := os.Stat("/proc/kcore"); err == nil { links = append(links, [2]string{"/proc/kcore", "/dev/core"}) } for _, link := range links { var ( src = link[0] dst = filepath.Join(rootfs, link[1]) ) if err := os.Symlink(src, dst); err != nil && !os.IsExist(err) { return fmt.Errorf("symlink %s %s %s", src, dst, err) } } return nil } // If stdin, stdout, and/or stderr are pointing to `/dev/null` in the parent's rootfs // this method will make them point to `/dev/null` in this container's rootfs. This // needs to be called after we chroot/pivot into the container's rootfs so that any // symlinks are resolved locally. func reOpenDevNull() error { var stat, devNullStat syscall.Stat_t file, err := os.OpenFile("/dev/null", os.O_RDWR, 0) if err != nil { return fmt.Errorf("Failed to open /dev/null - %s", err) } defer file.Close() if err := syscall.Fstat(int(file.Fd()), &devNullStat); err != nil { return err } for fd := 0; fd < 3; fd++ { if err := syscall.Fstat(fd, &stat); err != nil { return err } if stat.Rdev == devNullStat.Rdev { // Close and re-open the fd. if err := syscall.Dup3(int(file.Fd()), fd, 0); err != nil { return err } } } return nil } // Create the device nodes in the container. func createDevices(config *configs.Config) error { useBindMount := system.RunningInUserNS() || config.Namespaces.Contains(configs.NEWUSER) oldMask := syscall.Umask(0000) for _, node := range config.Devices { // containers running in a user namespace are not allowed to mknod // devices so we can just bind mount it from the host. if err := createDeviceNode(config.Rootfs, node, useBindMount); err != nil { syscall.Umask(oldMask) return err } } syscall.Umask(oldMask) return nil } func bindMountDeviceNode(dest string, node *configs.Device) error { f, err := os.Create(dest) if err != nil && !os.IsExist(err) { return err } if f != nil { f.Close() } return syscall.Mount(node.Path, dest, "bind", syscall.MS_BIND, "") } // Creates the device node in the rootfs of the container. func createDeviceNode(rootfs string, node *configs.Device, bind bool) error { dest := filepath.Join(rootfs, node.Path) if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil { return err } if bind { return bindMountDeviceNode(dest, node) } if err := mknodDevice(dest, node); err != nil { if os.IsExist(err) { return nil } else if os.IsPermission(err) { return bindMountDeviceNode(dest, node) } return err } return nil } func mknodDevice(dest string, node *configs.Device) error { fileMode := node.FileMode switch node.Type { case 'c': fileMode |= syscall.S_IFCHR case 'b': fileMode |= syscall.S_IFBLK default: return fmt.Errorf("%c is not a valid device type for device %s", node.Type, node.Path) } if err := syscall.Mknod(dest, uint32(fileMode), node.Mkdev()); err != nil { return err } return syscall.Chown(dest, int(node.Uid), int(node.Gid)) } func getMountInfo(mountinfo []*mount.Info, dir string) *mount.Info { for _, m := range mountinfo { if m.Mountpoint == dir { return m } } return nil } // Get the parent mount point of directory passed in as argument. Also return // optional fields. func getParentMount(rootfs string) (string, string, error) { var path string mountinfos, err := mount.GetMounts() if err != nil { return "", "", err } mountinfo := getMountInfo(mountinfos, rootfs) if mountinfo != nil { return rootfs, mountinfo.Optional, nil } path = rootfs for { path = filepath.Dir(path) mountinfo = getMountInfo(mountinfos, path) if mountinfo != nil { return path, mountinfo.Optional, nil } if path == "/" { break } } // If we are here, we did not find parent mount. Something is wrong. return "", "", fmt.Errorf("Could not find parent mount of %s", rootfs) } // Make parent mount private if it was shared func rootfsParentMountPrivate(config *configs.Config) error { sharedMount := false parentMount, optionalOpts, err := getParentMount(config.Rootfs) if err != nil { return err } optsSplit := strings.Split(optionalOpts, " ") for _, opt := range optsSplit { if strings.HasPrefix(opt, "shared:") { sharedMount = true break } } // Make parent mount PRIVATE if it was shared. It is needed for two // reasons. First of all pivot_root() will fail if parent mount is // shared. Secondly when we bind mount rootfs it will propagate to // parent namespace and we don't want that to happen. if sharedMount { return syscall.Mount("", parentMount, "", syscall.MS_PRIVATE, "") } return nil } func prepareRoot(config *configs.Config) error { flag := syscall.MS_SLAVE | syscall.MS_REC if config.RootPropagation != 0 { flag = config.RootPropagation } if err := syscall.Mount("", "/", "", uintptr(flag), ""); err != nil { return err } if err := rootfsParentMountPrivate(config); err != nil { return err } return syscall.Mount(config.Rootfs, config.Rootfs, "bind", syscall.MS_BIND|syscall.MS_REC, "") } func setReadonly() error { return syscall.Mount("/", "/", "bind", syscall.MS_BIND|syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_REC, "") } func setupPtmx(config *configs.Config, console *linuxConsole) error { ptmx := filepath.Join(config.Rootfs, "dev/ptmx") if err := os.Remove(ptmx); err != nil && !os.IsNotExist(err) { return err } if err := os.Symlink("pts/ptmx", ptmx); err != nil { return fmt.Errorf("symlink dev ptmx %s", err) } if console != nil { return console.mount(config.Rootfs, config.MountLabel) } return nil } func pivotRoot(rootfs, pivotBaseDir string) (err error) { if pivotBaseDir == "" { pivotBaseDir = "/" } tmpDir := filepath.Join(rootfs, pivotBaseDir) if err := os.MkdirAll(tmpDir, 0755); err != nil { return fmt.Errorf("can't create tmp dir %s, error %v", tmpDir, err) } pivotDir, err := ioutil.TempDir(tmpDir, ".pivot_root") if err != nil { return fmt.Errorf("can't create pivot_root dir %s, error %v", pivotDir, err) } defer func() { errVal := os.Remove(pivotDir) if err == nil { err = errVal } }() if err := syscall.PivotRoot(rootfs, pivotDir); err != nil { return fmt.Errorf("pivot_root %s", err) } if err := syscall.Chdir("/"); err != nil { return fmt.Errorf("chdir / %s", err) } // path to pivot dir now changed, update pivotDir = filepath.Join(pivotBaseDir, filepath.Base(pivotDir)) // Make pivotDir rprivate to make sure any of the unmounts don't // propagate to parent. if err := syscall.Mount("", pivotDir, "", syscall.MS_PRIVATE|syscall.MS_REC, ""); err != nil { return err } if err := syscall.Unmount(pivotDir, syscall.MNT_DETACH); err != nil { return fmt.Errorf("unmount pivot_root dir %s", err) } return nil } func msMoveRoot(rootfs string) error { if err := syscall.Mount(rootfs, "/", "", syscall.MS_MOVE, ""); err != nil { return err } if err := syscall.Chroot("."); err != nil { return err } return syscall.Chdir("/") } // createIfNotExists creates a file or a directory only if it does not already exist. func createIfNotExists(path string, isDir bool) error { if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { if isDir { return os.MkdirAll(path, 0755) } if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { return err } f, err := os.OpenFile(path, os.O_CREATE, 0755) if err != nil { return err } f.Close() } } return nil } // remountReadonly will bind over the top of an existing path and ensure that it is read-only. func remountReadonly(path string) error { for i := 0; i < 5; i++ { if err := syscall.Mount("", path, "", syscall.MS_REMOUNT|syscall.MS_RDONLY, ""); err != nil && !os.IsNotExist(err) { switch err { case syscall.EINVAL: // Probably not a mountpoint, use bind-mount if err := syscall.Mount(path, path, "", syscall.MS_BIND, ""); err != nil { return err } return syscall.Mount(path, path, "", syscall.MS_BIND|syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_REC|defaultMountFlags, "") case syscall.EBUSY: time.Sleep(100 * time.Millisecond) continue default: return err } } return nil } return fmt.Errorf("unable to mount %s as readonly max retries reached", path) } // maskFile bind mounts /dev/null over the top of the specified path inside a container // to avoid security issues from processes reading information from non-namespace aware mounts ( proc/kcore ). func maskFile(path string) error { if err := syscall.Mount("/dev/null", path, "", syscall.MS_BIND, ""); err != nil && !os.IsNotExist(err) { return err } return nil } // writeSystemProperty writes the value to a path under /proc/sys as determined from the key. // For e.g. net.ipv4.ip_forward translated to /proc/sys/net/ipv4/ip_forward. func writeSystemProperty(key, value string) error { keyPath := strings.Replace(key, ".", "/", -1) return ioutil.WriteFile(path.Join("/proc/sys", keyPath), []byte(value), 0644) } func remount(m *configs.Mount, rootfs string) error { var ( dest = m.Destination ) if !strings.HasPrefix(dest, rootfs) { dest = filepath.Join(rootfs, dest) } if err := syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags|syscall.MS_REMOUNT), ""); err != nil { return err } return nil } // Do the mount operation followed by additional mounts required to take care // of propagation flags. func mountPropagate(m *configs.Mount, rootfs string, mountLabel string) error { var ( dest = m.Destination data = label.FormatMountLabel(m.Data, mountLabel) flags = m.Flags ) if dest == "/dev" { flags &= ^syscall.MS_RDONLY } if !strings.HasPrefix(dest, rootfs) { dest = filepath.Join(rootfs, dest) } if err := syscall.Mount(m.Source, dest, m.Device, uintptr(flags), data); err != nil { return err } for _, pflag := range m.PropagationFlags { if err := syscall.Mount("", dest, "", uintptr(pflag), ""); err != nil { return err } } return nil }
thaJeztah/binctr
vendor/github.com/opencontainers/runc/libcontainer/rootfs_linux.go
GO
mit
19,935
<?php namespace Lexik\Bundle\JWTAuthenticationBundle; /** * Events. * * @author Dev Lexik <dev@lexik.fr> */ final class Events { /** * Dispatched after the token generation to allow sending more data * on the authentication success response. */ const AUTHENTICATION_SUCCESS = 'lexik_jwt_authentication.on_authentication_success'; /** * Dispatched after an authentication failure. * Hook into this event to add a custom error message in the response body. */ const AUTHENTICATION_FAILURE = 'lexik_jwt_authentication.on_authentication_failure'; /** * Dispatched before the token payload is encoded by the configured encoder (JWTEncoder by default). * Hook into this event to add extra fields to the payload. */ const JWT_CREATED = 'lexik_jwt_authentication.on_jwt_created'; /** * Dispatched right after token string is created. * Hook into this event to get token representation itself. */ const JWT_ENCODED = 'lexik_jwt_authentication.on_jwt_encoded'; /** * Dispatched after the token payload has been decoded by the configured encoder (JWTEncoder by default). * Hook into this event to perform additional validation on the received payload. */ const JWT_DECODED = 'lexik_jwt_authentication.on_jwt_decoded'; /** * Dispatched after the token payload has been authenticated by the provider. * Hook into this event to perform additional modification to the authenticated token using the payload. */ const JWT_AUTHENTICATED = 'lexik_jwt_authentication.on_jwt_authenticated'; /** * Dispatched after the token has been invalidated by the provider. * Hook into this event to add a custom error message in the response body. */ const JWT_INVALID = 'lexik_jwt_authentication.on_jwt_invalid'; /** * Dispatched when no token can be found in a request. * Hook into this event to set a custom response. */ const JWT_NOT_FOUND = 'lexik_jwt_authentication.on_jwt_not_found'; /** * Dispatched when the token is expired. * The expired token's payload can be retrieved by hooking into this event, so you can set a different * response. */ const JWT_EXPIRED = 'lexik_jwt_authentication.on_jwt_expired'; }
DevKhater/symfony2-testing
vendor/lexik/jwt-authentication-bundle/Events.php
PHP
mit
2,311
<?php global $_MODULE; $_MODULE = array(); $_MODULE['<{gridhtml}prestashop>gridhtml_cf6b972204ee563b4e5691b293e931b6'] = 'Visualització simple taula HTML'; $_MODULE['<{gridhtml}prestashop>gridhtml_05ce5a49b49dd6245f71e384c4b43564'] = 'Permet que el sistema d\'estadístiques mostri les dades en una quadrícula.'; return $_MODULE;
insbadia-dawm8/gitteam
proyecto/modules/gridhtml/translations/ca.php
PHP
mit
336
var fs = require('fs') var path = require('path') var util = require('util') var semver = require('semver') exports.checkEngine = checkEngine function checkEngine (target, npmVer, nodeVer, force, strict, cb) { var nodev = force ? null : nodeVer var eng = target.engines var opt = { includePrerelease: true } if (!eng) return cb() if (nodev && eng.node && !semver.satisfies(nodev, eng.node, opt) || eng.npm && !semver.satisfies(npmVer, eng.npm, opt)) { var er = new Error(util.format('Unsupported engine for %s: wanted: %j (current: %j)', target._id, eng, {node: nodev, npm: npmVer})) er.code = 'ENOTSUP' er.required = eng er.pkgid = target._id if (strict) { return cb(er) } else { return cb(null, er) } } return cb() } exports.checkPlatform = checkPlatform function checkPlatform (target, force, cb) { var platform = process.platform var arch = process.arch var osOk = true var cpuOk = true if (force) { return cb() } if (target.os) { osOk = checkList(platform, target.os) } if (target.cpu) { cpuOk = checkList(arch, target.cpu) } if (!osOk || !cpuOk) { var er = new Error(util.format('Unsupported platform for %s: wanted %j (current: %j)', target._id, target, {os: platform, cpu: arch})) er.code = 'EBADPLATFORM' er.os = target.os || ['any'] er.cpu = target.cpu || ['any'] er.pkgid = target._id return cb(er) } return cb() } function checkList (value, list) { var tmp var match = false var blc = 0 if (typeof list === 'string') { list = [list] } if (list.length === 1 && list[0] === 'any') { return true } for (var i = 0; i < list.length; ++i) { tmp = list[i] if (tmp[0] === '!') { tmp = tmp.slice(1) if (tmp === value) { return false } ++blc } else { match = match || tmp === value } } return match || blc === list.length } exports.checkCycle = checkCycle function checkCycle (target, ancestors, cb) { // there are some very rare and pathological edge-cases where // a cycle can cause npm to try to install a never-ending tree // of stuff. // Simplest: // // A -> B -> A' -> B' -> A -> B -> A' -> B' -> A -> ... // // Solution: Simply flat-out refuse to install any name@version // that is already in the prototype tree of the ancestors object. // A more correct, but more complex, solution would be to symlink // the deeper thing into the new location. // Will do that if anyone whines about this irl. // // Note: `npm install foo` inside of the `foo` package will abort // earlier if `--force` is not set. However, if it IS set, then // we need to still fail here, but just skip the first level. Of // course, it'll still fail eventually if it's a true cycle, and // leave things in an undefined state, but that's what is to be // expected when `--force` is used. That is why getPrototypeOf // is used *twice* here: to skip the first level of repetition. var p = Object.getPrototypeOf(Object.getPrototypeOf(ancestors)) var name = target.name var version = target.version while (p && p !== Object.prototype && p[name] !== version) { p = Object.getPrototypeOf(p) } if (p[name] !== version) return cb() var er = new Error(target._id + ': Unresolvable cycle detected') var tree = [target._id, JSON.parse(JSON.stringify(ancestors))] var t = Object.getPrototypeOf(ancestors) while (t && t !== Object.prototype) { if (t === p) t.THIS_IS_P = true tree.push(JSON.parse(JSON.stringify(t))) t = Object.getPrototypeOf(t) } er.pkgid = target._id er.code = 'ECYCLE' return cb(er) } exports.checkGit = checkGit function checkGit (folder, cb) { // if it's a git repo then don't touch it! fs.lstat(folder, function (er, s) { if (er || !s.isDirectory()) return cb() else checkGit_(folder, cb) }) } function checkGit_ (folder, cb) { fs.stat(path.resolve(folder, '.git'), function (er, s) { if (!er && s.isDirectory()) { var e = new Error(folder + ': Appears to be a git repo or submodule.') e.path = folder e.code = 'EISGIT' return cb(e) } cb() }) }
giovannic/giovannic.github.com
node_modules/npm/node_modules/npm-install-checks/index.js
JavaScript
mit
4,201
package main import ( "fmt" "time" "github.com/google/jsonapi" ) // Blog is a model representing a blog site type Blog struct { ID int `jsonapi:"primary,blogs"` Title string `jsonapi:"attr,title"` Posts []*Post `jsonapi:"relation,posts"` CurrentPost *Post `jsonapi:"relation,current_post"` CurrentPostID int `jsonapi:"attr,current_post_id"` CreatedAt time.Time `jsonapi:"attr,created_at"` ViewCount int `jsonapi:"attr,view_count"` } // Post is a model representing a post on a blog type Post struct { ID int `jsonapi:"primary,posts"` BlogID int `jsonapi:"attr,blog_id"` Title string `jsonapi:"attr,title"` Body string `jsonapi:"attr,body"` Comments []*Comment `jsonapi:"relation,comments"` } // Comment is a model representing a user submitted comment type Comment struct { ID int `jsonapi:"primary,comments"` PostID int `jsonapi:"attr,post_id"` Body string `jsonapi:"attr,body"` } // JSONAPILinks implements the Linkable interface for a blog func (blog Blog) JSONAPILinks() *jsonapi.Links { return &jsonapi.Links{ "self": fmt.Sprintf("https://example.com/blogs/%d", blog.ID), } } // JSONAPIRelationshipLinks implements the RelationshipLinkable interface for a blog func (blog Blog) JSONAPIRelationshipLinks(relation string) *jsonapi.Links { if relation == "posts" { return &jsonapi.Links{ "related": fmt.Sprintf("https://example.com/blogs/%d/posts", blog.ID), } } if relation == "current_post" { return &jsonapi.Links{ "related": fmt.Sprintf("https://example.com/blogs/%d/current_post", blog.ID), } } return nil } // JSONAPIMeta implements the Metable interface for a blog func (blog Blog) JSONAPIMeta() *jsonapi.Meta { return &jsonapi.Meta{ "detail": "extra details regarding the blog", } } // JSONAPIRelationshipMeta implements the RelationshipMetable interface for a blog func (blog Blog) JSONAPIRelationshipMeta(relation string) *jsonapi.Meta { if relation == "posts" { return &jsonapi.Meta{ "detail": "posts meta information", } } if relation == "current_post" { return &jsonapi.Meta{ "detail": "current post meta information", } } return nil }
aren55555/jsonapi
examples/models.go
GO
mit
2,237
require File.expand_path('../../../enumerable/shared/enumeratorized', __FILE__) describe :keep_if, :shared => true do it "deletes elements for which the block returns a false value" do array = [1, 2, 3, 4, 5] array.send(@method) {|item| item > 3 }.should equal(array) array.should == [4, 5] end it "returns an enumerator if no block is given" do [1, 2, 3].send(@method).should be_an_instance_of(enumerator_class) end before :all do @object = [1,2,3] end it_should_behave_like :enumeratorized_with_origin_size describe "on frozen objects" do before :each do @origin = [true, false] @frozen = @origin.dup.freeze end it "returns an Enumerator if no block is given" do @frozen.send(@method).should be_an_instance_of(enumerator_class) end describe "with truthy block" do it "keeps elements after any exception" do lambda { @frozen.send(@method) { true } }.should raise_error(Exception) @frozen.should == @origin end it "raises a RuntimeError" do lambda { @frozen.send(@method) { true } }.should raise_error(RuntimeError) end end describe "with falsy block" do it "keeps elements after any exception" do lambda { @frozen.send(@method) { false } }.should raise_error(Exception) @frozen.should == @origin end it "raises a RuntimeError" do lambda { @frozen.send(@method) { false } }.should raise_error(RuntimeError) end end end end
benlovell/rubyspec
core/array/shared/keep_if.rb
Ruby
mit
1,516
define(["bin/core/naviPageView"], function(Base) { var Class = {}; Class.onViewPush = function(pushFrom, pushData) { this._config = pushData; } Class.genHTML = function() { Base.prototype.genHTML.call(this); this.setTitle("示例 "+this._config.name); } return Base.extend(Class); });
weizhiwu/BIN
demo/common/demoView.js
JavaScript
mit
316
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using Orleans.Metadata; namespace Orleans.Runtime.Versions { /// <summary> /// Functionality for querying the declared version of grain interfaces. /// </summary> internal class GrainVersionManifest { private readonly object _lockObj = new object(); private readonly ConcurrentDictionary<GrainInterfaceType, GrainInterfaceType> _genericInterfaceMapping = new ConcurrentDictionary<GrainInterfaceType, GrainInterfaceType>(); private readonly ConcurrentDictionary<GrainType, GrainType> _genericGrainTypeMapping = new ConcurrentDictionary<GrainType, GrainType>(); private readonly IClusterManifestProvider _clusterManifestProvider; private readonly Dictionary<GrainInterfaceType, ushort> _localVersions; private Cache _cache; /// <summary> /// Initializes a new instance of the <see cref="GrainVersionManifest"/> class. /// </summary> /// <param name="clusterManifestProvider">The cluster manifest provider.</param> public GrainVersionManifest(IClusterManifestProvider clusterManifestProvider) { _clusterManifestProvider = clusterManifestProvider; _cache = BuildCache(clusterManifestProvider.Current); _localVersions = BuildLocalVersionMap(clusterManifestProvider.LocalGrainManifest); } /// <summary> /// Gets the current cluster manifest version. /// </summary> public MajorMinorVersion LatestVersion => _clusterManifestProvider.Current.Version; /// <summary> /// Gets the local version for a specified grain interface type. /// </summary> /// <param name="interfaceType">The grain intrerface type name.</param> /// <returns>The version of the specified grain interface.</returns> public ushort GetLocalVersion(GrainInterfaceType interfaceType) { if (_localVersions.TryGetValue(interfaceType, out var result)) { return result; } if (_genericInterfaceMapping.TryGetValue(interfaceType, out var genericInterfaceId)) { return GetLocalVersion(genericInterfaceId); } if (GenericGrainInterfaceType.TryParse(interfaceType, out var generic) && generic.IsConstructed) { var genericId = _genericInterfaceMapping[interfaceType] = generic.GetGenericGrainType().Value; return GetLocalVersion(genericId); } return 0; } /// <summary> /// Gets a collection of all known versions for a grain interface. /// </summary> /// <param name="interfaceType">The grain interface type name.</param> /// <returns>All known versions for the specified grain interface.</returns> public (MajorMinorVersion Version, ushort[] Result) GetAvailableVersions(GrainInterfaceType interfaceType) { var cache = GetCache(); if (cache.AvailableVersions.TryGetValue(interfaceType, out var result)) { return (cache.Version, result); } if (_genericInterfaceMapping.TryGetValue(interfaceType, out var genericInterfaceId)) { return GetAvailableVersions(genericInterfaceId); } if (GenericGrainInterfaceType.TryParse(interfaceType, out var generic) && generic.IsConstructed) { var genericId = _genericInterfaceMapping[interfaceType] = generic.GetGenericGrainType().Value; return GetAvailableVersions(genericId); } // No versions available. return (cache.Version, Array.Empty<ushort>()); } /// <summary> /// Gets the set of supported silos for a specified grain interface and version. /// </summary> /// <param name="interfaceType">The grain interface type name.</param> /// <param name="version">The grain interface version.</param> /// <returns>The set of silos which support the specified grain interface type and version.</returns> public (MajorMinorVersion Version, SiloAddress[] Result) GetSupportedSilos(GrainInterfaceType interfaceType, ushort version) { var cache = GetCache(); if (cache.SupportedSilosByInterface.TryGetValue((interfaceType, version), out var result)) { return (cache.Version, result); } if (_genericInterfaceMapping.TryGetValue(interfaceType, out var genericInterfaceId)) { return GetSupportedSilos(genericInterfaceId, version); } if (GenericGrainInterfaceType.TryParse(interfaceType, out var generic) && generic.IsConstructed) { var genericId = _genericInterfaceMapping[interfaceType] = generic.GetGenericGrainType().Value; return GetSupportedSilos(genericId, version); } // No supported silos for this version. return (cache.Version, Array.Empty<SiloAddress>()); } /// <summary> /// Gets the set of supported silos for the specified grain type. /// </summary> /// <param name="grainType">The grain type.</param> /// <returns>The silos which support the specified grain type.</returns> public (MajorMinorVersion Version, SiloAddress[] Result) GetSupportedSilos(GrainType grainType) { var cache = GetCache(); if (cache.SupportedSilosByGrainType.TryGetValue(grainType, out var result)) { return (cache.Version, result); } if (_genericGrainTypeMapping.TryGetValue(grainType, out var genericGrainType)) { return GetSupportedSilos(genericGrainType); } if (GenericGrainType.TryParse(grainType, out var generic) && generic.IsConstructed) { var genericId = _genericGrainTypeMapping[grainType] = generic.GetUnconstructedGrainType().GrainType; return GetSupportedSilos(genericId); } // No supported silos for this type. return (cache.Version, Array.Empty<SiloAddress>()); } /// <summary> /// Gets the set of supported silos for the specified combination of grain type, interface type, and version. /// </summary> /// <param name="grainType">The grain type.</param> /// <param name="interfaceType">The grain interface type name.</param> /// <param name="versions">The grain interface version.</param> /// <returns>The set of silos which support the specifed grain.</returns> public (MajorMinorVersion Version, Dictionary<ushort, SiloAddress[]> Result) GetSupportedSilos(GrainType grainType, GrainInterfaceType interfaceType, ushort[] versions) { var result = new Dictionary<ushort, SiloAddress[]>(); // Track the minimum version in case of inconsistent reads, since the caller can use that information to // ensure they refresh on the next call. MajorMinorVersion? minCacheVersion = null; foreach (var version in versions) { (var cacheVersion, var silosWithGrain) = this.GetSupportedSilos(grainType); if (!minCacheVersion.HasValue || cacheVersion > minCacheVersion.Value) { minCacheVersion = cacheVersion; } // We need to sort this so the list of silos returned will // be the same across all silos in the cluster SiloAddress[] silosWithCorrectVersion; (cacheVersion, silosWithCorrectVersion) = this.GetSupportedSilos(interfaceType, version); if (!minCacheVersion.HasValue || cacheVersion > minCacheVersion.Value) { minCacheVersion = cacheVersion; } result[version] = silosWithCorrectVersion .Intersect(silosWithGrain) .OrderBy(addr => addr) .ToArray(); } if (!minCacheVersion.HasValue) minCacheVersion = MajorMinorVersion.Zero; return (minCacheVersion.Value, result); } private Cache GetCache() { var cache = _cache; var manifest = _clusterManifestProvider.Current; if (manifest.Version == cache.Version) { return cache; } lock (_lockObj) { cache = _cache; manifest = _clusterManifestProvider.Current; if (manifest.Version == cache.Version) { return cache; } return _cache = BuildCache(manifest); } } private static Dictionary<GrainInterfaceType, ushort> BuildLocalVersionMap(GrainManifest manifest) { var result = new Dictionary<GrainInterfaceType, ushort>(); foreach (var grainInterface in manifest.Interfaces) { var id = grainInterface.Key; if (!grainInterface.Value.Properties.TryGetValue(WellKnownGrainInterfaceProperties.Version, out var versionString) || !ushort.TryParse(versionString, out var version)) { version = 0; } result[id] = version; } return result; } private static Cache BuildCache(ClusterManifest clusterManifest) { var available = new Dictionary<GrainInterfaceType, List<ushort>>(); var supportedInterfaces = new Dictionary<(GrainInterfaceType, ushort), List<SiloAddress>>(); var supportedGrains = new Dictionary<GrainType, List<SiloAddress>>(); foreach (var entry in clusterManifest.Silos) { var silo = entry.Key; var manifest = entry.Value; foreach (var grainInterface in manifest.Interfaces) { var id = grainInterface.Key; if (!grainInterface.Value.Properties.TryGetValue(WellKnownGrainInterfaceProperties.Version, out var versionString) || !ushort.TryParse(versionString, out var version)) { version = 0; } if (!available.TryGetValue(id, out var versions)) { available[id] = new List<ushort> { version }; } else if (!versions.Contains(version)) { versions.Add(version); } if (!supportedInterfaces.TryGetValue((id, version), out var supportedSilos)) { supportedInterfaces[(id, version)] = new List<SiloAddress> { silo }; } else if (!supportedSilos.Contains(silo)) { supportedSilos.Add(silo); } } foreach (var grainType in manifest.Grains) { var id = grainType.Key; if (!supportedGrains.TryGetValue(id, out var supportedSilos)) { supportedGrains[id] = new List<SiloAddress> { silo }; } else if (!supportedSilos.Contains(silo)) { supportedSilos.Add(silo); } } } var resultAvailable = new Dictionary<GrainInterfaceType, ushort[]>(); foreach (var entry in available) { entry.Value.Sort(); resultAvailable[entry.Key] = entry.Value.ToArray(); } var resultSupportedByInterface = new Dictionary<(GrainInterfaceType, ushort), SiloAddress[]>(); foreach (var entry in supportedInterfaces) { entry.Value.Sort(); resultSupportedByInterface[entry.Key] = entry.Value.ToArray(); } var resultSupportedSilosByGrainType = new Dictionary<GrainType, SiloAddress[]>(); foreach (var entry in supportedGrains) { entry.Value.Sort(); resultSupportedSilosByGrainType[entry.Key] = entry.Value.ToArray(); } return new Cache(clusterManifest.Version, resultAvailable, resultSupportedByInterface, resultSupportedSilosByGrainType); } private class Cache { public Cache( MajorMinorVersion version, Dictionary<GrainInterfaceType, ushort[]> availableVersions, Dictionary<(GrainInterfaceType, ushort), SiloAddress[]> supportedSilosByInterface, Dictionary<GrainType, SiloAddress[]> supportedSilosByGrainType) { this.Version = version; this.AvailableVersions = availableVersions; this.SupportedSilosByGrainType = supportedSilosByGrainType; this.SupportedSilosByInterface = supportedSilosByInterface; } public MajorMinorVersion Version { get; } public Dictionary<GrainInterfaceType, ushort[]> AvailableVersions { get; } public Dictionary<(GrainInterfaceType, ushort), SiloAddress[]> SupportedSilosByInterface { get; } = new Dictionary<(GrainInterfaceType, ushort), SiloAddress[]>(); public Dictionary<GrainType, SiloAddress[]> SupportedSilosByGrainType { get; } = new Dictionary<GrainType, SiloAddress[]>(); } } }
veikkoeeva/orleans
src/Orleans.Core/Manifest/GrainVersionManifest.cs
C#
mit
14,080
//===---- include/gcinfo/gcinfoutil.cpp -------------------------*- C++ -*-===// // // LLILC // // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // See LICENSE file in the project root for full license information. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Implementation of utility classes used by GCInfoEncoder library /// //===----------------------------------------------------------------------===// #include "GcInfoUtil.h" //***************************************************************************** // GcInfoAllocator //***************************************************************************** int GcInfoAllocator::ZeroLengthAlloc = 0; //***************************************************************************** // Utility Functions //***************************************************************************** //------------------------------------------------------------------------ // BitPosition: Return the position of the single bit that is set in 'value'. // // Return Value: // The position (0 is LSB) of bit that is set in 'value' // // Notes: // 'value' must have exactly one bit set. // The algorithm is as follows: // - PRIME is a prime bigger than sizeof(unsigned int), which is not of the // form 2^n-1. // - Taking the modulo of 'value' with this will produce a unique hash for // all powers of 2 (which is what "value" is). // - Entries in hashTable[] which are -1 should never be used. There // should be PRIME-8*sizeof(value) entries which are -1 . //------------------------------------------------------------------------ unsigned BitPosition(unsigned value) { _ASSERTE((value != 0) && ((value & (value - 1)) == 0)); const unsigned PRIME = 37; static const char hashTable[PRIME] = { -1, 0, 1, 26, 2, 23, 27, -1, 3, 16, 24, 30, 28, 11, -1, 13, 4, 7, 17, -1, 25, 22, 31, 15, 29, 10, 12, 6, -1, 21, 14, 9, 5, 20, 8, 19, 18}; _ASSERTE(PRIME >= 8 * sizeof(value)); _ASSERTE(sizeof(hashTable) == PRIME); unsigned hash = value % PRIME; unsigned index = hashTable[hash]; _ASSERTE(index != (unsigned char)-1); return index; } //***************************************************************************** // ArrayList //***************************************************************************** void StructArrayListBase::CreateNewChunk(SIZE_T InitialChunkLength, SIZE_T ChunkLengthGrowthFactor, SIZE_T cbElement, AllocProc *pfnAlloc, SIZE_T alignment) { _ASSERTE(InitialChunkLength > 0); _ASSERTE(ChunkLengthGrowthFactor > 0); _ASSERTE(cbElement > 0); SIZE_T cbBaseSize = SIZE_T(roundUp(sizeof(StructArrayListEntryBase), alignment)); SIZE_T maxChunkCapacity = (MAXSIZE_T - cbBaseSize) / cbElement; _ASSERTE(maxChunkCapacity > 0); SIZE_T nChunkCapacity; if (!m_pChunkListHead) nChunkCapacity = InitialChunkLength; else nChunkCapacity = m_nLastChunkCapacity * ChunkLengthGrowthFactor; if (nChunkCapacity > maxChunkCapacity) { // Limit nChunkCapacity such that cbChunk computation does not overflow. nChunkCapacity = maxChunkCapacity; } SIZE_T cbChunk = cbBaseSize + SIZE_T(cbElement) * SIZE_T(nChunkCapacity); StructArrayListEntryBase *pNewChunk = (StructArrayListEntryBase *)pfnAlloc(this, cbChunk); if (m_pChunkListTail) { _ASSERTE(m_pChunkListHead); m_pChunkListTail->pNext = pNewChunk; } else { _ASSERTE(!m_pChunkListHead); m_pChunkListHead = pNewChunk; } pNewChunk->pNext = NULL; m_pChunkListTail = pNewChunk; m_nItemsInLastChunk = 0; m_nLastChunkCapacity = nChunkCapacity; }
tempbottle/llilc
lib/GcInfo/GcInfoUtil.cpp
C++
mit
3,819
using System; namespace ClosedXML.Excel { internal class XLSheetView : IXLSheetView { public XLSheetView() { View = XLSheetViewOptions.Normal; ZoomScale = 100; ZoomScaleNormal = 100; ZoomScalePageLayoutView = 100; ZoomScaleSheetLayoutView = 100; } public XLSheetView(IXLSheetView sheetView) : this() { this.SplitRow = sheetView.SplitRow; this.SplitColumn = sheetView.SplitColumn; this.FreezePanes = ((XLSheetView)sheetView).FreezePanes; } public Boolean FreezePanes { get; set; } public Int32 SplitColumn { get; set; } public Int32 SplitRow { get; set; } public XLSheetViewOptions View { get; set; } public int ZoomScale { get { return _zoomScale; } set { _zoomScale = value; switch (View) { case XLSheetViewOptions.Normal: ZoomScaleNormal = value; break; case XLSheetViewOptions.PageBreakPreview: ZoomScalePageLayoutView = value; break; case XLSheetViewOptions.PageLayout: ZoomScaleSheetLayoutView = value; break; } } } public int ZoomScaleNormal { get; set; } public int ZoomScalePageLayoutView { get; set; } public int ZoomScaleSheetLayoutView { get; set; } private int _zoomScale { get; set; } public void Freeze(Int32 rows, Int32 columns) { SplitRow = rows; SplitColumn = columns; FreezePanes = true; } public void FreezeColumns(Int32 columns) { SplitColumn = columns; FreezePanes = true; } public void FreezeRows(Int32 rows) { SplitRow = rows; FreezePanes = true; } public IXLSheetView SetView(XLSheetViewOptions value) { View = value; return this; } } }
b0bi79/ClosedXML
ClosedXML/Excel/XLSheetView.cs
C#
mit
2,252
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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. */ package org.spongepowered.mod.mixin.entityactivation; import org.spongepowered.api.util.annotation.NonnullByDefault; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import org.spongepowered.common.interfaces.world.IMixinWorld; import org.spongepowered.common.mixin.plugin.entityactivation.ActivationRange; import org.spongepowered.common.mixin.plugin.entityactivation.interfaces.IModData_Activation; @NonnullByDefault @Mixin(net.minecraft.world.World.class) public abstract class MixinWorld_Activation implements IMixinWorld { @Inject(method = "updateEntityWithOptionalForce", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/event/ForgeEventFactory;canEntityUpdate(Lnet/minecraft/entity/Entity;)Z", shift = At.Shift.BY, by = 3, ordinal = 0, remap = false), cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD) public void onUpdateEntityWithOptionalForce(net.minecraft.entity.Entity entity, boolean forceUpdate, CallbackInfo ci, int i, int j, boolean isForced, int k, boolean canUpdate) { if (forceUpdate && !ActivationRange.checkIfActive(entity)) { entity.ticksExisted++; ((IModData_Activation) entity).inactiveTick(); ci.cancel(); } } }
DDoS/SpongeForge
src/main/java/org/spongepowered/mod/mixin/entityactivation/MixinWorld_Activation.java
Java
mit
2,737
module Danger class ExampleManyMethodsPlugin < Plugin def one end # Thing two # def two(param1) end def two_point_five(param1 = nil) end # Thing three # # @param [String] param1 # A thing thing, defaults to nil. # @return [void] # def three(param1 = nil) end # Thing four # # @param [Number] param1 # A thing thing, defaults to nil. # @param [String] param2 # Another param # @return [String] # def four(param1 = nil, param2) end # Thing five # # @param [Array<String>] param1 # A thing thing. # @param [Filepath] param2 # Another param # @return [String] # def five(param1 = [], param2, param3) end # Does six # @return [Bool] # def six? end # Attribute docs # # @return [Array<String>] attr_accessor :seven attr_accessor :eight end end
KrauseFx/danger
spec/fixtures/plugins/plugin_many_methods.rb
Ruby
mit
995
namespace MYOB.AccountRight.SDK.Contracts.Version2.Company { /// <summary> /// Purchase preferences /// </summary> public class CompanyPurchasesPreferences { /// <summary> /// Purchases' terms preferences /// </summary> public CompanyPurchasesPreferencesTerms Terms { get; set; } } }
MYOB-Technology/AccountRight_Live_API_.Net_SDK
MYOB.API.SDK/SDK/Contracts/Version2/Company/CompanyPurchasesPreferences.cs
C#
mit
343
/* * Websock: high-performance binary WebSockets * Copyright (C) 2012 Joel Martin * Licensed under MPL 2.0 (see LICENSE.txt) * * Websock is similar to the standard WebSocket object but Websock * enables communication with raw TCP sockets (i.e. the binary stream) * via websockify. This is accomplished by base64 encoding the data * stream between Websock and websockify. * * Websock has built-in receive queue buffering; the message event * does not contain actual data but is simply a notification that * there is new data available. Several rQ* methods are available to * read binary data off of the receive queue. */ /*jslint browser: true, bitwise: true */ /*global Util*/ // Load Flash WebSocket emulator if needed // To force WebSocket emulator even when native WebSocket available //window.WEB_SOCKET_FORCE_FLASH = true; // To enable WebSocket emulator debug: //window.WEB_SOCKET_DEBUG=1; if (window.WebSocket && !window.WEB_SOCKET_FORCE_FLASH) { Websock_native = true; } else if (window.MozWebSocket && !window.WEB_SOCKET_FORCE_FLASH) { Websock_native = true; window.WebSocket = window.MozWebSocket; } else { /* no builtin WebSocket so load web_socket.js */ Websock_native = false; } function Websock() { "use strict"; this._websocket = null; // WebSocket object this._rQi = 0; // Receive queue index this._rQlen = 0; // Next write position in the receive queue this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB) this._rQmax = this._rQbufferSize / 8; // called in init: this._rQ = new Uint8Array(this._rQbufferSize); this._rQ = null; // Receive queue this._sQbufferSize = 1024 * 10; // 10 KiB // called in init: this._sQ = new Uint8Array(this._sQbufferSize); this._sQlen = 0; this._sQ = null; // Send queue this._mode = 'binary'; // Current WebSocket mode: 'binary', 'base64' this.maxBufferedAmount = 200; this._eventHandlers = { 'message': function () {}, 'open': function () {}, 'close': function () {}, 'error': function () {} }; } (function () { "use strict"; // this has performance issues in some versions Chromium, and // doesn't gain a tremendous amount of performance increase in Firefox // at the moment. It may be valuable to turn it on in the future. var ENABLE_COPYWITHIN = false; var MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB var typedArrayToString = (function () { // This is only for PhantomJS, which doesn't like apply-ing // with Typed Arrays try { var arr = new Uint8Array([1, 2, 3]); String.fromCharCode.apply(null, arr); return function (a) { return String.fromCharCode.apply(null, a); }; } catch (ex) { return function (a) { return String.fromCharCode.apply( null, Array.prototype.slice.call(a)); }; } })(); Websock.prototype = { // Getters and Setters get_sQ: function () { return this._sQ; }, get_rQ: function () { return this._rQ; }, get_rQi: function () { return this._rQi; }, set_rQi: function (val) { this._rQi = val; }, // Receive Queue rQlen: function () { return this._rQlen - this._rQi; }, rQpeek8: function () { return this._rQ[this._rQi]; }, rQshift8: function () { return this._rQ[this._rQi++]; }, rQskip8: function () { this._rQi++; }, rQskipBytes: function (num) { this._rQi += num; }, // TODO(directxman12): test performance with these vs a DataView rQshift16: function () { return (this._rQ[this._rQi++] << 8) + this._rQ[this._rQi++]; }, rQshift32: function () { return (this._rQ[this._rQi++] << 24) + (this._rQ[this._rQi++] << 16) + (this._rQ[this._rQi++] << 8) + this._rQ[this._rQi++]; }, rQshiftStr: function (len) { if (typeof(len) === 'undefined') { len = this.rQlen(); } var arr = new Uint8Array(this._rQ.buffer, this._rQi, len); this._rQi += len; return typedArrayToString(arr); }, rQshiftBytes: function (len) { if (typeof(len) === 'undefined') { len = this.rQlen(); } this._rQi += len; return new Uint8Array(this._rQ.buffer, this._rQi - len, len); }, rQshiftTo: function (target, len) { if (len === undefined) { len = this.rQlen(); } // TODO: make this just use set with views when using a ArrayBuffer to store the rQ target.set(new Uint8Array(this._rQ.buffer, this._rQi, len)); this._rQi += len; }, rQwhole: function () { return new Uint8Array(this._rQ.buffer, 0, this._rQlen); }, rQslice: function (start, end) { if (end) { return new Uint8Array(this._rQ.buffer, this._rQi + start, end - start); } else { return new Uint8Array(this._rQ.buffer, this._rQi + start, this._rQlen - this._rQi - start); } }, // Check to see if we must wait for 'num' bytes (default to FBU.bytes) // to be available in the receive queue. Return true if we need to // wait (and possibly print a debug message), otherwise false. rQwait: function (msg, num, goback) { var rQlen = this._rQlen - this._rQi; // Skip rQlen() function call if (rQlen < num) { if (goback) { if (this._rQi < goback) { throw new Error("rQwait cannot backup " + goback + " bytes"); } this._rQi -= goback; } return true; // true means need more data } return false; }, // Send Queue flush: function () { if (this._websocket.bufferedAmount !== 0) { Util.Debug("bufferedAmount: " + this._websocket.bufferedAmount); } if (this._websocket.bufferedAmount < this.maxBufferedAmount) { if (this._sQlen > 0 && this._websocket.readyState === WebSocket.OPEN) { this._websocket.send(this._encode_message()); this._sQlen = 0; } return true; } else { Util.Info("Delaying send, bufferedAmount: " + this._websocket.bufferedAmount); return false; } }, send: function (arr) { this._sQ.set(arr, this._sQlen); this._sQlen += arr.length; return this.flush(); }, send_string: function (str) { this.send(str.split('').map(function (chr) { return chr.charCodeAt(0); })); }, // Event Handlers off: function (evt) { this._eventHandlers[evt] = function () {}; }, on: function (evt, handler) { this._eventHandlers[evt] = handler; }, _allocate_buffers: function () { this._rQ = new Uint8Array(this._rQbufferSize); this._sQ = new Uint8Array(this._sQbufferSize); }, init: function (protocols, ws_schema) { this._allocate_buffers(); this._rQi = 0; this._websocket = null; // Check for full typed array support var bt = false; if (('Uint8Array' in window) && ('set' in Uint8Array.prototype)) { bt = true; } // Check for full binary type support in WebSockets // Inspired by: // https://github.com/Modernizr/Modernizr/issues/370 // https://github.com/Modernizr/Modernizr/blob/master/feature-detects/websockets/binary.js var wsbt = false; try { if (bt && ('binaryType' in WebSocket.prototype || !!(new WebSocket(ws_schema + '://.').binaryType))) { Util.Info("Detected binaryType support in WebSockets"); wsbt = true; } } catch (exc) { // Just ignore failed test localhost connection } // Default protocols if not specified if (typeof(protocols) === "undefined") { protocols = 'binary'; } if (Array.isArray(protocols) && protocols.indexOf('binary') > -1) { protocols = 'binary'; } if (!wsbt) { throw new Error("noVNC no longer supports base64 WebSockets. " + "Please use a browser which supports binary WebSockets."); } if (protocols != 'binary') { throw new Error("noVNC no longer supports base64 WebSockets. Please " + "use the binary subprotocol instead."); } return protocols; }, open: function (uri, protocols) { var ws_schema = uri.match(/^([a-z]+):\/\//)[1]; protocols = this.init(protocols, ws_schema); this._websocket = new WebSocket(uri, protocols); if (protocols.indexOf('binary') >= 0) { this._websocket.binaryType = 'arraybuffer'; } this._websocket.onmessage = this._recv_message.bind(this); this._websocket.onopen = (function () { Util.Debug('>> WebSock.onopen'); if (this._websocket.protocol) { this._mode = this._websocket.protocol; Util.Info("Server choose sub-protocol: " + this._websocket.protocol); } else { this._mode = 'binary'; Util.Error('Server select no sub-protocol!: ' + this._websocket.protocol); } if (this._mode != 'binary') { throw new Error("noVNC no longer supports base64 WebSockets. Please " + "use the binary subprotocol instead."); } this._eventHandlers.open(); Util.Debug("<< WebSock.onopen"); }).bind(this); this._websocket.onclose = (function (e) { Util.Debug(">> WebSock.onclose"); this._eventHandlers.close(e); Util.Debug("<< WebSock.onclose"); }).bind(this); this._websocket.onerror = (function (e) { Util.Debug(">> WebSock.onerror: " + e); this._eventHandlers.error(e); Util.Debug("<< WebSock.onerror: " + e); }).bind(this); }, close: function () { if (this._websocket) { if ((this._websocket.readyState === WebSocket.OPEN) || (this._websocket.readyState === WebSocket.CONNECTING)) { Util.Info("Closing WebSocket connection"); this._websocket.close(); } this._websocket.onmessage = function (e) { return; }; } }, // private methods _encode_message: function () { // Put in a binary arraybuffer // according to the spec, you can send ArrayBufferViews with the send method return new Uint8Array(this._sQ.buffer, 0, this._sQlen); }, _expand_compact_rQ: function (min_fit) { var resizeNeeded = min_fit || this._rQlen - this._rQi > this._rQbufferSize / 2; if (resizeNeeded) { if (!min_fit) { // just double the size if we need to do compaction this._rQbufferSize *= 2; } else { // otherwise, make sure we satisy rQlen - rQi + min_fit < rQbufferSize / 8 this._rQbufferSize = (this._rQlen - this._rQi + min_fit) * 8; } } // we don't want to grow unboundedly if (this._rQbufferSize > MAX_RQ_GROW_SIZE) { this._rQbufferSize = MAX_RQ_GROW_SIZE; if (this._rQbufferSize - this._rQlen - this._rQi < min_fit) { throw new Exception("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit"); } } if (resizeNeeded) { var old_rQbuffer = this._rQ.buffer; this._rQmax = this._rQbufferSize / 8; this._rQ = new Uint8Array(this._rQbufferSize); this._rQ.set(new Uint8Array(old_rQbuffer, this._rQi)); } else { if (ENABLE_COPYWITHIN) { this._rQ.copyWithin(0, this._rQi); } else { this._rQ.set(new Uint8Array(this._rQ.buffer, this._rQi)); } } this._rQlen = this._rQlen - this._rQi; this._rQi = 0; }, _decode_message: function (data) { // push arraybuffer values onto the end var u8 = new Uint8Array(data); if (u8.length > this._rQbufferSize - this._rQlen) { this._expand_compact_rQ(u8.length); } this._rQ.set(u8, this._rQlen); this._rQlen += u8.length; }, _recv_message: function (e) { try { this._decode_message(e.data); if (this.rQlen() > 0) { this._eventHandlers.message(); // Compact the receive queue if (this._rQlen == this._rQi) { this._rQlen = 0; this._rQi = 0; } else if (this._rQlen > this._rQmax) { this._expand_compact_rQ(); } } else { Util.Debug("Ignoring empty message"); } } catch (exc) { var exception_str = ""; if (exc.name) { exception_str += "\n name: " + exc.name + "\n"; exception_str += " message: " + exc.message + "\n"; } if (typeof exc.description !== 'undefined') { exception_str += " description: " + exc.description + "\n"; } if (typeof exc.stack !== 'undefined') { exception_str += exc.stack; } if (exception_str.length > 0) { Util.Error("recv_message, caught exception: " + exception_str); } else { Util.Error("recv_message, caught exception: " + exc); } if (typeof exc.name !== 'undefined') { this._eventHandlers.error(exc.name + ": " + exc.message); } else { this._eventHandlers.error(exc); } } } }; })();
jerry-0824/017_stone
web/vnc/include/websock.js
JavaScript
mit
15,502
module Lotus module View module Rendering # Null Object pattern for layout template # # It's used when a layout doesn't have an associated template. # # A common scenario is for non-html requests. # Usually we have a template for the application layout # (eg `templates/application.html.erb`), but we don't use to have the a # template for JSON requests (eg `templates/application.json.erb`). # Because most of the times, we only return the output of the view. # # @api private # @since 0.1.0 # # @example # require 'lotus/view' # # # We have an ApplicationLayout (views/application_layout.rb): # class ApplicationLayout # include Lotus::Layout # end # # # Our layout has a template for HTML requests, located at: # # templates/application.html.erb # # # We set it as global layout # Lotus::View.layout = :application # # # We have two views for HTML and JSON articles. # # They have a template each: # # # # * templates/articles/show.html.erb # # * templates/articles/show.json.erb # module Articles # class Show # include Lotus::View # format :html # end # # class JsonShow < Show # format :json # end # end # # # We initialize the framework # Lotus::View.load! # # # # # When we ask for a HTML rendering, it will use `Articles::Show` and # # ApplicationLayout. The output will be a composition of: # # # # * templates/articles/show.html.erb # # * templates/application.html.erb # # # When we ask for a JSON rendering, it will use `Articles::JsonShow` # # and ApplicationLayout. Since, the layout doesn't have any associated # # template for JSON, the output will be a composition of: # # # # * templates/articles/show.json.erb class NullTemplate # Render the layout template # # @param scope [Lotus::View::Scope] the rendering scope # @param locals [Hash] a set of objects available during the rendering # @yield [Proc] yields the given block # # @return [String] the output of the rendering process # # @api private # @since 0.1.0 # # @see Lotus::Layout#render # @see Lotus::View::Rendering#render def render(scope, locals = {}) yield end end end end end
farrel/view
lib/lotus/view/rendering/null_template.rb
Ruby
mit
2,669
package service import ( "encoding/json" "strings" "code.cloudfoundry.org/cli/cf" "code.cloudfoundry.org/cli/cf/flagcontext" "code.cloudfoundry.org/cli/cf/flags" . "code.cloudfoundry.org/cli/cf/i18n" "code.cloudfoundry.org/cli/cf/uihelpers" "fmt" "code.cloudfoundry.org/cli/cf/api" "code.cloudfoundry.org/cli/cf/commandregistry" "code.cloudfoundry.org/cli/cf/configuration/coreconfig" "code.cloudfoundry.org/cli/cf/requirements" "code.cloudfoundry.org/cli/cf/terminal" ) type CreateUserProvidedService struct { ui terminal.UI config coreconfig.Reader userProvidedServiceInstanceRepo api.UserProvidedServiceInstanceRepository } func init() { commandregistry.Register(&CreateUserProvidedService{}) } func (cmd *CreateUserProvidedService) MetaData() commandregistry.CommandMetadata { fs := make(map[string]flags.FlagSet) fs["p"] = &flags.StringFlag{ShortName: "p", Usage: T("Credentials, provided inline or in a file, to be exposed in the VCAP_SERVICES environment variable for bound applications")} fs["l"] = &flags.StringFlag{ShortName: "l", Usage: T("URL to which logs for bound applications will be streamed")} fs["r"] = &flags.StringFlag{ShortName: "r", Usage: T("URL to which requests for bound routes will be forwarded. Scheme for this URL must be https")} fs["t"] = &flags.StringFlag{ShortName: "t", Usage: T("User provided tags")} return commandregistry.CommandMetadata{ Name: "create-user-provided-service", ShortName: "cups", Description: T("Make a user-provided service instance available to CF apps"), Usage: []string{ T(`CF_NAME create-user-provided-service SERVICE_INSTANCE [-p CREDENTIALS] [-l SYSLOG_DRAIN_URL] [-r ROUTE_SERVICE_URL] [-t TAGS] Pass comma separated credential parameter names to enable interactive mode: CF_NAME create-user-provided-service SERVICE_INSTANCE -p "comma, separated, parameter, names" Pass credential parameters as JSON to create a service non-interactively: CF_NAME create-user-provided-service SERVICE_INSTANCE -p '{"key1":"value1","key2":"value2"}' Specify a path to a file containing JSON: CF_NAME create-user-provided-service SERVICE_INSTANCE -p PATH_TO_FILE`), }, Examples: []string{ `CF_NAME create-user-provided-service my-db-mine -p "username, password"`, `CF_NAME create-user-provided-service my-db-mine -p /path/to/credentials.json`, `CF_NAME create-user-provided-service my-db-mine -t "list, of, tags"`, `CF_NAME create-user-provided-service my-drain-service -l syslog://example.com`, `CF_NAME create-user-provided-service my-route-service -r https://example.com`, ``, fmt.Sprintf("%s:", T(`Linux/Mac`)), ` CF_NAME create-user-provided-service my-db-mine -p '{"username":"admin","password":"pa55woRD"}'`, ``, fmt.Sprintf("%s:", T(`Windows Command Line`)), ` CF_NAME create-user-provided-service my-db-mine -p "{\"username\":\"admin\",\"password\":\"pa55woRD\"}"`, ``, fmt.Sprintf("%s:", T(`Windows PowerShell`)), ` CF_NAME create-user-provided-service my-db-mine -p '{\"username\":\"admin\",\"password\":\"pa55woRD\"}'`, }, Flags: fs, } } func (cmd *CreateUserProvidedService) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) { if len(fc.Args()) != 1 { cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + commandregistry.Commands.CommandUsage("create-user-provided-service")) return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 1) } reqs := []requirements.Requirement{ requirementsFactory.NewLoginRequirement(), requirementsFactory.NewTargetedSpaceRequirement(), } if fc.IsSet("t") { reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '-t'", cf.UserProvidedServiceTagsMinimumAPIVersion)) } return reqs, nil } func (cmd *CreateUserProvidedService) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command { cmd.ui = deps.UI cmd.config = deps.Config cmd.userProvidedServiceInstanceRepo = deps.RepoLocator.GetUserProvidedServiceInstanceRepository() return cmd } func (cmd *CreateUserProvidedService) Execute(c flags.FlagContext) error { name := c.Args()[0] drainURL := c.String("l") routeServiceURL := c.String("r") credentials := strings.Trim(c.String("p"), `"'`) credentialsMap := make(map[string]interface{}) tags := c.String("t") tagsList := uihelpers.ParseTags(tags) if c.IsSet("p") { jsonBytes, err := flagcontext.GetContentsFromFlagValue(credentials) if err != nil { return err } err = json.Unmarshal(jsonBytes, &credentialsMap) if err != nil { for _, param := range strings.Split(credentials, ",") { param = strings.Trim(param, " ") credentialsMap[param] = cmd.ui.Ask(param) } } } cmd.ui.Say(T("Creating user provided service {{.ServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...", map[string]interface{}{ "ServiceName": terminal.EntityNameColor(name), "OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name), "SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name), "CurrentUser": terminal.EntityNameColor(cmd.config.Username()), })) err := cmd.userProvidedServiceInstanceRepo.Create(name, drainURL, routeServiceURL, credentialsMap, tagsList) if err != nil { return err } cmd.ui.Ok() return nil }
odlp/antifreeze
vendor/github.com/cloudfoundry/cli/cf/commands/service/create_user_provided_service.go
GO
mit
5,467
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Spark.CSharp.Core; using Microsoft.Spark.CSharp.Interop; using Microsoft.Spark.CSharp.Interop.Ipc; namespace Microsoft.Spark.CSharp.Proxy.Ipc { [ExcludeFromCodeCoverage] //IPC calls to JVM validated using validation-enabled samples - unit test coverage not reqiured internal class StatusTrackerIpcProxy : IStatusTrackerProxy { private readonly JvmObjectReference jvmStatusTrackerReference; public StatusTrackerIpcProxy(JvmObjectReference jStatusTracker) { jvmStatusTrackerReference = jStatusTracker; } public int[] GetJobIdsForGroup(string jobGroup) { return (int[])SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jvmStatusTrackerReference, "getJobIdsForGroup", new object[] { jobGroup }); } public int[] GetActiveStageIds() { return (int[])SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jvmStatusTrackerReference, "getActiveStageIds"); } public int[] GetActiveJobsIds() { return (int[])SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jvmStatusTrackerReference, "getActiveJobsIds"); } public SparkJobInfo GetJobInfo(int jobId) { var jobInfoId = SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jvmStatusTrackerReference, "getJobInfo", new object[] { jobId }); if (jobInfoId == null) return null; JvmObjectReference jJobInfo = new JvmObjectReference((string)jobInfoId); int[] stageIds = (int[])SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jJobInfo, "stageIds"); string statusString = SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jJobInfo, "status").ToString(); var status = (JobExecutionStatus) Enum.Parse(typeof(JobExecutionStatus), statusString, true); return new SparkJobInfo(jobId, stageIds, status); } public SparkStageInfo GetStageInfo(int stageId) { var stageInfoId = SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jvmStatusTrackerReference, "getStageInfo", new object[] { stageId }); if (stageInfoId == null) return null; JvmObjectReference jStageInfo = new JvmObjectReference((string)stageInfoId); int currentAttemptId = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "currentAttemptId"); int submissionTime = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "submissionTime"); string name = (string)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "name"); int numTasks = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "numTasks"); int numActiveTasks = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "numActiveTasks"); int numCompletedTasks = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "numCompletedTasks"); int numFailedTasks = (int)SparkCLRIpcProxy.JvmBridge.CallNonStaticJavaMethod(jStageInfo, "numFailedTasks"); return new SparkStageInfo(stageId, currentAttemptId, (long)submissionTime, name, numTasks, numActiveTasks, numCompletedTasks, numFailedTasks); } } }
dwnichols/Mobius
csharp/Adapter/Microsoft.Spark.CSharp/Proxy/Ipc/StatusTrackerIpcProxy.cs
C#
mit
3,621
/* Copyright 2016 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package helm // import "k8s.io/helm/pkg/helm" import ( "errors" "path/filepath" "reflect" "testing" "github.com/golang/protobuf/proto" "golang.org/x/net/context" "k8s.io/helm/pkg/chartutil" cpb "k8s.io/helm/pkg/proto/hapi/chart" rls "k8s.io/helm/pkg/proto/hapi/release" tpb "k8s.io/helm/pkg/proto/hapi/services" ) // Path to example charts relative to pkg/helm. const chartsDir = "../../docs/examples/" // Sentinel error to indicate to the Helm client to not send the request to Tiller. var errSkip = errors.New("test: skip") // Verify each ReleaseListOption is applied to a ListReleasesRequest correctly. func TestListReleases_VerifyOptions(t *testing.T) { // Options testdata var limit = 2 var offset = "offset" var filter = "filter" var sortBy = int32(2) var sortOrd = int32(1) var codes = []rls.Status_Code{ rls.Status_FAILED, rls.Status_DELETED, rls.Status_DEPLOYED, rls.Status_SUPERSEDED, } var namespace = "namespace" // Expected ListReleasesRequest message exp := &tpb.ListReleasesRequest{ Limit: int64(limit), Offset: offset, Filter: filter, SortBy: tpb.ListSort_SortBy(sortBy), SortOrder: tpb.ListSort_SortOrder(sortOrd), StatusCodes: codes, Namespace: namespace, } // Options used in ListReleases ops := []ReleaseListOption{ ReleaseListSort(sortBy), ReleaseListOrder(sortOrd), ReleaseListLimit(limit), ReleaseListOffset(offset), ReleaseListFilter(filter), ReleaseListStatuses(codes), ReleaseListNamespace(namespace), } // BeforeCall option to intercept Helm client ListReleasesRequest b4c := BeforeCall(func(_ context.Context, msg proto.Message) error { switch act := msg.(type) { case *tpb.ListReleasesRequest: t.Logf("ListReleasesRequest: %#+v\n", act) assert(t, exp, act) default: t.Fatalf("expected message of type ListReleasesRequest, got %T\n", act) } return errSkip }) client := NewClient(b4c) if _, err := client.ListReleases(ops...); err != errSkip { t.Fatalf("did not expect error but got (%v)\n``", err) } // ensure options for call are not saved to client assert(t, "", client.opts.listReq.Filter) } // Verify each InstallOption is applied to an InstallReleaseRequest correctly. func TestInstallRelease_VerifyOptions(t *testing.T) { // Options testdata var disableHooks = true var releaseName = "test" var namespace = "default" var reuseName = true var dryRun = true var chartName = "alpine" var chartPath = filepath.Join(chartsDir, chartName) var overrides = []byte("key1=value1,key2=value2") // Expected InstallReleaseRequest message exp := &tpb.InstallReleaseRequest{ Chart: loadChart(t, chartName), Values: &cpb.Config{Raw: string(overrides)}, DryRun: dryRun, Name: releaseName, DisableHooks: disableHooks, Namespace: namespace, ReuseName: reuseName, } // Options used in InstallRelease ops := []InstallOption{ ValueOverrides(overrides), InstallDryRun(dryRun), ReleaseName(releaseName), InstallReuseName(reuseName), InstallDisableHooks(disableHooks), } // BeforeCall option to intercept Helm client InstallReleaseRequest b4c := BeforeCall(func(_ context.Context, msg proto.Message) error { switch act := msg.(type) { case *tpb.InstallReleaseRequest: t.Logf("InstallReleaseRequest: %#+v\n", act) assert(t, exp, act) default: t.Fatalf("expected message of type InstallReleaseRequest, got %T\n", act) } return errSkip }) client := NewClient(b4c) if _, err := client.InstallRelease(chartPath, namespace, ops...); err != errSkip { t.Fatalf("did not expect error but got (%v)\n``", err) } // ensure options for call are not saved to client assert(t, "", client.opts.instReq.Name) } // Verify each DeleteOptions is applied to an UninstallReleaseRequest correctly. func TestDeleteRelease_VerifyOptions(t *testing.T) { // Options testdata var releaseName = "test" var disableHooks = true var purgeFlag = true // Expected DeleteReleaseRequest message exp := &tpb.UninstallReleaseRequest{ Name: releaseName, Purge: purgeFlag, DisableHooks: disableHooks, } // Options used in DeleteRelease ops := []DeleteOption{ DeletePurge(purgeFlag), DeleteDisableHooks(disableHooks), } // BeforeCall option to intercept Helm client DeleteReleaseRequest b4c := BeforeCall(func(_ context.Context, msg proto.Message) error { switch act := msg.(type) { case *tpb.UninstallReleaseRequest: t.Logf("UninstallReleaseRequest: %#+v\n", act) assert(t, exp, act) default: t.Fatalf("expected message of type UninstallReleaseRequest, got %T\n", act) } return errSkip }) client := NewClient(b4c) if _, err := client.DeleteRelease(releaseName, ops...); err != errSkip { t.Fatalf("did not expect error but got (%v)\n``", err) } // ensure options for call are not saved to client assert(t, "", client.opts.uninstallReq.Name) } // Verify each UpdateOption is applied to an UpdateReleaseRequest correctly. func TestUpdateRelease_VerifyOptions(t *testing.T) { // Options testdata var chartName = "alpine" var chartPath = filepath.Join(chartsDir, chartName) var releaseName = "test" var disableHooks = true var overrides = []byte("key1=value1,key2=value2") var dryRun = false // Expected UpdateReleaseRequest message exp := &tpb.UpdateReleaseRequest{ Name: releaseName, Chart: loadChart(t, chartName), Values: &cpb.Config{Raw: string(overrides)}, DryRun: dryRun, DisableHooks: disableHooks, } // Options used in UpdateRelease ops := []UpdateOption{ UpgradeDryRun(dryRun), UpdateValueOverrides(overrides), UpgradeDisableHooks(disableHooks), } // BeforeCall option to intercept Helm client UpdateReleaseRequest b4c := BeforeCall(func(_ context.Context, msg proto.Message) error { switch act := msg.(type) { case *tpb.UpdateReleaseRequest: t.Logf("UpdateReleaseRequest: %#+v\n", act) assert(t, exp, act) default: t.Fatalf("expected message of type UpdateReleaseRequest, got %T\n", act) } return errSkip }) client := NewClient(b4c) if _, err := client.UpdateRelease(releaseName, chartPath, ops...); err != errSkip { t.Fatalf("did not expect error but got (%v)\n``", err) } // ensure options for call are not saved to client assert(t, "", client.opts.updateReq.Name) } // Verify each RollbackOption is applied to a RollbackReleaseRequest correctly. func TestRollbackRelease_VerifyOptions(t *testing.T) { // Options testdata var disableHooks = true var releaseName = "test" var revision = int32(2) var dryRun = true // Expected RollbackReleaseRequest message exp := &tpb.RollbackReleaseRequest{ Name: releaseName, DryRun: dryRun, Version: revision, DisableHooks: disableHooks, } // Options used in RollbackRelease ops := []RollbackOption{ RollbackDryRun(dryRun), RollbackVersion(revision), RollbackDisableHooks(disableHooks), } // BeforeCall option to intercept Helm client RollbackReleaseRequest b4c := BeforeCall(func(_ context.Context, msg proto.Message) error { switch act := msg.(type) { case *tpb.RollbackReleaseRequest: t.Logf("RollbackReleaseRequest: %#+v\n", act) assert(t, exp, act) default: t.Fatalf("expected message of type RollbackReleaseRequest, got %T\n", act) } return errSkip }) client := NewClient(b4c) if _, err := client.RollbackRelease(releaseName, ops...); err != errSkip { t.Fatalf("did not expect error but got (%v)\n``", err) } // ensure options for call are not saved to client assert(t, "", client.opts.rollbackReq.Name) } // Verify each StatusOption is applied to a GetReleaseStatusRequest correctly. func TestReleaseStatus_VerifyOptions(t *testing.T) { // Options testdata var releaseName = "test" var revision = int32(2) // Expected GetReleaseStatusRequest message exp := &tpb.GetReleaseStatusRequest{ Name: releaseName, Version: revision, } // BeforeCall option to intercept Helm client GetReleaseStatusRequest b4c := BeforeCall(func(_ context.Context, msg proto.Message) error { switch act := msg.(type) { case *tpb.GetReleaseStatusRequest: t.Logf("GetReleaseStatusRequest: %#+v\n", act) assert(t, exp, act) default: t.Fatalf("expected message of type GetReleaseStatusRequest, got %T\n", act) } return errSkip }) client := NewClient(b4c) if _, err := client.ReleaseStatus(releaseName, StatusReleaseVersion(revision)); err != errSkip { t.Fatalf("did not expect error but got (%v)\n``", err) } // ensure options for call are not saved to client assert(t, "", client.opts.statusReq.Name) } // Verify each ContentOption is applied to a GetReleaseContentRequest correctly. func TestReleaseContent_VerifyOptions(t *testing.T) { // Options testdata var releaseName = "test" var revision = int32(2) // Expected GetReleaseContentRequest message exp := &tpb.GetReleaseContentRequest{ Name: releaseName, Version: revision, } // BeforeCall option to intercept Helm client GetReleaseContentRequest b4c := BeforeCall(func(_ context.Context, msg proto.Message) error { switch act := msg.(type) { case *tpb.GetReleaseContentRequest: t.Logf("GetReleaseContentRequest: %#+v\n", act) assert(t, exp, act) default: t.Fatalf("expected message of type GetReleaseContentRequest, got %T\n", act) } return errSkip }) client := NewClient(b4c) if _, err := client.ReleaseContent(releaseName, ContentReleaseVersion(revision)); err != errSkip { t.Fatalf("did not expect error but got (%v)\n``", err) } // ensure options for call are not saved to client assert(t, "", client.opts.contentReq.Name) } func assert(t *testing.T, expect, actual interface{}) { if !reflect.DeepEqual(expect, actual) { t.Fatalf("expected %#+v, actual %#+v\n", expect, actual) } } func loadChart(t *testing.T, name string) *cpb.Chart { c, err := chartutil.Load(filepath.Join(chartsDir, name)) if err != nil { t.Fatalf("failed to load test chart (%q): %s\n", name, err) } return c }
skuid/helm-value-store
vendor/k8s.io/helm/pkg/helm/helm_test.go
GO
mit
10,604
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Filesystem; use Symfony\Component\Filesystem\Exception\FileNotFoundException; use Symfony\Component\Filesystem\Exception\InvalidArgumentException; use Symfony\Component\Filesystem\Exception\IOException; /** * Provides basic utility to manipulate the file system. * * @author Fabien Potencier <fabien@symfony.com> */ class Filesystem { private static $lastError; /** * Copies a file. * * If the target file is older than the origin file, it's always overwritten. * If the target file is newer, it is overwritten only when the * $overwriteNewerFiles option is set to true. * * @throws FileNotFoundException When originFile doesn't exist * @throws IOException When copy fails */ public function copy(string $originFile, string $targetFile, bool $overwriteNewerFiles = false) { $originIsLocal = stream_is_local($originFile) || 0 === stripos($originFile, 'file://'); if ($originIsLocal && !is_file($originFile)) { throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile); } $this->mkdir(\dirname($targetFile)); $doCopy = true; if (!$overwriteNewerFiles && null === parse_url($originFile, PHP_URL_HOST) && is_file($targetFile)) { $doCopy = filemtime($originFile) > filemtime($targetFile); } if ($doCopy) { // https://bugs.php.net/64634 if (false === $source = @fopen($originFile, 'r')) { throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile); } // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default if (false === $target = @fopen($targetFile, 'w', null, stream_context_create(['ftp' => ['overwrite' => true]]))) { throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile); } $bytesCopied = stream_copy_to_stream($source, $target); fclose($source); fclose($target); unset($source, $target); if (!is_file($targetFile)) { throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile); } if ($originIsLocal) { // Like `cp`, preserve executable permission bits @chmod($targetFile, fileperms($targetFile) | (fileperms($originFile) & 0111)); if ($bytesCopied !== $bytesOrigin = filesize($originFile)) { throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s" (%g of %g bytes copied).', $originFile, $targetFile, $bytesCopied, $bytesOrigin), 0, null, $originFile); } } } } /** * Creates a directory recursively. * * @param string|iterable $dirs The directory path * * @throws IOException On any directory creation failure */ public function mkdir($dirs, int $mode = 0777) { foreach ($this->toIterable($dirs) as $dir) { if (is_dir($dir)) { continue; } if (!self::box('mkdir', $dir, $mode, true)) { if (!is_dir($dir)) { // The directory was not created by a concurrent process. Let's throw an exception with a developer friendly error message if we have one if (self::$lastError) { throw new IOException(sprintf('Failed to create "%s": ', $dir).self::$lastError, 0, null, $dir); } throw new IOException(sprintf('Failed to create "%s".', $dir), 0, null, $dir); } } } } /** * Checks the existence of files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to check * * @return bool true if the file exists, false otherwise */ public function exists($files) { $maxPathLength = PHP_MAXPATHLEN - 2; foreach ($this->toIterable($files) as $file) { if (\strlen($file) > $maxPathLength) { throw new IOException(sprintf('Could not check if file exist because path length exceeds %d characters.', $maxPathLength), 0, null, $file); } if (!file_exists($file)) { return false; } } return true; } /** * Sets access and modification time of file. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to create * @param int|null $time The touch time as a Unix timestamp, if not supplied the current system time is used * @param int|null $atime The access time as a Unix timestamp, if not supplied the current system time is used * * @throws IOException When touch fails */ public function touch($files, int $time = null, int $atime = null) { foreach ($this->toIterable($files) as $file) { $touch = $time ? @touch($file, $time, $atime) : @touch($file); if (true !== $touch) { throw new IOException(sprintf('Failed to touch "%s".', $file), 0, null, $file); } } } /** * Removes files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to remove * * @throws IOException When removal fails */ public function remove($files) { if ($files instanceof \Traversable) { $files = iterator_to_array($files, false); } elseif (!\is_array($files)) { $files = [$files]; } $files = array_reverse($files); foreach ($files as $file) { if (is_link($file)) { // See https://bugs.php.net/52176 if (!(self::box('unlink', $file) || '\\' !== \DIRECTORY_SEPARATOR || self::box('rmdir', $file)) && file_exists($file)) { throw new IOException(sprintf('Failed to remove symlink "%s": ', $file).self::$lastError); } } elseif (is_dir($file)) { $this->remove(new \FilesystemIterator($file, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS)); if (!self::box('rmdir', $file) && file_exists($file)) { throw new IOException(sprintf('Failed to remove directory "%s": ', $file).self::$lastError); } } elseif (!self::box('unlink', $file) && file_exists($file)) { throw new IOException(sprintf('Failed to remove file "%s": ', $file).self::$lastError); } } } /** * Change mode for an array of files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change mode * @param int $mode The new mode (octal) * @param int $umask The mode mask (octal) * @param bool $recursive Whether change the mod recursively or not * * @throws IOException When the change fails */ public function chmod($files, int $mode, int $umask = 0000, bool $recursive = false) { foreach ($this->toIterable($files) as $file) { if (true !== @chmod($file, $mode & ~$umask)) { throw new IOException(sprintf('Failed to chmod file "%s".', $file), 0, null, $file); } if ($recursive && is_dir($file) && !is_link($file)) { $this->chmod(new \FilesystemIterator($file), $mode, $umask, true); } } } /** * Change the owner of an array of files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change owner * @param string|int $user A user name or number * @param bool $recursive Whether change the owner recursively or not * * @throws IOException When the change fails */ public function chown($files, $user, bool $recursive = false) { foreach ($this->toIterable($files) as $file) { if ($recursive && is_dir($file) && !is_link($file)) { $this->chown(new \FilesystemIterator($file), $user, true); } if (is_link($file) && \function_exists('lchown')) { if (true !== @lchown($file, $user)) { throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file); } } else { if (true !== @chown($file, $user)) { throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file); } } } } /** * Change the group of an array of files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change group * @param string|int $group A group name or number * @param bool $recursive Whether change the group recursively or not * * @throws IOException When the change fails */ public function chgrp($files, $group, bool $recursive = false) { foreach ($this->toIterable($files) as $file) { if ($recursive && is_dir($file) && !is_link($file)) { $this->chgrp(new \FilesystemIterator($file), $group, true); } if (is_link($file) && \function_exists('lchgrp')) { if (true !== @lchgrp($file, $group)) { throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file); } } else { if (true !== @chgrp($file, $group)) { throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file); } } } } /** * Renames a file or a directory. * * @throws IOException When target file or directory already exists * @throws IOException When origin cannot be renamed */ public function rename(string $origin, string $target, bool $overwrite = false) { // we check that target does not exist if (!$overwrite && $this->isReadable($target)) { throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target), 0, null, $target); } if (true !== @rename($origin, $target)) { if (is_dir($origin)) { // See https://bugs.php.net/54097 & https://php.net/rename#113943 $this->mirror($origin, $target, null, ['override' => $overwrite, 'delete' => $overwrite]); $this->remove($origin); return; } throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target), 0, null, $target); } } /** * Tells whether a file exists and is readable. * * @throws IOException When windows path is longer than 258 characters */ private function isReadable(string $filename): bool { $maxPathLength = PHP_MAXPATHLEN - 2; if (\strlen($filename) > $maxPathLength) { throw new IOException(sprintf('Could not check if file is readable because path length exceeds %d characters.', $maxPathLength), 0, null, $filename); } return is_readable($filename); } /** * Creates a symbolic link or copy a directory. * * @throws IOException When symlink fails */ public function symlink(string $originDir, string $targetDir, bool $copyOnWindows = false) { if ('\\' === \DIRECTORY_SEPARATOR) { $originDir = strtr($originDir, '/', '\\'); $targetDir = strtr($targetDir, '/', '\\'); if ($copyOnWindows) { $this->mirror($originDir, $targetDir); return; } } $this->mkdir(\dirname($targetDir)); if (is_link($targetDir)) { if (readlink($targetDir) === $originDir) { return; } $this->remove($targetDir); } if (!self::box('symlink', $originDir, $targetDir)) { $this->linkException($originDir, $targetDir, 'symbolic'); } } /** * Creates a hard link, or several hard links to a file. * * @param string|string[] $targetFiles The target file(s) * * @throws FileNotFoundException When original file is missing or not a file * @throws IOException When link fails, including if link already exists */ public function hardlink(string $originFile, $targetFiles) { if (!$this->exists($originFile)) { throw new FileNotFoundException(null, 0, null, $originFile); } if (!is_file($originFile)) { throw new FileNotFoundException(sprintf('Origin file "%s" is not a file.', $originFile)); } foreach ($this->toIterable($targetFiles) as $targetFile) { if (is_file($targetFile)) { if (fileinode($originFile) === fileinode($targetFile)) { continue; } $this->remove($targetFile); } if (!self::box('link', $originFile, $targetFile)) { $this->linkException($originFile, $targetFile, 'hard'); } } } /** * @param string $linkType Name of the link type, typically 'symbolic' or 'hard' */ private function linkException(string $origin, string $target, string $linkType) { if (self::$lastError) { if ('\\' === \DIRECTORY_SEPARATOR && false !== strpos(self::$lastError, 'error code(1314)')) { throw new IOException(sprintf('Unable to create "%s" link due to error code 1314: \'A required privilege is not held by the client\'. Do you have the required Administrator-rights?', $linkType), 0, null, $target); } } throw new IOException(sprintf('Failed to create "%s" link from "%s" to "%s".', $linkType, $origin, $target), 0, null, $target); } /** * Resolves links in paths. * * With $canonicalize = false (default) * - if $path does not exist or is not a link, returns null * - if $path is a link, returns the next direct target of the link without considering the existence of the target * * With $canonicalize = true * - if $path does not exist, returns null * - if $path exists, returns its absolute fully resolved final version * * @return string|null */ public function readlink(string $path, bool $canonicalize = false) { if (!$canonicalize && !is_link($path)) { return null; } if ($canonicalize) { if (!$this->exists($path)) { return null; } if ('\\' === \DIRECTORY_SEPARATOR) { $path = readlink($path); } return realpath($path); } if ('\\' === \DIRECTORY_SEPARATOR) { return realpath($path); } return readlink($path); } /** * Given an existing path, convert it to a path relative to a given starting path. * * @return string Path of target relative to starting path */ public function makePathRelative(string $endPath, string $startPath) { if (!$this->isAbsolutePath($startPath)) { throw new InvalidArgumentException(sprintf('The start path "%s" is not absolute.', $startPath)); } if (!$this->isAbsolutePath($endPath)) { throw new InvalidArgumentException(sprintf('The end path "%s" is not absolute.', $endPath)); } // Normalize separators on Windows if ('\\' === \DIRECTORY_SEPARATOR) { $endPath = str_replace('\\', '/', $endPath); $startPath = str_replace('\\', '/', $startPath); } $splitDriveLetter = function ($path) { return (\strlen($path) > 2 && ':' === $path[1] && '/' === $path[2] && ctype_alpha($path[0])) ? [substr($path, 2), strtoupper($path[0])] : [$path, null]; }; $splitPath = function ($path) { $result = []; foreach (explode('/', trim($path, '/')) as $segment) { if ('..' === $segment) { array_pop($result); } elseif ('.' !== $segment && '' !== $segment) { $result[] = $segment; } } return $result; }; list($endPath, $endDriveLetter) = $splitDriveLetter($endPath); list($startPath, $startDriveLetter) = $splitDriveLetter($startPath); $startPathArr = $splitPath($startPath); $endPathArr = $splitPath($endPath); if ($endDriveLetter && $startDriveLetter && $endDriveLetter != $startDriveLetter) { // End path is on another drive, so no relative path exists return $endDriveLetter.':/'.($endPathArr ? implode('/', $endPathArr).'/' : ''); } // Find for which directory the common path stops $index = 0; while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) { ++$index; } // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels) if (1 === \count($startPathArr) && '' === $startPathArr[0]) { $depth = 0; } else { $depth = \count($startPathArr) - $index; } // Repeated "../" for each level need to reach the common path $traverser = str_repeat('../', $depth); $endPathRemainder = implode('/', \array_slice($endPathArr, $index)); // Construct $endPath from traversing to the common path, then to the remaining $endPath $relativePath = $traverser.('' !== $endPathRemainder ? $endPathRemainder.'/' : ''); return '' === $relativePath ? './' : $relativePath; } /** * Mirrors a directory to another. * * Copies files and directories from the origin directory into the target directory. By default: * * - existing files in the target directory will be overwritten, except if they are newer (see the `override` option) * - files in the target directory that do not exist in the source directory will not be deleted (see the `delete` option) * * @param \Traversable|null $iterator Iterator that filters which files and directories to copy, if null a recursive iterator is created * @param array $options An array of boolean options * Valid options are: * - $options['override'] If true, target files newer than origin files are overwritten (see copy(), defaults to false) * - $options['copy_on_windows'] Whether to copy files instead of links on Windows (see symlink(), defaults to false) * - $options['delete'] Whether to delete files that are not in the source directory (defaults to false) * * @throws IOException When file type is unknown */ public function mirror(string $originDir, string $targetDir, \Traversable $iterator = null, array $options = []) { $targetDir = rtrim($targetDir, '/\\'); $originDir = rtrim($originDir, '/\\'); $originDirLen = \strlen($originDir); if (!$this->exists($originDir)) { throw new IOException(sprintf('The origin directory specified "%s" was not found.', $originDir), 0, null, $originDir); } // Iterate in destination folder to remove obsolete entries if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) { $deleteIterator = $iterator; if (null === $deleteIterator) { $flags = \FilesystemIterator::SKIP_DOTS; $deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST); } $targetDirLen = \strlen($targetDir); foreach ($deleteIterator as $file) { $origin = $originDir.substr($file->getPathname(), $targetDirLen); if (!$this->exists($origin)) { $this->remove($file); } } } $copyOnWindows = $options['copy_on_windows'] ?? false; if (null === $iterator) { $flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS; $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST); } $this->mkdir($targetDir); $filesCreatedWhileMirroring = []; foreach ($iterator as $file) { if ($file->getPathname() === $targetDir || $file->getRealPath() === $targetDir || isset($filesCreatedWhileMirroring[$file->getRealPath()])) { continue; } $target = $targetDir.substr($file->getPathname(), $originDirLen); $filesCreatedWhileMirroring[$target] = true; if (!$copyOnWindows && is_link($file)) { $this->symlink($file->getLinkTarget(), $target); } elseif (is_dir($file)) { $this->mkdir($target); } elseif (is_file($file)) { $this->copy($file, $target, isset($options['override']) ? $options['override'] : false); } else { throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file); } } } /** * Returns whether the file path is an absolute path. * * @return bool */ public function isAbsolutePath(string $file) { return strspn($file, '/\\', 0, 1) || (\strlen($file) > 3 && ctype_alpha($file[0]) && ':' === $file[1] && strspn($file, '/\\', 2, 1) ) || null !== parse_url($file, PHP_URL_SCHEME) ; } /** * Creates a temporary file with support for custom stream wrappers. * * @param string $prefix The prefix of the generated temporary filename * Note: Windows uses only the first three characters of prefix * @param string $suffix The suffix of the generated temporary filename * * @return string The new temporary filename (with path), or throw an exception on failure */ public function tempnam(string $dir, string $prefix/*, string $suffix = ''*/) { $suffix = \func_num_args() > 2 ? func_get_arg(2) : ''; list($scheme, $hierarchy) = $this->getSchemeAndHierarchy($dir); // If no scheme or scheme is "file" or "gs" (Google Cloud) create temp file in local filesystem if ((null === $scheme || 'file' === $scheme || 'gs' === $scheme) && '' === $suffix) { $tmpFile = @tempnam($hierarchy, $prefix); // If tempnam failed or no scheme return the filename otherwise prepend the scheme if (false !== $tmpFile) { if (null !== $scheme && 'gs' !== $scheme) { return $scheme.'://'.$tmpFile; } return $tmpFile; } throw new IOException('A temporary file could not be created.'); } // Loop until we create a valid temp file or have reached 10 attempts for ($i = 0; $i < 10; ++$i) { // Create a unique filename $tmpFile = $dir.'/'.$prefix.uniqid(mt_rand(), true).$suffix; // Use fopen instead of file_exists as some streams do not support stat // Use mode 'x+' to atomically check existence and create to avoid a TOCTOU vulnerability $handle = @fopen($tmpFile, 'x+'); // If unsuccessful restart the loop if (false === $handle) { continue; } // Close the file if it was successfully opened @fclose($handle); return $tmpFile; } throw new IOException('A temporary file could not be created.'); } /** * Atomically dumps content into a file. * * @param string|resource $content The data to write into the file * * @throws IOException if the file cannot be written to */ public function dumpFile(string $filename, $content) { if (\is_array($content)) { throw new \TypeError(sprintf('Argument 2 passed to "%s()" must be string or resource, array given.', __METHOD__)); } $dir = \dirname($filename); if (!is_dir($dir)) { $this->mkdir($dir); } if (!is_writable($dir)) { throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir); } // Will create a temp file with 0600 access rights // when the filesystem supports chmod. $tmpFile = $this->tempnam($dir, basename($filename)); if (false === @file_put_contents($tmpFile, $content)) { throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename); } @chmod($tmpFile, file_exists($filename) ? fileperms($filename) : 0666 & ~umask()); $this->rename($tmpFile, $filename, true); } /** * Appends content to an existing file. * * @param string|resource $content The content to append * * @throws IOException If the file is not writable */ public function appendToFile(string $filename, $content) { if (\is_array($content)) { throw new \TypeError(sprintf('Argument 2 passed to "%s()" must be string or resource, array given.', __METHOD__)); } $dir = \dirname($filename); if (!is_dir($dir)) { $this->mkdir($dir); } if (!is_writable($dir)) { throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir); } if (false === @file_put_contents($filename, $content, FILE_APPEND)) { throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename); } } private function toIterable($files): iterable { return \is_array($files) || $files instanceof \Traversable ? $files : [$files]; } /** * Gets a 2-tuple of scheme (may be null) and hierarchical part of a filename (e.g. file:///tmp -> [file, tmp]). */ private function getSchemeAndHierarchy(string $filename): array { $components = explode('://', $filename, 2); return 2 === \count($components) ? [$components[0], $components[1]] : [null, $components[0]]; } /** * @return mixed */ private static function box(callable $func) { self::$lastError = null; set_error_handler(__CLASS__.'::handleError'); try { $result = $func(...\array_slice(\func_get_args(), 1)); restore_error_handler(); return $result; } catch (\Throwable $e) { } restore_error_handler(); throw $e; } /** * @internal */ public static function handleError($type, $msg) { self::$lastError = $msg; } }
gonzalovilaseca/symfony
src/Symfony/Component/Filesystem/Filesystem.php
PHP
mit
28,366