repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
eSDK/esdk_uc_plugin_ucservice
platform/HWUCSDK/windows/eSpace_Desktop_V200R001C50SPC100B091/include/ace/PI_Malloc.cpp
5174
#ifndef ACE_PI_MALLOC_CPP #define ACE_PI_MALLOC_CPP #include "ace/PI_Malloc.h" ACE_RCSID (ace, PI_Malloc, "$Id: PI_Malloc.cpp 79134 2007-07-31 18:23:50Z johnnyw $") #if (ACE_HAS_POSITION_INDEPENDENT_POINTERS == 1) #if !defined (__ACE_INLINE__) #include "ace/PI_Malloc.inl" #endif /* __ACE_INLINE__ */ #include "ace/Object_Manager.h" #include "ace/Process_Mutex.h" #include "ace/OS_NS_string.h" ACE_BEGIN_VERSIONED_NAMESPACE_DECL void ACE_PI_Control_Block::ACE_Malloc_Header::dump (void) const { #if defined (ACE_HAS_DUMP) ACE_TRACE ("ACE_PI_Control_Block::ACE_Malloc_Header::dump"); ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nnext_block = %x"), (ACE_Malloc_Header *) this->next_block_)); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nsize = %d\n"), this->size_)); ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); #endif /* ACE_HAS_DUMP */ } void ACE_PI_Control_Block::print_alignment_info (void) { #if defined (ACE_HAS_DUMP) ACE_TRACE ("ACE_PI_Control_Block::ACE_Control_Block::print_alignment_info"); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Start ---> ACE_PI_Control_Block::print_alignment_info:\n"))); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Sizeof ptr: %d\n") ACE_TEXT ("Sizeof size_t: %d\n") ACE_TEXT ("Sizeof long: %d\n") ACE_TEXT ("Sizeof double: %d\n") ACE_TEXT ("Sizeof ACE_MALLOC_ALIGN: %d\n") ACE_TEXT ("sizeof ACE_MALLOC_PADDING: %d\n") ACE_TEXT ("Sizeof ACE_MALLOC_HEADER_SIZE: %d\n") ACE_TEXT ("Sizeof ACE_PI_MALLOC_PADDING_SIZE: %d\n") ACE_TEXT ("Sizeof ACE_PI_CONTROL_BLOCK_SIZE: %d\n") ACE_TEXT ("Sizeof ACE_PI_CONTROL_BLOCK_ALIGN_BYTES: %d\n") ACE_TEXT ("Sizeof (MALLOC_HEADER): %d\n") ACE_TEXT ("Sizeof (CONTROL_BLOCK): %d\n"), sizeof (char *), sizeof (size_t), sizeof (long), sizeof (double), ACE_MALLOC_ALIGN, ACE_MALLOC_PADDING, ACE_MALLOC_HEADER_SIZE, ACE_PI_MALLOC_PADDING_SIZE, ACE_PI_CONTROL_BLOCK_SIZE, ACE_PI_CONTROL_BLOCK_ALIGN_BYTES, sizeof (ACE_Malloc_Header), sizeof (ACE_PI_Control_Block) )); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("End <--- ACE_PI_Control_Block::print_alignment_info:\n"))); #endif /* ACE_HAS_DUMP */ } void ACE_PI_Control_Block::dump (void) const { #if defined (ACE_HAS_DUMP) ACE_TRACE ("ACE_PI_Control_Block::dump"); ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Name Node:\n"))); for (ACE_Name_Node *nextn = this->name_head_; nextn != 0; nextn = nextn->next_) nextn->dump (); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("freep_ = %x"), (ACE_Malloc_Header *) this->freep_)); this->base_.dump (); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nMalloc Header:\n"))); for (ACE_Malloc_Header *nexth = ((ACE_Malloc_Header *)this->freep_)->next_block_; nexth != 0 && nexth != &this->base_; nexth = nexth->next_block_) nexth->dump (); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); #endif /* ACE_HAS_DUMP */ } ACE_PI_Control_Block::ACE_Name_Node::ACE_Name_Node (void) { ACE_TRACE ("ACE_PI_Control_Block::ACE_Name_Node::ACE_Name_Node"); } ACE_PI_Control_Block::ACE_Name_Node::ACE_Name_Node (const char *name, char *name_ptr, char *pointer, ACE_Name_Node *next) : name_ (name_ptr), pointer_ (pointer), next_ (next), prev_ (0) { ACE_TRACE ("ACE_PI_Control_Block::ACE_Name_Node::ACE_Name_Node"); char *n = this->name_; ACE_OS::strcpy (n, name); if (next != 0) next->prev_ = this; } ACE_PI_Control_Block::ACE_Name_Node::ACE_Name_Node (const ACE_Name_Node &) { ACE_TRACE ("ACE_PI_Control_Block::ACE_Name_Node::ACE_Name_Node"); ACE_ASSERT (0); // not implemented! } const char * ACE_PI_Control_Block::ACE_Name_Node::name (void) const { const char *c = this->name_; return c; } void ACE_PI_Control_Block::ACE_Name_Node::name (const char *) { ACE_ASSERT (0); // not implemented yet. } ACE_PI_Control_Block::ACE_Malloc_Header::ACE_Malloc_Header (void) : next_block_ (0), size_ (0) { } void ACE_PI_Control_Block::ACE_Name_Node::dump (void) const { #if defined (ACE_HAS_DUMP) ACE_TRACE ("ACE_PI_Control_Block::ACE_Name_Node::dump"); ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); ACE_DEBUG ((LM_DEBUG, ACE_TEXT("pointer = %x"), (const char *) this->pointer_)); ACE_DEBUG ((LM_DEBUG, ACE_TEXT("\nnext_ = %x"), (ACE_Name_Node *) this->next_)); ACE_DEBUG ((LM_DEBUG, ACE_TEXT("\nname_ = (%x, %s)"), (const char *) this->name_, (const char *) this->name_)); ACE_DEBUG ((LM_DEBUG, ACE_TEXT("\n"))); ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); #endif /* ACE_HAS_DUMP */ } ACE_END_VERSIONED_NAMESPACE_DECL #endif /* ACE_HAS_POSITION_INDEPENDENT_POINTERS == 1*/ #endif /* ACE_PI_MALLOC_CPP */
apache-2.0
Shadance/StockSharp
Connectors/Rss/RssMarketDataMessageAdapter.cs
3356
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Rss.Rss File: RssMarketDataMessageAdapter.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Rss { using System; using System.Linq; using System.ServiceModel.Syndication; using Ecng.Common; using Ecng.Serialization; using StockSharp.Messages; using StockSharp.Localization; /// <summary> /// The market-data message adapter for Rss. /// </summary> public partial class RssMarketDataMessageAdapter : MessageAdapter { private bool _isSubscribed; /// <summary> /// Initializes a new instance of the <see cref="RssMarketDataMessageAdapter"/>. /// </summary> /// <param name="transactionIdGenerator">Transaction id generator.</param> public RssMarketDataMessageAdapter(IdGenerator transactionIdGenerator) : base(transactionIdGenerator) { HeartbeatInterval = TimeSpan.FromMinutes(5); this.AddSupportedMessage(MessageTypes.MarketData); } /// <summary> /// Send message. /// </summary> /// <param name="message">Message.</param> protected override void OnSendInMessage(Message message) { switch (message.Type) { case MessageTypes.Reset: { _isSubscribed = false; SendOutMessage(new ResetMessage()); break; } case MessageTypes.Connect: { var error = Address == null ? new InvalidOperationException(LocalizedStrings.Str3503) : null; SendOutMessage(new ConnectMessage { Error = error }); break; } case MessageTypes.Disconnect: SendOutMessage(new DisconnectMessage()); break; case MessageTypes.MarketData: { var mdMsg = (MarketDataMessage)message; switch (mdMsg.DataType) { case MarketDataTypes.News: { _isSubscribed = mdMsg.IsSubscribe; break; } default: { SendOutMarketDataNotSupported(mdMsg.TransactionId); return; } } var reply = (MarketDataMessage)mdMsg.Clone(); reply.OriginalTransactionId = mdMsg.TransactionId; SendOutMessage(reply); if (_isSubscribed) ProcessRss(); break; } case MessageTypes.Time: // heartbeat handling { if (_isSubscribed) ProcessRss(); break; } } } private void ProcessRss() { using (var reader = new XmlReaderEx(Address.To<string>()) { CustomDateFormat = CustomDateFormat }) { var feed = SyndicationFeed.Load(reader); foreach (var item in feed.Items) { SendOutMessage(new NewsMessage { Id = item.Id, Source = feed.Authors.Select(a => a.Name).Join(","), ServerTime = item.PublishDate, Headline = item.Title.Text, Story = item.Summary == null ? string.Empty : item.Summary.Text, Url = item.Links.Any() ? item.Links[0].Uri : null }); } } } } }
apache-2.0
ChenAt/common-dao
src/main/java/top/chenat/commondao/bean/Example.java
17262
/* * The MIT License (MIT) * * Copyright (c) 2014-2016 abel533@gmail.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. */ package top.chenat.commondao.bean; import top.chenat.commondao.BaseDaoSupport; import top.chenat.commondao.utils.StringUtil; import java.util.*; /** * 通用的Example查询对象 * * @author liuzh */ public class Example { protected String orderByClause; protected boolean distinct; protected boolean exists; protected boolean notNull; protected Set<String> selectColumns; protected List<Criteria> oredCriteria; protected Class<?> entityClass; protected Entity table; //属性和列对应 protected Map<String, Entity.Column> propertyMap; //动态表名 protected String tableName; protected OrderBy ORDERBY; //默认exists为true public Example(Class<?> entityClass) { this(entityClass, true); } /** * 带exists参数的构造方法,默认notNull为false,允许为空 * * @param exists - true时,如果字段不存在就抛出异常,false时,如果不存在就不使用该字段的条件 */ public Example(Class<?> entityClass, boolean exists) { this(entityClass, exists, false); } /** * 带exists参数的构造方法 * * @param exists - true时,如果字段不存在就抛出异常,false时,如果不存在就不使用该字段的条件 * @param notNull - true时,如果值为空,就会抛出异常,false时,如果为空就不使用该字段的条件 */ public Example(Class<?> entityClass, boolean exists, boolean notNull) { this.exists = exists; this.notNull = notNull; oredCriteria = new ArrayList<Criteria>(); this.entityClass = entityClass; table = BaseDaoSupport.getEntityTable(entityClass); //根据李领北建议修改#159 propertyMap = table.getPropertyMap(); this.tableName = table.getTableName(); this.ORDERBY = new OrderBy(this, propertyMap); } public Class<?> getEntityClass() { return entityClass; } public String getOrderByClause() { return orderByClause; } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public OrderBy orderBy(String property) { this.ORDERBY.orderBy(property); return this.ORDERBY; } public static class OrderBy { private Example example; private Boolean isProperty; //属性和列对应 protected Map<String, Entity.Column> propertyMap; protected boolean notNull; public OrderBy(Example example, Map<String, Entity.Column> propertyMap) { this.example = example; this.propertyMap = propertyMap; } private String property(String property) { if (propertyMap.containsKey(property)) { return propertyMap.get(property).getName(); } else if (notNull) { throw new RuntimeException("当前实体类不包含名为" + property + "的属性!"); } else { return null; } } public OrderBy orderBy(String property) { String column = property(property); if (column == null) { isProperty = false; return this; } if (StringUtil.isNotEmpty(example.getOrderByClause())) { example.setOrderByClause(example.getOrderByClause() + "," + column); } else { example.setOrderByClause(column); } isProperty = true; return this; } public OrderBy desc() { if (isProperty) { example.setOrderByClause(example.getOrderByClause() + " DESC"); isProperty = false; } return this; } public OrderBy asc() { if (isProperty) { example.setOrderByClause(example.getOrderByClause() + " ASC"); isProperty = false; } return this; } } public Set<String> getSelectColumns() { return selectColumns; } /** * 指定要查询的属性列 - 这里会自动映射到表字段 */ public Example selectProperties(String... properties) { if (properties != null && properties.length > 0) { if (this.selectColumns == null) { this.selectColumns = new LinkedHashSet<String>(); } for (String property : properties) { if (propertyMap.containsKey(property)) { this.selectColumns.add(propertyMap.get(property).getName()); } } } return this; } public boolean isDistinct() { return distinct; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(propertyMap, exists, notNull); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * 设置表名 */ public void setTableName(String tableName) { this.tableName = tableName; } public String getTableName() { return tableName; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; //字段是否必须存在 protected boolean exists; //值是否不能为空 protected boolean notNull; //属性和列对应 protected Map<String, Entity.Column> propertyMap; protected GeneratedCriteria(Map<String, Entity.Column> propertyMap, boolean exists, boolean notNull) { super(); this.exists = exists; this.notNull = notNull; criteria = new ArrayList<Criterion>(); this.propertyMap = propertyMap; } private String column(String property) { if (propertyMap.containsKey(property)) { return propertyMap.get(property).getName(); } else if (exists) { throw new RuntimeException("当前实体类不包含名为" + property + "的属性!"); } else { return null; } } private String property(String property) { if (propertyMap.containsKey(property)) { return property; } else if (exists) { throw new RuntimeException("当前实体类不包含名为" + property + "的属性!"); } else { return null; } } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } if (condition.startsWith("null")) { return; } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { if (notNull) { throw new RuntimeException("Value for " + property + " cannot be null"); } else { return; } } if (property == null) { return; } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { if (notNull) { throw new RuntimeException("Between values for " + property + " cannot be null"); } else { return; } } if (property == null) { return; } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIsNull(String property) { addCriterion(column(property) + " is null"); return (Criteria) this; } public Criteria andIsNotNull(String property) { addCriterion(column(property) + " is not null"); return (Criteria) this; } public Criteria andEqualTo(String property, Object value) { addCriterion(column(property) + " =", value, property(property)); return (Criteria) this; } public Criteria andNotEqualTo(String property, Object value) { addCriterion(column(property) + " <>", value, property(property)); return (Criteria) this; } public Criteria andGreaterThan(String property, Object value) { addCriterion(column(property) + " >", value, property(property)); return (Criteria) this; } public Criteria andGreaterThanOrEqualTo(String property, Object value) { addCriterion(column(property) + " >=", value, property(property)); return (Criteria) this; } public Criteria andLessThan(String property, Object value) { addCriterion(column(property) + " <", value, property(property)); return (Criteria) this; } public Criteria andLessThanOrEqualTo(String property, Object value) { addCriterion(column(property) + " <=", value, property(property)); return (Criteria) this; } public Criteria andIn(String property, Iterable values) { addCriterion(column(property) + " in", values, property(property)); return (Criteria) this; } public Criteria andNotIn(String property, Iterable values) { addCriterion(column(property) + " not in", values, property(property)); return (Criteria) this; } public Criteria andBetween(String property, Object value1, Object value2) { addCriterion(column(property) + " between", value1, value2, property(property)); return (Criteria) this; } public Criteria andNotBetween(String property, Object value1, Object value2) { addCriterion(column(property) + " not between", value1, value2, property(property)); return (Criteria) this; } public Criteria andLike(String property, String value) { addCriterion(column(property) + " like", value, property(property)); return (Criteria) this; } public Criteria andNotLike(String property, String value) { addCriterion(column(property) + " not like", value, property(property)); return (Criteria) this; } /** * 手写条件 * * @param condition 例如 "length(countryname)<5" */ public Criteria andCondition(String condition) { addCriterion(condition); return (Criteria) this; } /** * 手写左边条件,右边用value值 * * @param condition 例如 "length(countryname)=" * @param value 例如 5 */ public Criteria andCondition(String condition, Object value) { criteria.add(new Criterion(condition, value)); return (Criteria) this; } /** * 手写左边条件,右边用value值 * * @param condition 例如 "length(countryname)=" * @param value 例如 5 * @param typeHandler 类型处理 * @deprecated 由于typeHandler起不到作用,该方法会在4.x版本去掉 */ @Deprecated public Criteria andCondition(String condition, Object value, String typeHandler) { criteria.add(new Criterion(condition, value, typeHandler)); return (Criteria) this; } // /** // * 将此对象的不为空的字段参数作为相等查询条件 // * // * @param param 参数对象 // * @author Bob {@link}0haizhu0@gmail.com // * @Date 2015年7月17日 下午12:48:08 // */ // public Criteria andEqualTo(Object param) { // MetaObject metaObject = SystemMetaObject.forObject(param); // String[] properties = metaObject.getGetterNames(); // for (String property : properties) { // //属性和列对应Map中有此属性 // if (propertyMap.get(property) != null) { // Object value = metaObject.getValue(property); // //属性值不为空 // if (value != null) { // andEqualTo(property, value); // } // } // } // return (Criteria) this; // } } public static class Criteria extends GeneratedCriteria { protected Criteria(Map<String, Entity.Column> propertyMap, boolean exists, boolean notNull) { super(propertyMap, exists, notNull); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof Collection<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } public String getCondition() { return condition; } public Object getValue() { return "'"+value+"'"; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } } }
apache-2.0
ckelsel/AndroidTraining
training/owncloud-android-library/src/com/owncloud/android/lib/common/network/NetworkUtils.java
9204
/* ownCloud Android Library is available under MIT license * Copyright (C) 2016 ownCloud GmbH. * * 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 com.owncloud.android.lib.common.network; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier; import org.apache.http.conn.ssl.X509HostnameVerifier; import android.content.Context; import com.owncloud.android.lib.common.utils.Log_OC; public class NetworkUtils { final private static String TAG = NetworkUtils.class.getSimpleName(); /** Default timeout for waiting data from the server */ public static final int DEFAULT_DATA_TIMEOUT = 60000; /** Default timeout for establishing a connection */ public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; /** Standard name for protocol TLS version 1.2 in Java Secure Socket Extension (JSSE) API */ public static final String PROTOCOL_TLSv1_2 = "TLSv1.2"; /** Standard name for protocol TLS version 1.0 in JSSE API */ public static final String PROTOCOL_TLSv1_0 = "TLSv1"; /** Connection manager for all the OwnCloudClients */ private static MultiThreadedHttpConnectionManager mConnManager = null; private static Protocol mDefaultHttpsProtocol = null; private static AdvancedSslSocketFactory mAdvancedSslSocketFactory = null; private static X509HostnameVerifier mHostnameVerifier = null; /** * Registers or unregisters the proper components for advanced SSL handling. * @throws IOException */ @SuppressWarnings("deprecation") public static void registerAdvancedSslContext(boolean register, Context context) throws GeneralSecurityException, IOException { Protocol pr = null; try { pr = Protocol.getProtocol("https"); if (pr != null && mDefaultHttpsProtocol == null) { mDefaultHttpsProtocol = pr; } } catch (IllegalStateException e) { // nothing to do here; really } boolean isRegistered = (pr != null && pr.getSocketFactory() instanceof AdvancedSslSocketFactory); if (register && !isRegistered) { Protocol.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context), 443)); } else if (!register && isRegistered) { if (mDefaultHttpsProtocol != null) { Protocol.registerProtocol("https", mDefaultHttpsProtocol); } } } public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException { if (mAdvancedSslSocketFactory == null) { KeyStore trustStore = getKnownServersStore(context); AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore); TrustManager[] tms = new TrustManager[] { trustMgr }; SSLContext sslContext; try { sslContext = SSLContext.getInstance("TLSv1.2"); } catch (NoSuchAlgorithmException e) { Log_OC.w(TAG, "TLSv1.2 is not supported in this device; falling through TLSv1.0"); sslContext = SSLContext.getInstance("TLSv1"); // should be available in any device; see reference of supported protocols in // http://developer.android.com/reference/javax/net/ssl/SSLSocket.html } sslContext.init(null, tms, null); mHostnameVerifier = new BrowserCompatHostnameVerifier(); mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier); } return mAdvancedSslSocketFactory; } private static String LOCAL_TRUSTSTORE_FILENAME = "knownServers.bks"; private static String LOCAL_TRUSTSTORE_PASSWORD = "password"; private static KeyStore mKnownServersStore = null; /** * Returns the local store of reliable server certificates, explicitly accepted by the user. * * Returns a KeyStore instance with empty content if the local store was never created. * * Loads the store from the storage environment if needed. * * @param context Android context where the operation is being performed. * @return KeyStore instance with explicitly-accepted server certificates. * @throws KeyStoreException When the KeyStore instance could not be created. * @throws IOException When an existing local trust store could not be loaded. * @throws NoSuchAlgorithmException When the existing local trust store was saved with an unsupported algorithm. * @throws CertificateException When an exception occurred while loading the certificates from the local * trust store. */ private static KeyStore getKnownServersStore(Context context) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { if (mKnownServersStore == null) { //mKnownServersStore = KeyStore.getInstance("BKS"); mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType()); File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME); Log_OC.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath()); if (localTrustStoreFile.exists()) { InputStream in = new FileInputStream(localTrustStoreFile); try { mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); } finally { in.close(); } } else { // next is necessary to initialize an empty KeyStore instance mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); } } return mKnownServersStore; } public static void addCertToKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore knownServers = getKnownServersStore(context); knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert); FileOutputStream fos = null; try { fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE); knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); } finally { fos.close(); } } static public MultiThreadedHttpConnectionManager getMultiThreadedConnManager() { if (mConnManager == null) { mConnManager = new MultiThreadedHttpConnectionManager(); mConnManager.getParams().setDefaultMaxConnectionsPerHost(5); mConnManager.getParams().setMaxTotalConnections(5); } return mConnManager; } public static boolean isCertInKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore knownServers = getKnownServersStore(context); Log_OC.d(TAG, "Certificate - HashCode: " + cert.hashCode() + " " + Boolean.toString(knownServers.isCertificateEntry(Integer.toString(cert.hashCode())))); return knownServers.isCertificateEntry(Integer.toString(cert.hashCode())); } }
apache-2.0
AlexanderTAdams/hw2_rottenpotatoes
config/routes.rb
96
Rottenpotatoes::Application.routes.draw do root :to => 'movies#index' resources :movies end
apache-2.0
ferstl/spring-jdbc-oracle
src/test/java/com/github/ferstl/spring/jdbc/oracle/HikariNamedParameterIntegrationTest.java
961
/* * Copyright (c) 2021 by Philippe Marschall <philippe.marschall@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.ferstl.spring.jdbc.oracle; import org.springframework.test.context.ActiveProfiles; import com.github.ferstl.spring.jdbc.oracle.dsconfig.DataSourceProfile; @ActiveProfiles(DataSourceProfile.HIKARICP) public class HikariNamedParameterIntegrationTest extends AbstractNamedParameterIntegrationTest { }
apache-2.0
alienyip/coolweather
app/src/main/java/com/coolweather/android/db/City.java
841
package com.coolweather.android.db; import org.litepal.crud.DataSupport; /** * Created by Nature on 2017/3/23. */ public class City extends DataSupport { private int id; private String cityName; private int cityCode; private int provinceId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public int getCityCode() { return cityCode; } public void setCityCode(int cityCode) { this.cityCode = cityCode; } public int getProvinceId() { return provinceId; } public void setProvinceId(int provinceId) { this.provinceId = provinceId; } }
apache-2.0
nishikigoi/watson-mm
spec/line/bot/send_message_03_video_spec.rb
1592
require 'spec_helper' require 'webmock/rspec' require 'json' WebMock.allow_net_connect! describe Line::Bot::Client do it 'pushes the video message' do uri_template = Addressable::Template.new Line::Bot::API::DEFAULT_ENDPOINT + '/message/push' stub_request(:post, uri_template).to_return { |request| {:body => request.body, :status => 200} } client = Line::Bot::Client.new do |config| config.channel_token = 'channel_token' end user_id = 'user_id' message = { type: 'video', originalContentUrl: 'https://example.com/video.mp4', previewImageUrl: 'https://example.com/video_preview.jpg', } response = client.push_message(user_id, message) expected = { to: user_id, messages: [ message ] }.to_json expect(response.body).to eq(expected) end it 'replies the video message' do uri_template = Addressable::Template.new Line::Bot::API::DEFAULT_ENDPOINT + '/message/reply' stub_request(:post, uri_template).to_return { |request| {:body => request.body, :status => 200} } client = Line::Bot::Client.new do |config| config.channel_token = 'channel_token' end reply_token = 'reply_token' message = { type: 'video', originalContentUrl: 'https://example.com/video.mp4', previewImageUrl: 'https://example.com/video_preview.jpg', } response = client.reply_message(reply_token, message) expected = { replyToken: reply_token, messages: [ message ] }.to_json expect(response.body).to eq(expected) end end
apache-2.0
vimaier/conqat
org.conqat.engine.text/test-src/org/conqat/engine/text/comments/analysis/metric/CommentMetricTest.java
3214
/*-------------------------------------------------------------------------+ | | | Copyright 2005-2011 The ConQAT Project | | | | 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.conqat.engine.text.comments.analysis.metric; import org.conqat.engine.sourcecode.resource.ITokenElement; import org.conqat.engine.text.comments.analysis.CommentTestBase; import org.conqat.engine.text.comments.analysis.metric.CommentMetricAnalysis; import org.conqat.lib.scanner.ELanguage; /** * Test for comment metrics, i.e. the comment character distribution. * * @author $Author: hummelb $ * @version $Rev: 46289 $ * @ConQAT.Rating GREEN Hash: EF2F2F0FE92DC9B7A21564AD93CF912C */ public class CommentMetricTest extends CommentTestBase { /** Tests how many comments were counted for each comment category. */ public void testCommentDistribution() throws Exception { initBundleContexts(); assertMetricValue("CommentClassification.java", 654, CommentMetricAnalysis.KEY_COPYRIGHT_COUNT); assertMetricValue("CommentClassification.java", 94, CommentMetricAnalysis.KEY_HEADER_COUNT); assertMetricValue("CommentClassification.java", 57, CommentMetricAnalysis.KEY_INTERFACE_COUNT); assertMetricValue("CommentClassification.java", 23, CommentMetricAnalysis.KEY_INLINE_COUNT); assertMetricValue("CommentClassification.java", 37, CommentMetricAnalysis.KEY_TASK_COUNT); assertMetricValue("CommentClassification.java", 291, CommentMetricAnalysis.KEY_COMMENTED_OUT_CODE_COUNT); assertMetricValue("CommentClassification.java", 100, CommentMetricAnalysis.KEY_SECTION_COUNT); } /** * Assertion method that the number of characters counted in the given file * under the given key matches the expected number of characters. */ private void assertMetricValue(String filename, int expectedCharacters, String metricKey) throws Exception { ITokenElement element = createTokenElement( useCanonicalTestFile(filename), ELanguage.JAVA); executeProcessor(CommentMetricAnalysis.class, "(input=(ref=", element, "))"); int num = (Integer) element.getValue(metricKey); assertEquals(expectedCharacters, num); } }
apache-2.0
bikeonastick/embedjrubytest
src/org/bikeonastick/scripting/RubyRunner.java
2376
package org.bikeonastick.scripting; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.jruby.Ruby; import org.jruby.RubyArray; import org.jruby.RubyClass; import org.jruby.ast.executable.Script; import org.jruby.embed.ScriptingContainer; import org.jruby.exceptions.RaiseException; import org.jruby.internal.runtime.GlobalVariables; import org.jruby.javasupport.JavaEmbedUtils; import org.jruby.javasupport.JavaEmbedUtils.EvalUnit; import org.jruby.runtime.builtin.IRubyObject; /** * Copyright 2011 robert tomb */ public class RubyRunner { /** * @param args */ public static void main(String[] args) { RubyRunner theMaker = new RubyRunner("call_greeting.rb"); theMaker.rubyEval(args); } public RubyRunner(String scriptName){ this.scriptName = scriptName; this.fileUrl = this.getClass().getResource("/" + scriptName); System.out.println(); } /** * This creates a RubyRuntime with loadpaths set to the directory * that holds your script. */ public Ruby getRubyRuntime(){ if(this.rubyRuntime == null){ List placesToSearch = new ArrayList(); String filepath = getScriptLoc(); placesToSearch.add(filepath); this.rubyRuntime = JavaEmbedUtils.initialize(placesToSearch); } return this.rubyRuntime; } public String getScriptLoc(){ String loc = null; if(fileUrl != null){ String filePath = fileUrl.getFile(); loc = filePath.substring(0, (filePath.length() - this.scriptName.length())); } return loc; } public IRubyObject rubyEval(String[] args) { InputStream script; IRubyObject ret = null; try { script = this.fileUrl.openStream(); ScriptingContainer container = new ScriptingContainer(); container.setArgv(args); EvalUnit parsedScript = container.parse(script,this.scriptName); ret = parsedScript.run(); } catch (IOException e) { System.out.println("Problems reading the ruby script"); e.printStackTrace(); } return ret; } private Ruby rubyRuntime; private URL fileUrl; private String scriptName; }
apache-2.0
cityzendata/warp10-platform
warp10/src/main/java/io/warp10/script/functions/LOCATIONS.java
2342
// // Copyright 2018 SenX S.A.S. // // 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 io.warp10.script.functions; import io.warp10.continuum.gts.GTSHelper; import io.warp10.continuum.gts.GeoTimeSerie; import io.warp10.script.NamedWarpScriptFunction; import io.warp10.script.WarpScriptStackFunction; import io.warp10.script.WarpScriptException; import io.warp10.script.WarpScriptStack; import java.util.ArrayList; import java.util.List; import com.geoxp.GeoXPLib; /** * Extract the locations of a GTS and push them onto the stack. * * Only the ticks with actual values are returned */ public class LOCATIONS extends NamedWarpScriptFunction implements WarpScriptStackFunction { public LOCATIONS(String name) { super(name); } @Override public Object apply(WarpScriptStack stack) throws WarpScriptException { Object o = stack.pop(); if (!(o instanceof GeoTimeSerie)) { throw new WarpScriptException(getName() + " expects a geo time series on top of the stack."); } List<Object> latitudes = new ArrayList<Object>(); List<Object> longitudes = new ArrayList<Object>(); int nvalues = GTSHelper.nvalues((GeoTimeSerie) o); for (int i = 0; i < nvalues; i++) { long location = GTSHelper.locationAtIndex((GeoTimeSerie) o, i); if (GeoTimeSerie.NO_LOCATION == location) { latitudes.add(Double.NaN); longitudes.add(Double.NaN); } else { double[] latlon = GeoXPLib.fromGeoXPPoint(location); latitudes.add(latlon[0]); longitudes.add(latlon[1]); } } // TODO(tce): should return a list of 2 lists to be able to extend this class from GTSStackFunction. Or a zip of these lists. stack.push(latitudes); stack.push(longitudes); return stack; } }
apache-2.0
Apereo-Learning-Analytics-Initiative/Larissa
src/main/java/nl/uva/larissa/repository/VoidingTargetException.java
241
package nl.uva.larissa.repository; public class VoidingTargetException extends Exception { /** * */ private static final long serialVersionUID = 5092620357939696353L; public VoidingTargetException(String msg) { super(msg); } }
apache-2.0
bitjammer/swift
lib/IRGen/IRGenSIL.cpp
187592
//===--- IRGenSIL.cpp - Swift Per-Function IR Generation ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements basic setup and teardown for the class which // performs IR generation for function bodies. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "irgensil" #include "llvm/IR/Function.h" #include "llvm/IR/Module.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/InlineAsm.h" #include "llvm/IR/Intrinsics.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Support/Debug.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/TargetInfo.h" #include "swift/Basic/Range.h" #include "swift/Basic/STLExtras.h" #include "swift/AST/ASTContext.h" #include "swift/AST/IRGenOptions.h" #include "swift/AST/Pattern.h" #include "swift/AST/ParameterList.h" #include "swift/AST/SubstitutionMap.h" #include "swift/AST/Types.h" #include "swift/SIL/Dominance.h" #include "swift/SIL/PrettyStackTrace.h" #include "swift/SIL/SILDebugScope.h" #include "swift/SIL/SILDeclRef.h" #include "swift/SIL/SILLinkage.h" #include "swift/SIL/SILModule.h" #include "swift/SIL/SILType.h" #include "swift/SIL/SILVisitor.h" #include "swift/SIL/InstructionUtils.h" #include "clang/CodeGen/CodeGenABITypes.h" #include "CallEmission.h" #include "Explosion.h" #include "GenArchetype.h" #include "GenBuiltin.h" #include "GenCall.h" #include "GenCast.h" #include "GenClass.h" #include "GenConstant.h" #include "GenEnum.h" #include "GenExistential.h" #include "GenFunc.h" #include "GenHeap.h" #include "GenMeta.h" #include "GenObjC.h" #include "GenOpaque.h" #include "GenPoly.h" #include "GenProto.h" #include "GenStruct.h" #include "GenTuple.h" #include "GenType.h" #include "IRGenDebugInfo.h" #include "IRGenModule.h" #include "NativeConventionSchema.h" #include "ReferenceTypeInfo.h" #include "WeakTypeInfo.h" using namespace swift; using namespace irgen; namespace { class LoweredValue; /// Represents a statically-known function as a SIL thin function value. class StaticFunction { /// The function reference. llvm::Function *Function; ForeignFunctionInfo ForeignInfo; /// The function's native representation. SILFunctionTypeRepresentation Rep; public: StaticFunction(llvm::Function *function, ForeignFunctionInfo foreignInfo, SILFunctionTypeRepresentation rep) : Function(function), ForeignInfo(foreignInfo), Rep(rep) {} llvm::Function *getFunction() const { return Function; } SILFunctionTypeRepresentation getRepresentation() const { return Rep; } const ForeignFunctionInfo &getForeignInfo() const { return ForeignInfo; } llvm::Value *getExplosionValue(IRGenFunction &IGF) const; }; /// Represents a SIL value lowered to IR, in one of these forms: /// - an Address, corresponding to a SIL address value; /// - an Explosion of (unmanaged) Values, corresponding to a SIL "register"; or /// - a CallEmission for a partially-applied curried function or method. class LoweredValue { public: enum class Kind { /// The first two LoweredValue kinds correspond to a SIL address value. /// /// The LoweredValue of an existential alloc_stack keeps an owning container /// in addition to the address of the allocated buffer. /// Depending on the allocated type, the container may be equal to the /// buffer itself (for types with known sizes) or it may be the address /// of a fixed-size container which points to the heap-allocated buffer. /// In this case the address-part may be null, which means that the buffer /// is not allocated yet. ContainedAddress, /// The LoweredValue of a resilient, generic, or loadable typed alloc_stack /// keeps an optional stackrestore point in addition to the address of the /// allocated buffer. For all other address values the stackrestore point is /// just null. /// If the stackrestore point is set (currently, this might happen for /// opaque types: generic and resilient) the deallocation of the stack must /// reset the stack pointer to this point. Address, /// The following kinds correspond to SIL non-address values. Value_First, /// A normal value, represented as an exploded array of llvm Values. Explosion = Value_First, /// A @box together with the address of the box value. BoxWithAddress, /// A value that represents a statically-known function symbol that /// can be called directly, represented as a StaticFunction. StaticFunction, /// A value that represents an Objective-C method that must be called with /// a form of objc_msgSend. ObjCMethod, Value_Last = ObjCMethod, }; Kind kind; private: using ExplosionVector = SmallVector<llvm::Value *, 4>; union { ContainedAddress containedAddress; StackAddress address; OwnedAddress boxWithAddress; struct { ExplosionVector values; } explosion; StaticFunction staticFunction; ObjCMethod objcMethod; }; public: /// Create an address value without a stack restore point. LoweredValue(const Address &address) : kind(Kind::Address), address(address) {} /// Create an address value with an optional stack restore point. LoweredValue(const StackAddress &address) : kind(Kind::Address), address(address) {} enum ContainerForUnallocatedAddress_t { ContainerForUnallocatedAddress }; /// Create an address value for an alloc_stack, consisting of a container and /// a not yet allocated buffer. LoweredValue(const Address &container, ContainerForUnallocatedAddress_t) : kind(Kind::ContainedAddress), containedAddress(container, Address()) {} /// Create an address value for an alloc_stack, consisting of a container and /// the address of the allocated buffer. LoweredValue(const ContainedAddress &address) : kind(Kind::ContainedAddress), containedAddress(address) {} LoweredValue(StaticFunction &&staticFunction) : kind(Kind::StaticFunction), staticFunction(std::move(staticFunction)) {} LoweredValue(ObjCMethod &&objcMethod) : kind(Kind::ObjCMethod), objcMethod(std::move(objcMethod)) {} LoweredValue(Explosion &e) : kind(Kind::Explosion), explosion{{}} { auto Elts = e.claimAll(); explosion.values.append(Elts.begin(), Elts.end()); } LoweredValue(const OwnedAddress &boxWithAddress) : kind(Kind::BoxWithAddress), boxWithAddress(boxWithAddress) {} LoweredValue(LoweredValue &&lv) : kind(lv.kind) { switch (kind) { case Kind::ContainedAddress: ::new (&containedAddress) ContainedAddress(std::move(lv.containedAddress)); break; case Kind::Address: ::new (&address) StackAddress(std::move(lv.address)); break; case Kind::Explosion: ::new (&explosion.values) ExplosionVector(std::move(lv.explosion.values)); break; case Kind::BoxWithAddress: ::new (&boxWithAddress) OwnedAddress(std::move(lv.boxWithAddress)); break; case Kind::StaticFunction: ::new (&staticFunction) StaticFunction(std::move(lv.staticFunction)); break; case Kind::ObjCMethod: ::new (&objcMethod) ObjCMethod(std::move(lv.objcMethod)); break; } } LoweredValue &operator=(LoweredValue &&lv) { assert(this != &lv); this->~LoweredValue(); ::new (this) LoweredValue(std::move(lv)); return *this; } bool isAddress() const { return kind == Kind::Address && address.getAddress().isValid(); } bool isUnallocatedAddressInBuffer() const { return kind == Kind::ContainedAddress && !containedAddress.getAddress().isValid(); } bool isValue() const { return kind >= Kind::Value_First && kind <= Kind::Value_Last; } bool isBoxWithAddress() const { return kind == Kind::BoxWithAddress; } Address getAddress() const { assert(isAddress() && "not an allocated address"); return address.getAddress(); } StackAddress getStackAddress() const { assert(isAddress() && "not an allocated address"); return address; } Address getContainerOfAddress() const { assert(kind == Kind::ContainedAddress); assert(containedAddress.getContainer().isValid() && "address has no container"); return containedAddress.getContainer(); } Address getAddressInContainer() const { assert(kind == Kind::ContainedAddress); assert(containedAddress.getContainer().isValid() && "address has no container"); return containedAddress.getAddress(); } void getExplosion(IRGenFunction &IGF, Explosion &ex) const; Explosion getExplosion(IRGenFunction &IGF) const { Explosion e; getExplosion(IGF, e); return e; } Address getAddressOfBox() const { assert(kind == Kind::BoxWithAddress); return boxWithAddress.getAddress(); } llvm::Value *getSingletonExplosion(IRGenFunction &IGF) const; const StaticFunction &getStaticFunction() const { assert(kind == Kind::StaticFunction && "not a static function"); return staticFunction; } const ObjCMethod &getObjCMethod() const { assert(kind == Kind::ObjCMethod && "not an objc method"); return objcMethod; } ~LoweredValue() { switch (kind) { case Kind::Address: address.~StackAddress(); break; case Kind::ContainedAddress: containedAddress.~ContainedAddress(); break; case Kind::Explosion: explosion.values.~ExplosionVector(); break; case Kind::BoxWithAddress: boxWithAddress.~OwnedAddress(); break; case Kind::StaticFunction: staticFunction.~StaticFunction(); break; case Kind::ObjCMethod: objcMethod.~ObjCMethod(); break; } } }; using PHINodeVector = llvm::TinyPtrVector<llvm::PHINode*>; /// Represents a lowered SIL basic block. This keeps track /// of SIL branch arguments so that they can be lowered to LLVM phi nodes. struct LoweredBB { llvm::BasicBlock *bb; PHINodeVector phis; LoweredBB() = default; explicit LoweredBB(llvm::BasicBlock *bb, PHINodeVector &&phis) : bb(bb), phis(std::move(phis)) {} }; /// Visits a SIL Function and generates LLVM IR. class IRGenSILFunction : public IRGenFunction, public SILInstructionVisitor<IRGenSILFunction> { public: llvm::DenseMap<SILValue, LoweredValue> LoweredValues; llvm::DenseMap<SILType, LoweredValue> LoweredUndefs; /// All alloc_ref instructions which allocate the object on the stack. llvm::SmallPtrSet<SILInstruction *, 8> StackAllocs; /// With closure captures it is actually possible to have two function /// arguments that both have the same name. Until this is fixed, we need to /// also hash the ArgNo here. typedef std::pair<unsigned, std::pair<const SILDebugScope *, StringRef>> StackSlotKey; /// Keeps track of the mapping of source variables to -O0 shadow copy allocas. llvm::SmallDenseMap<StackSlotKey, Address, 8> ShadowStackSlots; llvm::SmallDenseMap<Decl *, SmallString<4>, 8> AnonymousVariables; /// To avoid inserting elements into ValueDomPoints twice. llvm::SmallDenseSet<llvm::Instruction *, 8> ValueVariables; /// Holds the DominancePoint of values that are storage for a source variable. SmallVector<std::pair<llvm::Instruction *, DominancePoint>, 8> ValueDomPoints; unsigned NumAnonVars = 0; unsigned NumCondFails = 0; /// Accumulative amount of allocated bytes on the stack. Used to limit the /// size for stack promoted objects. /// We calculate it on demand, so that we don't have to do it if the /// function does not have any stack promoted allocations. int EstimatedStackSize = -1; llvm::MapVector<SILBasicBlock *, LoweredBB> LoweredBBs; // Destination basic blocks for condfail traps. llvm::SmallVector<llvm::BasicBlock *, 8> FailBBs; SILFunction *CurSILFn; Address IndirectReturn; // A cached dominance analysis. std::unique_ptr<DominanceInfo> Dominance; IRGenSILFunction(IRGenModule &IGM, SILFunction *f); ~IRGenSILFunction(); /// Generate IR for the SIL Function. void emitSILFunction(); /// Calculates EstimatedStackSize. void estimateStackSize(); void setLoweredValue(SILValue v, LoweredValue &&lv) { auto inserted = LoweredValues.insert({v, std::move(lv)}); assert(inserted.second && "already had lowered value for sil value?!"); (void)inserted; } /// Create a new Address corresponding to the given SIL address value. void setLoweredAddress(SILValue v, const Address &address) { assert(v->getType().isAddress() && "address for non-address value?!"); setLoweredValue(v, address); } void setLoweredStackAddress(SILValue v, const StackAddress &address) { assert(v->getType().isAddress() && "address for non-address value?!"); setLoweredValue(v, address); } void setContainerOfUnallocatedAddress(SILValue v, const Address &buffer) { assert(v->getType().isAddress() && "address for non-address value?!"); setLoweredValue(v, LoweredValue(buffer, LoweredValue::ContainerForUnallocatedAddress)); } void overwriteAllocatedAddress(SILValue v, const Address &address) { assert(v->getType().isAddress() && "address for non-address value?!"); auto it = LoweredValues.find(v); assert(it != LoweredValues.end() && "no existing entry for overwrite?"); assert(it->second.isUnallocatedAddressInBuffer() && "not an unallocated address"); it->second = ContainedAddress(it->second.getContainerOfAddress(), address); } void setAllocatedAddressForBuffer(SILValue v, const Address &allocedAddress); /// Create a new Explosion corresponding to the given SIL value. void setLoweredExplosion(SILValue v, Explosion &e) { assert(v->getType().isObject() && "explosion for address value?!"); setLoweredValue(v, LoweredValue(e)); } void setLoweredBox(SILValue v, const OwnedAddress &box) { assert(v->getType().isObject() && "box for address value?!"); setLoweredValue(v, LoweredValue(box)); } /// Create a new StaticFunction corresponding to the given SIL value. void setLoweredStaticFunction(SILValue v, llvm::Function *f, SILFunctionTypeRepresentation rep, ForeignFunctionInfo foreignInfo) { assert(v->getType().isObject() && "function for address value?!"); assert(v->getType().is<SILFunctionType>() && "function for non-function value?!"); setLoweredValue(v, StaticFunction{f, foreignInfo, rep}); } /// Create a new Objective-C method corresponding to the given SIL value. void setLoweredObjCMethod(SILValue v, SILDeclRef method) { assert(v->getType().isObject() && "function for address value?!"); assert(v->getType().is<SILFunctionType>() && "function for non-function value?!"); setLoweredValue(v, ObjCMethod{method, SILType(), false}); } /// Create a new Objective-C method corresponding to the given SIL value that /// starts its search from the given search type. /// /// Unlike \c setLoweredObjCMethod, which finds the method in the actual /// runtime type of the object, this routine starts at the static type of the /// object and searches up the class hierarchy (toward superclasses). /// /// \param searchType The class from which the Objective-C runtime will start /// its search for a method. /// /// \param startAtSuper Whether we want to start at the superclass of the /// static type (vs. the static type itself). void setLoweredObjCMethodBounded(SILValue v, SILDeclRef method, SILType searchType, bool startAtSuper) { assert(v->getType().isObject() && "function for address value?!"); assert(v->getType().is<SILFunctionType>() && "function for non-function value?!"); setLoweredValue(v, ObjCMethod{method, searchType, startAtSuper}); } LoweredValue &getUndefLoweredValue(SILType t) { auto found = LoweredUndefs.find(t); if (found != LoweredUndefs.end()) return found->second; auto &ti = getTypeInfo(t); switch (t.getCategory()) { case SILValueCategory::Address: { Address undefAddr = ti.getAddressForPointer( llvm::UndefValue::get(ti.getStorageType()->getPointerTo())); LoweredUndefs.insert({t, LoweredValue(undefAddr)}); break; } case SILValueCategory::Object: { auto schema = ti.getSchema(); Explosion e; for (auto &elt : schema) { assert(!elt.isAggregate() && "non-scalar element in loadable type schema?!"); e.add(llvm::UndefValue::get(elt.getScalarType())); } LoweredUndefs.insert({t, LoweredValue(e)}); break; } } found = LoweredUndefs.find(t); assert(found != LoweredUndefs.end()); return found->second; } /// Get the LoweredValue corresponding to the given SIL value, which must /// have been lowered. LoweredValue &getLoweredValue(SILValue v) { if (isa<SILUndef>(v)) return getUndefLoweredValue(v->getType()); auto foundValue = LoweredValues.find(v); assert(foundValue != LoweredValues.end() && "no lowered explosion for sil value!"); return foundValue->second; } /// Get the Address of a SIL value of address type, which must have been /// lowered. Address getLoweredAddress(SILValue v) { if (getLoweredValue(v).kind == LoweredValue::Kind::Address) return getLoweredValue(v).getAddress(); else return getLoweredValue(v).getAddressInContainer(); } StackAddress getLoweredStackAddress(SILValue v) { return getLoweredValue(v).getStackAddress(); } /// Add the unmanaged LLVM values lowered from a SIL value to an explosion. void getLoweredExplosion(SILValue v, Explosion &e) { getLoweredValue(v).getExplosion(*this, e); } /// Create an Explosion containing the unmanaged LLVM values lowered from a /// SIL value. Explosion getLoweredExplosion(SILValue v) { return getLoweredValue(v).getExplosion(*this); } /// Return the single member of the lowered explosion for the /// given SIL value. llvm::Value *getLoweredSingletonExplosion(SILValue v) { return getLoweredValue(v).getSingletonExplosion(*this); } LoweredBB &getLoweredBB(SILBasicBlock *bb) { auto foundBB = LoweredBBs.find(bb); assert(foundBB != LoweredBBs.end() && "no llvm bb for sil bb?!"); return foundBB->second; } StringRef getOrCreateAnonymousVarName(VarDecl *Decl) { llvm::SmallString<4> &Name = AnonymousVariables[Decl]; if (Name.empty()) { { llvm::raw_svector_ostream S(Name); S << '_' << NumAnonVars++; } AnonymousVariables.insert({Decl, Name}); } return Name; } template <class DebugVarCarryingInst> StringRef getVarName(DebugVarCarryingInst *i) { StringRef Name = i->getVarInfo().Name; // The $match variables generated by the type checker are not // guaranteed to be unique within their scope, but they have // unique VarDecls. if ((Name.empty() || Name == "$match") && i->getDecl()) return getOrCreateAnonymousVarName(i->getDecl()); return Name; } /// At -Onone, forcibly keep all LLVM values that are tracked by /// debug variables alive by inserting an empty inline assembler /// expression depending on the value in the blocks dominated by the /// value. void emitDebugVariableRangeExtension(const SILBasicBlock *CurBB) { if (IGM.IRGen.Opts.Optimize) return; for (auto &Variable : ValueDomPoints) { auto VarDominancePoint = Variable.second; llvm::Value *Storage = Variable.first; if (getActiveDominancePoint() == VarDominancePoint || isActiveDominancePointDominatedBy(VarDominancePoint)) { llvm::Type *ArgTys; auto *Ty = Storage->getType(); // Vectors, Pointers and Floats are expected to fit into a register. if (Ty->isPointerTy() || Ty->isFloatingPointTy() || Ty->isVectorTy()) ArgTys = { Ty }; else { // If this is not a scalar or vector type, we can't handle it. if (isa<llvm::CompositeType>(Ty)) continue; // The storage is guaranteed to be no larger than the register width. // Extend the storage so it would fit into a register. llvm::Type *IntTy; switch (IGM.getClangASTContext().getTargetInfo().getRegisterWidth()) { case 64: IntTy = IGM.Int64Ty; break; case 32: IntTy = IGM.Int32Ty; break; default: llvm_unreachable("unsupported register width"); } ArgTys = { IntTy }; Storage = Builder.CreateZExtOrBitCast(Storage, IntTy); } // Emit an empty inline assembler expression depending on the register. auto *AsmFnTy = llvm::FunctionType::get(IGM.VoidTy, ArgTys, false); auto *InlineAsm = llvm::InlineAsm::get(AsmFnTy, "", "r", true); Builder.CreateCall(InlineAsm, Storage); // Propagate the dbg.value intrinsics into the later basic blocks. Note // that this shouldn't be necessary. LiveDebugValues should be doing // this but can't in general because it currently only tracks register // locations. llvm::Instruction *Value = Variable.first; auto It = llvm::BasicBlock::iterator(Value); auto *BB = Value->getParent(); auto *CurBB = Builder.GetInsertBlock(); if (BB != CurBB) for (auto I = std::next(It), E = BB->end(); I != E; ++I) { auto *DVI = dyn_cast<llvm::DbgValueInst>(I); if (DVI && DVI->getValue() == Value) IGM.DebugInfo->getBuilder().insertDbgValueIntrinsic( DVI->getValue(), 0, DVI->getVariable(), DVI->getExpression(), DVI->getDebugLoc(), &*CurBB->getFirstInsertionPt()); else // Found all dbg.value intrinsics describing this location. break; } } } } /// Account for bugs in LLVM. /// /// - The LLVM type legalizer currently doesn't update debug /// intrinsics when a large value is split up into smaller /// pieces. Note that this heuristic as a bit too conservative /// on 32-bit targets as it will also fire for doubles. /// /// - CodeGen Prepare may drop dbg.values pointing to PHI instruction. bool needsShadowCopy(llvm::Value *Storage) { return (IGM.DataLayout.getTypeSizeInBits(Storage->getType()) > IGM.getClangASTContext().getTargetInfo().getRegisterWidth()) || isa<llvm::PHINode>(Storage); } /// At -Onone, emit a shadow copy of an Address in an alloca, so the /// register allocator doesn't elide the dbg.value intrinsic when /// register pressure is high. There is a trade-off to this: With /// shadow copies, we lose the precise lifetime. llvm::Value *emitShadowCopy(llvm::Value *Storage, const SILDebugScope *Scope, StringRef Name, unsigned ArgNo, Alignment Align = Alignment(0)) { auto Ty = Storage->getType(); // Never emit shadow copies when optimizing, or if already on the stack. if (IGM.IRGen.Opts.Optimize || isa<llvm::AllocaInst>(Storage) || isa<llvm::UndefValue>(Storage) || Ty == IGM.RefCountedPtrTy) // No debug info is emitted for refcounts. return Storage; // Always emit shadow copies for function arguments. if (ArgNo == 0) // Otherwise only if debug value range extension is not feasible. if (!needsShadowCopy(Storage)) { // Mark for debug value range extension unless this is a constant. if (auto *Value = dyn_cast<llvm::Instruction>(Storage)) if (ValueVariables.insert(Value).second) ValueDomPoints.push_back({Value, getActiveDominancePoint()}); return Storage; } if (Align.isZero()) Align = IGM.getPointerAlignment(); auto &Alloca = ShadowStackSlots[{ArgNo, {Scope, Name}}]; if (!Alloca.isValid()) Alloca = createAlloca(Ty, Align, Name+".addr"); ArtificialLocation AutoRestore(getDebugScope(), IGM.DebugInfo, Builder); Builder.CreateStore(Storage, Alloca.getAddress(), Align); return Alloca.getAddress(); } llvm::Value *emitShadowCopy(Address Storage, const SILDebugScope *Scope, StringRef Name, unsigned ArgNo) { return emitShadowCopy(Storage.getAddress(), Scope, Name, ArgNo, Storage.getAlignment()); } void emitShadowCopy(ArrayRef<llvm::Value *> vals, const SILDebugScope *Scope, StringRef Name, unsigned ArgNo, llvm::SmallVectorImpl<llvm::Value *> &copy) { // Only do this at -O0. if (IGM.IRGen.Opts.Optimize) { copy.append(vals.begin(), vals.end()); return; } // Single or empty values. if (vals.size() <= 1) { for (auto val : vals) copy.push_back(emitShadowCopy(val, Scope, Name, ArgNo)); return; } // Create a single aggregate alloca for explosions. // TODO: why are we doing this instead of using the TypeInfo? llvm::StructType *aggregateType = [&] { SmallVector<llvm::Type *, 8> eltTypes; for (auto val : vals) eltTypes.push_back(val->getType()); return llvm::StructType::get(IGM.LLVMContext, eltTypes); }(); auto layout = IGM.DataLayout.getStructLayout(aggregateType); Alignment align(layout->getAlignment()); auto alloca = createAlloca(aggregateType, align, Name + ".debug"); ArtificialLocation AutoRestore(getDebugScope(), IGM.DebugInfo, Builder); size_t i = 0; for (auto val : vals) { auto addr = Builder.CreateStructGEP(alloca, i, Size(layout->getElementOffset(i))); Builder.CreateStore(val, addr); i++; } copy.push_back(alloca.getAddress()); } /// Determine whether a generic variable has been inlined. static bool isInlinedGeneric(VarDecl *VarDecl, const SILDebugScope *DS) { if (!DS->InlinedCallSite) return false; if (VarDecl->hasType()) return VarDecl->getType()->hasArchetype(); return VarDecl->getInterfaceType()->hasTypeParameter(); } /// Emit debug info for a function argument or a local variable. template <typename StorageType> void emitDebugVariableDeclaration(StorageType Storage, DebugTypeInfo Ty, SILType SILTy, const SILDebugScope *DS, VarDecl *VarDecl, StringRef Name, unsigned ArgNo = 0, IndirectionKind Indirection = DirectValue) { // Force all archetypes referenced by the type to be bound by this point. // TODO: just make sure that we have a path to them that the debug info // can follow. // FIXME: The debug info type of all inlined instances of a variable must be // the same as the type of the abstract variable. if (isInlinedGeneric(VarDecl, DS)) return; auto runtimeTy = getRuntimeReifiedType(IGM, Ty.getType()->getCanonicalType()); if (!IGM.IRGen.Opts.Optimize && runtimeTy->hasArchetype()) runtimeTy.visit([&](CanType t) { if (auto archetype = dyn_cast<ArchetypeType>(t)) emitTypeMetadataRef(archetype); }); assert(IGM.DebugInfo && "debug info not enabled"); if (ArgNo) { PrologueLocation AutoRestore(IGM.DebugInfo, Builder); IGM.DebugInfo->emitVariableDeclaration(Builder, Storage, Ty, DS, VarDecl, Name, ArgNo, Indirection); } else IGM.DebugInfo->emitVariableDeclaration(Builder, Storage, Ty, DS, VarDecl, Name, 0, Indirection); } void emitFailBB() { if (!FailBBs.empty()) { // Move the trap basic blocks to the end of the function. for (auto *FailBB : FailBBs) { auto &BlockList = CurFn->getBasicBlockList(); BlockList.splice(BlockList.end(), BlockList, FailBB); } } } //===--------------------------------------------------------------------===// // SIL instruction lowering //===--------------------------------------------------------------------===// void visitSILBasicBlock(SILBasicBlock *BB); void emitErrorResultVar(SILResultInfo ErrorInfo, DebugValueInst *DbgValue); void emitDebugInfoForAllocStack(AllocStackInst *i, const TypeInfo &type, llvm::Value *addr); void visitAllocStackInst(AllocStackInst *i); void visitAllocRefInst(AllocRefInst *i); void visitAllocRefDynamicInst(AllocRefDynamicInst *i); void visitAllocBoxInst(AllocBoxInst *i); void visitProjectBoxInst(ProjectBoxInst *i); void visitApplyInst(ApplyInst *i); void visitTryApplyInst(TryApplyInst *i); void visitFullApplySite(FullApplySite i); void visitPartialApplyInst(PartialApplyInst *i); void visitBuiltinInst(BuiltinInst *i); void visitFunctionRefInst(FunctionRefInst *i); void visitAllocGlobalInst(AllocGlobalInst *i); void visitGlobalAddrInst(GlobalAddrInst *i); void visitIntegerLiteralInst(IntegerLiteralInst *i); void visitFloatLiteralInst(FloatLiteralInst *i); void visitStringLiteralInst(StringLiteralInst *i); void visitLoadInst(LoadInst *i); void visitStoreInst(StoreInst *i); void visitAssignInst(AssignInst *i) { llvm_unreachable("assign is not valid in canonical SIL"); } void visitMarkUninitializedInst(MarkUninitializedInst *i) { llvm_unreachable("mark_uninitialized is not valid in canonical SIL"); } void visitMarkUninitializedBehaviorInst(MarkUninitializedBehaviorInst *i) { llvm_unreachable("mark_uninitialized_behavior is not valid in canonical SIL"); } void visitMarkFunctionEscapeInst(MarkFunctionEscapeInst *i) { llvm_unreachable("mark_function_escape is not valid in canonical SIL"); } void visitLoadBorrowInst(LoadBorrowInst *i) { llvm_unreachable("unimplemented"); } void visitDebugValueInst(DebugValueInst *i); void visitDebugValueAddrInst(DebugValueAddrInst *i); void visitLoadWeakInst(LoadWeakInst *i); void visitStoreWeakInst(StoreWeakInst *i); void visitRetainValueInst(RetainValueInst *i); void visitCopyValueInst(CopyValueInst *i); void visitCopyUnownedValueInst(CopyUnownedValueInst *i) { llvm_unreachable("unimplemented"); } void visitReleaseValueInst(ReleaseValueInst *i); void visitDestroyValueInst(DestroyValueInst *i); void visitAutoreleaseValueInst(AutoreleaseValueInst *i); void visitSetDeallocatingInst(SetDeallocatingInst *i); void visitStructInst(StructInst *i); void visitTupleInst(TupleInst *i); void visitEnumInst(EnumInst *i); void visitInitEnumDataAddrInst(InitEnumDataAddrInst *i); void visitSelectEnumInst(SelectEnumInst *i); void visitSelectEnumAddrInst(SelectEnumAddrInst *i); void visitSelectValueInst(SelectValueInst *i); void visitUncheckedEnumDataInst(UncheckedEnumDataInst *i); void visitUncheckedTakeEnumDataAddrInst(UncheckedTakeEnumDataAddrInst *i); void visitInjectEnumAddrInst(InjectEnumAddrInst *i); void visitObjCProtocolInst(ObjCProtocolInst *i); void visitMetatypeInst(MetatypeInst *i); void visitValueMetatypeInst(ValueMetatypeInst *i); void visitExistentialMetatypeInst(ExistentialMetatypeInst *i); void visitTupleExtractInst(TupleExtractInst *i); void visitTupleElementAddrInst(TupleElementAddrInst *i); void visitStructExtractInst(StructExtractInst *i); void visitStructElementAddrInst(StructElementAddrInst *i); void visitRefElementAddrInst(RefElementAddrInst *i); void visitRefTailAddrInst(RefTailAddrInst *i); void visitClassMethodInst(ClassMethodInst *i); void visitSuperMethodInst(SuperMethodInst *i); void visitWitnessMethodInst(WitnessMethodInst *i); void visitDynamicMethodInst(DynamicMethodInst *i); void visitAllocValueBufferInst(AllocValueBufferInst *i); void visitProjectValueBufferInst(ProjectValueBufferInst *i); void visitDeallocValueBufferInst(DeallocValueBufferInst *i); void visitOpenExistentialAddrInst(OpenExistentialAddrInst *i); void visitOpenExistentialMetatypeInst(OpenExistentialMetatypeInst *i); void visitOpenExistentialRefInst(OpenExistentialRefInst *i); void visitOpenExistentialOpaqueInst(OpenExistentialOpaqueInst *i); void visitInitExistentialAddrInst(InitExistentialAddrInst *i); void visitInitExistentialOpaqueInst(InitExistentialOpaqueInst *i); void visitInitExistentialMetatypeInst(InitExistentialMetatypeInst *i); void visitInitExistentialRefInst(InitExistentialRefInst *i); void visitDeinitExistentialAddrInst(DeinitExistentialAddrInst *i); void visitDeinitExistentialOpaqueInst(DeinitExistentialOpaqueInst *i); void visitAllocExistentialBoxInst(AllocExistentialBoxInst *i); void visitOpenExistentialBoxInst(OpenExistentialBoxInst *i); void visitProjectExistentialBoxInst(ProjectExistentialBoxInst *i); void visitDeallocExistentialBoxInst(DeallocExistentialBoxInst *i); void visitProjectBlockStorageInst(ProjectBlockStorageInst *i); void visitInitBlockStorageHeaderInst(InitBlockStorageHeaderInst *i); void visitFixLifetimeInst(FixLifetimeInst *i); void visitEndLifetimeInst(EndLifetimeInst *i) { llvm_unreachable("unimplemented"); } void visitUncheckedOwnershipConversionInst(UncheckedOwnershipConversionInst *i) { llvm_unreachable("unimplemented"); } void visitBeginBorrowInst(BeginBorrowInst *i) { llvm_unreachable("unimplemented"); } void visitEndBorrowInst(EndBorrowInst *i) { llvm_unreachable("unimplemented"); } void visitEndBorrowArgumentInst(EndBorrowArgumentInst *i) { llvm_unreachable("unimplemented"); } void visitStoreBorrowInst(StoreBorrowInst *i) { llvm_unreachable("unimplemented"); } void visitBeginAccessInst(BeginAccessInst *i); void visitEndAccessInst(EndAccessInst *i); void visitUnmanagedRetainValueInst(UnmanagedRetainValueInst *i) { llvm_unreachable("unimplemented"); } void visitUnmanagedReleaseValueInst(UnmanagedReleaseValueInst *i) { llvm_unreachable("unimplemented"); } void visitUnmanagedAutoreleaseValueInst(UnmanagedAutoreleaseValueInst *i) { llvm_unreachable("unimplemented"); } void visitMarkDependenceInst(MarkDependenceInst *i); void visitCopyBlockInst(CopyBlockInst *i); void visitStrongPinInst(StrongPinInst *i); void visitStrongUnpinInst(StrongUnpinInst *i); void visitStrongRetainInst(StrongRetainInst *i); void visitStrongReleaseInst(StrongReleaseInst *i); void visitStrongRetainUnownedInst(StrongRetainUnownedInst *i); void visitUnownedRetainInst(UnownedRetainInst *i); void visitUnownedReleaseInst(UnownedReleaseInst *i); void visitLoadUnownedInst(LoadUnownedInst *i); void visitStoreUnownedInst(StoreUnownedInst *i); void visitIsUniqueInst(IsUniqueInst *i); void visitIsUniqueOrPinnedInst(IsUniqueOrPinnedInst *i); void visitDeallocStackInst(DeallocStackInst *i); void visitDeallocBoxInst(DeallocBoxInst *i); void visitDeallocRefInst(DeallocRefInst *i); void visitDeallocPartialRefInst(DeallocPartialRefInst *i); void visitCopyAddrInst(CopyAddrInst *i); void visitDestroyAddrInst(DestroyAddrInst *i); void visitBindMemoryInst(BindMemoryInst *i); void visitCondFailInst(CondFailInst *i); void visitConvertFunctionInst(ConvertFunctionInst *i); void visitThinFunctionToPointerInst(ThinFunctionToPointerInst *i); void visitPointerToThinFunctionInst(PointerToThinFunctionInst *i); void visitUpcastInst(UpcastInst *i); void visitAddressToPointerInst(AddressToPointerInst *i); void visitPointerToAddressInst(PointerToAddressInst *i); void visitUncheckedRefCastInst(UncheckedRefCastInst *i); void visitUncheckedRefCastAddrInst(UncheckedRefCastAddrInst *i); void visitUncheckedAddrCastInst(UncheckedAddrCastInst *i); void visitUncheckedTrivialBitCastInst(UncheckedTrivialBitCastInst *i); void visitUncheckedBitwiseCastInst(UncheckedBitwiseCastInst *i); void visitRefToRawPointerInst(RefToRawPointerInst *i); void visitRawPointerToRefInst(RawPointerToRefInst *i); void visitRefToUnownedInst(RefToUnownedInst *i); void visitUnownedToRefInst(UnownedToRefInst *i); void visitRefToUnmanagedInst(RefToUnmanagedInst *i); void visitUnmanagedToRefInst(UnmanagedToRefInst *i); void visitThinToThickFunctionInst(ThinToThickFunctionInst *i); void visitThickToObjCMetatypeInst(ThickToObjCMetatypeInst *i); void visitObjCToThickMetatypeInst(ObjCToThickMetatypeInst *i); void visitUnconditionalCheckedCastInst(UnconditionalCheckedCastInst *i); void visitUnconditionalCheckedCastAddrInst(UnconditionalCheckedCastAddrInst *i); void visitUnconditionalCheckedCastValueInst(UnconditionalCheckedCastValueInst *i); void visitObjCMetatypeToObjectInst(ObjCMetatypeToObjectInst *i); void visitObjCExistentialMetatypeToObjectInst( ObjCExistentialMetatypeToObjectInst *i); void visitRefToBridgeObjectInst(RefToBridgeObjectInst *i); void visitBridgeObjectToRefInst(BridgeObjectToRefInst *i); void visitBridgeObjectToWordInst(BridgeObjectToWordInst *i); void visitIsNonnullInst(IsNonnullInst *i); void visitIndexAddrInst(IndexAddrInst *i); void visitTailAddrInst(TailAddrInst *i); void visitIndexRawPointerInst(IndexRawPointerInst *i); void visitUnreachableInst(UnreachableInst *i); void visitBranchInst(BranchInst *i); void visitCondBranchInst(CondBranchInst *i); void visitReturnInst(ReturnInst *i); void visitThrowInst(ThrowInst *i); void visitSwitchValueInst(SwitchValueInst *i); void visitSwitchEnumInst(SwitchEnumInst *i); void visitSwitchEnumAddrInst(SwitchEnumAddrInst *i); void visitDynamicMethodBranchInst(DynamicMethodBranchInst *i); void visitCheckedCastBranchInst(CheckedCastBranchInst *i); void visitCheckedCastValueBranchInst(CheckedCastValueBranchInst *i); void visitCheckedCastAddrBranchInst(CheckedCastAddrBranchInst *i); }; } // end anonymous namespace llvm::Value *StaticFunction::getExplosionValue(IRGenFunction &IGF) const { return IGF.Builder.CreateBitCast(Function, IGF.IGM.Int8PtrTy); } void LoweredValue::getExplosion(IRGenFunction &IGF, Explosion &ex) const { switch (kind) { case Kind::Address: case Kind::ContainedAddress: llvm_unreachable("not a value"); case Kind::Explosion: for (auto *value : explosion.values) ex.add(value); break; case Kind::BoxWithAddress: ex.add(boxWithAddress.getOwner()); break; case Kind::StaticFunction: ex.add(staticFunction.getExplosionValue(IGF)); break; case Kind::ObjCMethod: ex.add(objcMethod.getExplosionValue(IGF)); break; } } llvm::Value *LoweredValue::getSingletonExplosion(IRGenFunction &IGF) const { switch (kind) { case Kind::Address: case Kind::ContainedAddress: llvm_unreachable("not a value"); case Kind::Explosion: assert(explosion.values.size() == 1); return explosion.values[0]; case Kind::BoxWithAddress: return boxWithAddress.getOwner(); case Kind::StaticFunction: return staticFunction.getExplosionValue(IGF); case Kind::ObjCMethod: return objcMethod.getExplosionValue(IGF); } llvm_unreachable("bad lowered value kind!"); } IRGenSILFunction::IRGenSILFunction(IRGenModule &IGM, SILFunction *f) : IRGenFunction(IGM, IGM.getAddrOfSILFunction(f, ForDefinition), f->getDebugScope(), f->getLocation()), CurSILFn(f) { // Apply sanitizer attributes to the function. // TODO: Check if the function is ASan black listed either in the external // file or via annotations. if (IGM.IRGen.Opts.Sanitize == SanitizerKind::Address) CurFn->addFnAttr(llvm::Attribute::SanitizeAddress); if (IGM.IRGen.Opts.Sanitize == SanitizerKind::Thread) { if (dyn_cast_or_null<DestructorDecl>(f->getDeclContext())) // Do not report races in deinit and anything called from it // because TSan does not observe synchronization between retain // count dropping to '0' and the object deinitialization. CurFn->addFnAttr("sanitize_thread_no_checking_at_run_time"); else CurFn->addFnAttr(llvm::Attribute::SanitizeThread); } } IRGenSILFunction::~IRGenSILFunction() { assert(Builder.hasPostTerminatorIP() && "did not terminate BB?!"); // Emit the fail BB if we have one. if (!FailBBs.empty()) emitFailBB(); DEBUG(CurFn->print(llvm::dbgs())); } template<typename ValueVector> static void emitPHINodesForType(IRGenSILFunction &IGF, SILType type, const TypeInfo &ti, unsigned predecessors, ValueVector &phis) { if (type.isAddress()) { phis.push_back(IGF.Builder.CreatePHI(ti.getStorageType()->getPointerTo(), predecessors)); } else { // PHIs are always emitted with maximal explosion. ExplosionSchema schema = ti.getSchema(); for (auto &elt : schema) { if (elt.isScalar()) phis.push_back( IGF.Builder.CreatePHI(elt.getScalarType(), predecessors)); else phis.push_back( IGF.Builder.CreatePHI(elt.getAggregateType()->getPointerTo(), predecessors)); } } } static PHINodeVector emitPHINodesForBBArgs(IRGenSILFunction &IGF, SILBasicBlock *silBB, llvm::BasicBlock *llBB) { PHINodeVector phis; unsigned predecessors = std::distance(silBB->pred_begin(), silBB->pred_end()); IGF.Builder.SetInsertPoint(llBB); if (IGF.IGM.DebugInfo) { // Use the location of the first instruction in the basic block // for the φ-nodes. if (!silBB->empty()) { SILInstruction &I = *silBB->begin(); auto DS = I.getDebugScope(); assert(DS); IGF.IGM.DebugInfo->setCurrentLoc(IGF.Builder, DS, I.getLoc()); } } for (SILArgument *arg : make_range(silBB->args_begin(), silBB->args_end())) { size_t first = phis.size(); const TypeInfo &ti = IGF.getTypeInfo(arg->getType()); emitPHINodesForType(IGF, arg->getType(), ti, predecessors, phis); if (arg->getType().isAddress()) { IGF.setLoweredAddress(arg, ti.getAddressForPointer(phis.back())); } else { Explosion argValue; for (llvm::PHINode *phi : swift::make_range(phis.begin()+first, phis.end())) argValue.add(phi); IGF.setLoweredExplosion(arg, argValue); } } // Since we return to the entry of the function, reset the location. if (IGF.IGM.DebugInfo) IGF.IGM.DebugInfo->clearLoc(IGF.Builder); return phis; } static void addIncomingExplosionToPHINodes(IRGenSILFunction &IGF, LoweredBB &lbb, unsigned &phiIndex, Explosion &argValue); // TODO: Handle this during SIL AddressLowering. static ArrayRef<SILArgument*> emitEntryPointIndirectReturn( IRGenSILFunction &IGF, SILBasicBlock *entry, Explosion &params, CanSILFunctionType funcTy, llvm::function_ref<bool(SILType)> requiresIndirectResult) { // Map an indirect return for a type SIL considers loadable but still // requires an indirect return at the IR level. SILFunctionConventions fnConv(funcTy, IGF.getSILModule()); SILType directResultType = IGF.CurSILFn->mapTypeIntoContext(fnConv.getSILResultType()); if (requiresIndirectResult(directResultType)) { auto &retTI = IGF.IGM.getTypeInfo(directResultType); IGF.IndirectReturn = retTI.getAddressForPointer(params.claimNext()); } auto bbargs = entry->getArguments(); // Map the indirect returns if present. unsigned numIndirectResults = fnConv.getNumIndirectSILResults(); for (unsigned i = 0; i != numIndirectResults; ++i) { SILArgument *ret = bbargs[i]; auto &retTI = IGF.IGM.getTypeInfo(ret->getType()); IGF.setLoweredAddress(ret, retTI.getAddressForPointer(params.claimNext())); } return bbargs.slice(numIndirectResults); } static void bindParameter(IRGenSILFunction &IGF, SILArgument *param, Explosion &allParamValues) { // Pull out the parameter value and its formal type. auto &paramTI = IGF.getTypeInfo(param->getType()); // If the SIL parameter isn't passed indirectly, we need to map it // to an explosion. if (param->getType().isObject()) { Explosion paramValues; auto &loadableTI = cast<LoadableTypeInfo>(paramTI); // If the explosion must be passed indirectly, load the value from the // indirect address. auto &nativeSchema = paramTI.nativeParameterValueSchema(IGF.IGM); if (nativeSchema.requiresIndirect()) { Address paramAddr = loadableTI.getAddressForPointer(allParamValues.claimNext()); loadableTI.loadAsTake(IGF, paramAddr, paramValues); } else { if (!nativeSchema.empty()) { // Otherwise, we map from the native convention to the type's explosion // schema. Explosion nativeParam; allParamValues.transferInto(nativeParam, nativeSchema.size()); paramValues = nativeSchema.mapFromNative(IGF.IGM, IGF, nativeParam, param->getType()); } else { assert(paramTI.getSchema().empty()); } } IGF.setLoweredExplosion(param, paramValues); return; } // Okay, the type is passed indirectly in SIL, so we need to map // it to an address. // FIXME: that doesn't mean we should physically pass it // indirectly at this resilience expansion. An @in or @in_guaranteed parameter // could be passed by value in the right resilience domain. Address paramAddr = paramTI.getAddressForPointer(allParamValues.claimNext()); IGF.setLoweredAddress(param, paramAddr); } /// Emit entry point arguments for a SILFunction with the Swift calling /// convention. static void emitEntryPointArgumentsNativeCC(IRGenSILFunction &IGF, SILBasicBlock *entry, Explosion &allParamValues) { auto funcTy = IGF.CurSILFn->getLoweredFunctionType(); // Map the indirect return if present. ArrayRef<SILArgument *> params = emitEntryPointIndirectReturn( IGF, entry, allParamValues, funcTy, [&](SILType retType) -> bool { auto &schema = IGF.IGM.getTypeInfo(retType).nativeReturnValueSchema(IGF.IGM); return schema.requiresIndirect(); }); // The witness method CC passes Self as a final argument. WitnessMetadata witnessMetadata; if (funcTy->getRepresentation() == SILFunctionTypeRepresentation::WitnessMethod) { collectTrailingWitnessMetadata(IGF, *IGF.CurSILFn, allParamValues, witnessMetadata); } // Bind the error result by popping it off the parameter list. if (funcTy->hasErrorResult()) { IGF.setErrorResultSlot(allParamValues.takeLast()); } // The 'self' argument might be in the context position, which is // now the end of the parameter list. Bind it now. if (funcTy->hasSelfParam() && isSelfContextParameter(funcTy->getSelfParameter())) { SILArgument *selfParam = params.back(); params = params.drop_back(); Explosion selfTemp; selfTemp.add(allParamValues.takeLast()); bindParameter(IGF, selfParam, selfTemp); // Even if we don't have a 'self', if we have an error result, we // should have a placeholder argument here. } else if (funcTy->hasErrorResult() || funcTy->getRepresentation() == SILFunctionTypeRepresentation::Thick) { llvm::Value *contextPtr = allParamValues.takeLast(); (void) contextPtr; assert(contextPtr->getType() == IGF.IGM.RefCountedPtrTy); } // Map the remaining SIL parameters to LLVM parameters. for (SILArgument *param : params) { bindParameter(IGF, param, allParamValues); } // Bind polymorphic arguments. This can only be done after binding // all the value parameters. if (hasPolymorphicParameters(funcTy)) { emitPolymorphicParameters(IGF, *IGF.CurSILFn, allParamValues, &witnessMetadata, [&](unsigned paramIndex) -> llvm::Value* { SILValue parameter = IGF.CurSILFn->getArgumentsWithoutIndirectResults()[paramIndex]; return IGF.getLoweredSingletonExplosion(parameter); }); } assert(allParamValues.empty() && "didn't claim all parameters!"); } /// Emit entry point arguments for the parameters of a C function, or the /// method parameters of an ObjC method. static void emitEntryPointArgumentsCOrObjC(IRGenSILFunction &IGF, SILBasicBlock *entry, Explosion &params, CanSILFunctionType funcTy) { // First, lower the method type. ForeignFunctionInfo foreignInfo = IGF.IGM.getForeignFunctionInfo(funcTy); assert(foreignInfo.ClangInfo); auto &FI = *foreignInfo.ClangInfo; // Okay, start processing the parameters explosion. // First, claim all the indirect results. ArrayRef<SILArgument*> args = emitEntryPointIndirectReturn(IGF, entry, params, funcTy, [&](SILType directResultType) -> bool { return FI.getReturnInfo().isIndirect(); }); unsigned nextArgTyIdx = 0; // Handle the arguments of an ObjC method. if (IGF.CurSILFn->getRepresentation() == SILFunctionTypeRepresentation::ObjCMethod) { // Claim the self argument from the end of the formal arguments. SILArgument *selfArg = args.back(); args = args.slice(0, args.size() - 1); // Set the lowered explosion for the self argument. auto &selfTI = cast<LoadableTypeInfo>(IGF.getTypeInfo(selfArg->getType())); auto selfSchema = selfTI.getSchema(); assert(selfSchema.size() == 1 && "Expected self to be a single element!"); auto *selfValue = params.claimNext(); auto *bodyType = selfSchema.begin()->getScalarType(); if (selfValue->getType() != bodyType) selfValue = IGF.coerceValue(selfValue, bodyType, IGF.IGM.DataLayout); Explosion self; self.add(selfValue); IGF.setLoweredExplosion(selfArg, self); // Discard the implicit _cmd argument. params.claimNext(); // We've handled the self and _cmd arguments, so when we deal with // generating explosions for the remaining arguments we can skip // these. nextArgTyIdx = 2; } assert(args.size() == (FI.arg_size() - nextArgTyIdx) && "Number of arguments not equal to number of argument types!"); // Generate lowered explosions for each explicit argument. for (auto i : indices(args)) { SILArgument *arg = args[i]; auto argTyIdx = i + nextArgTyIdx; auto &argTI = IGF.getTypeInfo(arg->getType()); // Bitcast indirect argument pointers to the right storage type. if (arg->getType().isAddress()) { llvm::Value *ptr = params.claimNext(); ptr = IGF.Builder.CreateBitCast(ptr, argTI.getStorageType()->getPointerTo()); IGF.setLoweredAddress(arg, Address(ptr, argTI.getBestKnownAlignment())); continue; } auto &loadableArgTI = cast<LoadableTypeInfo>(argTI); Explosion argExplosion; emitForeignParameter(IGF, params, foreignInfo, argTyIdx, arg->getType(), loadableArgTI, argExplosion); IGF.setLoweredExplosion(arg, argExplosion); } assert(params.empty() && "didn't claim all parameters!"); // emitPolymorphicParameters() may create function calls, so we need // to initialize the debug location here. ArtificialLocation Loc(IGF.getDebugScope(), IGF.IGM.DebugInfo, IGF.Builder); // Bind polymorphic arguments. This can only be done after binding // all the value parameters, and must be done even for non-polymorphic // functions because of imported Objective-C generics. emitPolymorphicParameters( IGF, *IGF.CurSILFn, params, nullptr, [&](unsigned paramIndex) -> llvm::Value * { SILValue parameter = entry->getArguments()[paramIndex]; return IGF.getLoweredSingletonExplosion(parameter); }); } /// Get metadata for the dynamic Self type if we have it. static void emitLocalSelfMetadata(IRGenSILFunction &IGF) { if (!IGF.CurSILFn->hasSelfMetadataParam()) return; const SILArgument *selfArg = IGF.CurSILFn->getSelfMetadataArgument(); CanMetatypeType metaTy = dyn_cast<MetatypeType>(selfArg->getType().getSwiftRValueType()); IRGenFunction::LocalSelfKind selfKind; if (!metaTy) selfKind = IRGenFunction::ObjectReference; else switch (metaTy->getRepresentation()) { case MetatypeRepresentation::Thin: llvm_unreachable("class metatypes are never thin"); case MetatypeRepresentation::Thick: selfKind = IRGenFunction::SwiftMetatype; break; case MetatypeRepresentation::ObjC: selfKind = IRGenFunction::ObjCMetatype; break; } llvm::Value *value = IGF.getLoweredExplosion(selfArg).claimNext(); IGF.setLocalSelfMetadata(value, selfKind); } /// Emit the definition for the given SIL constant. void IRGenModule::emitSILFunction(SILFunction *f) { if (f->isExternalDeclaration()) return; PrettyStackTraceSILFunction stackTrace("emitting IR", f); IRGenSILFunction(*this, f).emitSILFunction(); } void IRGenSILFunction::emitSILFunction() { DEBUG(llvm::dbgs() << "emitting SIL function: "; CurSILFn->printName(llvm::dbgs()); llvm::dbgs() << '\n'; CurSILFn->print(llvm::dbgs())); assert(!CurSILFn->empty() && "function has no basic blocks?!"); // Configure the dominance resolver. // TODO: consider re-using a dom analysis from the PassManager // TODO: consider using a cheaper analysis at -O0 setDominanceResolver([](IRGenFunction &IGF_, DominancePoint activePoint, DominancePoint dominatingPoint) -> bool { IRGenSILFunction &IGF = static_cast<IRGenSILFunction&>(IGF_); if (!IGF.Dominance) { IGF.Dominance.reset(new DominanceInfo(IGF.CurSILFn)); } return IGF.Dominance->dominates(dominatingPoint.as<SILBasicBlock>(), activePoint.as<SILBasicBlock>()); }); if (IGM.DebugInfo) IGM.DebugInfo->emitFunction(*CurSILFn, CurFn); // Map the entry bb. LoweredBBs[&*CurSILFn->begin()] = LoweredBB(&*CurFn->begin(), {}); // Create LLVM basic blocks for the other bbs. for (auto bi = std::next(CurSILFn->begin()), be = CurSILFn->end(); bi != be; ++bi) { // FIXME: Use the SIL basic block's name. llvm::BasicBlock *llBB = llvm::BasicBlock::Create(IGM.getLLVMContext()); auto phis = emitPHINodesForBBArgs(*this, &*bi, llBB); CurFn->getBasicBlockList().push_back(llBB); LoweredBBs[&*bi] = LoweredBB(llBB, std::move(phis)); } auto entry = LoweredBBs.begin(); Builder.SetInsertPoint(entry->second.bb); // Map the LLVM arguments to arguments on the entry point BB. Explosion params = collectParameters(); auto funcTy = CurSILFn->getLoweredFunctionType(); switch (funcTy->getLanguage()) { case SILFunctionLanguage::Swift: emitEntryPointArgumentsNativeCC(*this, entry->first, params); break; case SILFunctionLanguage::C: emitEntryPointArgumentsCOrObjC(*this, entry->first, params, funcTy); break; } emitLocalSelfMetadata(*this); assert(params.empty() && "did not map all llvm params to SIL params?!"); // It's really nice to be able to assume that we've already emitted // all the values from dominating blocks --- it makes simple // peepholing more powerful and allows us to avoid the need for // nasty "forward-declared" values. We can do this by emitting // blocks using a simple walk through the successor graph. // // We do want to preserve the original source order, but that's done // by having previously added all the primary blocks to the LLVM // function in their original order. As long as any secondary // blocks are inserted after the current IP instead of at the end // of the function, we're fine. // Invariant: for every block in the work queue, we have visited all // of its dominators. llvm::SmallPtrSet<SILBasicBlock*, 8> visitedBlocks; SmallVector<SILBasicBlock*, 8> workQueue; // really a stack // Queue up the entry block, for which the invariant trivially holds. visitedBlocks.insert(&*CurSILFn->begin()); workQueue.push_back(&*CurSILFn->begin()); while (!workQueue.empty()) { auto bb = workQueue.pop_back_val(); // Emit the block. visitSILBasicBlock(bb); #ifndef NDEBUG // Assert that the current IR IP (if valid) is immediately prior // to the initial IR block for the next primary SIL block. // It's not semantically necessary to preserve SIL block order, // but we really should. if (auto curBB = Builder.GetInsertBlock()) { auto next = std::next(SILFunction::iterator(bb)); if (next != CurSILFn->end()) { auto nextBB = LoweredBBs[&*next].bb; assert(&*std::next(curBB->getIterator()) == nextBB && "lost source SIL order?"); } } #endif // The immediate dominator of a successor of this block needn't be // this block, but it has to be something which dominates this // block. In either case, we've visited it. // // Therefore the invariant holds of all the successors, and we can // queue them up if we haven't already visited them. for (auto *succBB : bb->getSuccessorBlocks()) { if (visitedBlocks.insert(succBB).second) workQueue.push_back(succBB); } } // If there are dead blocks in the SIL function, we might have left // invalid blocks in the IR. Do another pass and kill them off. for (SILBasicBlock &bb : *CurSILFn) if (!visitedBlocks.count(&bb)) LoweredBBs[&bb].bb->eraseFromParent(); } void IRGenSILFunction::estimateStackSize() { if (EstimatedStackSize >= 0) return; // TODO: as soon as we generate alloca instructions with accurate lifetimes // we should also do a better stack size calculation here. Currently we // add all stack sizes even if life ranges do not overlap. for (SILBasicBlock &BB : *CurSILFn) { for (SILInstruction &I : BB) { if (auto *ASI = dyn_cast<AllocStackInst>(&I)) { const TypeInfo &type = getTypeInfo(ASI->getElementType()); if (llvm::Constant *SizeConst = type.getStaticSize(IGM)) { auto *SizeInt = cast<llvm::ConstantInt>(SizeConst); EstimatedStackSize += (int)SizeInt->getSExtValue(); } } } } } void IRGenSILFunction::visitSILBasicBlock(SILBasicBlock *BB) { // Insert into the lowered basic block. llvm::BasicBlock *llBB = getLoweredBB(BB).bb; Builder.SetInsertPoint(llBB); bool InEntryBlock = BB->pred_empty(); // Set this block as the dominance point. This implicitly communicates // with the dominance resolver configured in emitSILFunction. DominanceScope dominance(*this, InEntryBlock ? DominancePoint::universal() : DominancePoint(BB)); // The basic blocks are visited in a random order. Reset the debug location. std::unique_ptr<AutoRestoreLocation> ScopedLoc; if (InEntryBlock) ScopedLoc = llvm::make_unique<PrologueLocation>(IGM.DebugInfo, Builder); else ScopedLoc = llvm::make_unique<ArtificialLocation>( CurSILFn->getDebugScope(), IGM.DebugInfo, Builder); // Generate the body. bool InCleanupBlock = false; bool KeepCurrentLocation = false; for (auto InsnIter = BB->begin(); InsnIter != BB->end(); ++InsnIter) { auto &I = *InsnIter; if (IGM.DebugInfo) { // Set the debug info location for I, if applicable. SILLocation ILoc = I.getLoc(); auto DS = I.getDebugScope(); // Handle cleanup locations. if (ILoc.is<CleanupLocation>()) { // Cleanup locations point to the decl of the value that is // being destroyed (for diagnostic generation). As far as // the linetable is concerned, cleanups at the end of a // lexical scope should point to the cleanup location, which // is the location of the last instruction in the basic block. if (!InCleanupBlock) { InCleanupBlock = true; // Scan ahead to see if this is the final cleanup block in // this basic block. auto It = InsnIter; do ++It; while (It != BB->end() && It->getLoc().is<CleanupLocation>()); // We are still in the middle of a basic block? if (It != BB->end() && !isa<TermInst>(It)) KeepCurrentLocation = true; } // Assign the cleanup location to this instruction. if (!KeepCurrentLocation) { assert(BB->getTerminator()); ILoc = BB->getTerminator()->getLoc(); DS = BB->getTerminator()->getDebugScope(); } } else if (InCleanupBlock) { KeepCurrentLocation = false; InCleanupBlock = false; } // Until SILDebugScopes are properly serialized, bare functions // are allowed to not have a scope. if (!DS) { if (CurSILFn->isBare()) DS = CurSILFn->getDebugScope(); assert(maybeScopeless(I) && "instruction has location, but no scope"); } // Set the builder's debug location. if (DS && !KeepCurrentLocation) IGM.DebugInfo->setCurrentLoc(Builder, DS, ILoc); else // Use an artificial (line 0) location. IGM.DebugInfo->setCurrentLoc(Builder, DS); if (isa<TermInst>(&I)) emitDebugVariableRangeExtension(BB); } visit(&I); } assert(Builder.hasPostTerminatorIP() && "SIL bb did not terminate block?!"); } void IRGenSILFunction::visitFunctionRefInst(FunctionRefInst *i) { auto fn = i->getReferencedFunction(); llvm::Function *fnptr = IGM.getAddrOfSILFunction(fn, NotForDefinition); auto foreignInfo = IGM.getForeignFunctionInfo(fn->getLoweredFunctionType()); // Store the function constant and calling // convention as a StaticFunction so we can avoid bitcasting or thunking if // we don't need to. setLoweredStaticFunction(i, fnptr, fn->getRepresentation(), foreignInfo); } void IRGenSILFunction::visitAllocGlobalInst(AllocGlobalInst *i) { SILGlobalVariable *var = i->getReferencedGlobal(); SILType loweredTy = var->getLoweredType(); auto &ti = getTypeInfo(loweredTy); auto expansion = IGM.getResilienceExpansionForLayout(var); // If the global is fixed-size in all resilience domains that can see it, // we allocated storage for it statically, and there's nothing to do. if (ti.isFixedSize(expansion)) return; // Otherwise, the static storage for the global consists of a fixed-size // buffer. Address addr = IGM.getAddrOfSILGlobalVariable(var, ti, NotForDefinition); if (getSILModule().getOptions().UseCOWExistentials) { emitAllocateValueInBuffer(*this, loweredTy, addr); } else { (void) ti.allocateBuffer(*this, addr, loweredTy); } } void IRGenSILFunction::visitGlobalAddrInst(GlobalAddrInst *i) { SILGlobalVariable *var = i->getReferencedGlobal(); SILType loweredTy = var->getLoweredType(); assert(loweredTy == i->getType().getObjectType()); auto &ti = getTypeInfo(loweredTy); auto expansion = IGM.getResilienceExpansionForLayout(var); // If the variable is empty in all resilience domains that can see it, // don't actually emit a symbol for the global at all, just return undef. if (ti.isKnownEmpty(expansion)) { setLoweredAddress(i, ti.getUndefAddress()); return; } Address addr = IGM.getAddrOfSILGlobalVariable(var, ti, NotForDefinition); // If the global is fixed-size in all resilience domains that can see it, // we allocated storage for it statically, and there's nothing to do. if (ti.isFixedSize(expansion)) { setLoweredAddress(i, addr); return; } // Otherwise, the static storage for the global consists of a fixed-size // buffer; project it. if (getSILModule().getOptions().UseCOWExistentials) { addr = emitProjectValueInBuffer(*this, loweredTy, addr); } else { addr = ti.projectBuffer(*this, addr, loweredTy); } setLoweredAddress(i, addr); } void IRGenSILFunction::visitMetatypeInst(swift::MetatypeInst *i) { auto metaTy = i->getType().castTo<MetatypeType>(); Explosion e; emitMetatypeRef(*this, metaTy, e); setLoweredExplosion(i, e); } static llvm::Value *getClassBaseValue(IRGenSILFunction &IGF, SILValue v) { if (v->getType().isAddress()) { auto addr = IGF.getLoweredAddress(v); return IGF.Builder.CreateLoad(addr); } Explosion e = IGF.getLoweredExplosion(v); return e.claimNext(); } static llvm::Value *getClassMetatype(IRGenFunction &IGF, llvm::Value *baseValue, MetatypeRepresentation repr, SILType instanceType) { switch (repr) { case MetatypeRepresentation::Thin: llvm_unreachable("Class metatypes are never thin"); case MetatypeRepresentation::Thick: return emitDynamicTypeOfHeapObject(IGF, baseValue, instanceType); case MetatypeRepresentation::ObjC: return emitHeapMetadataRefForHeapObject(IGF, baseValue, instanceType); } llvm_unreachable("Not a valid MetatypeRepresentation."); } void IRGenSILFunction::visitValueMetatypeInst(swift::ValueMetatypeInst *i) { SILType instanceTy = i->getOperand()->getType(); auto metaTy = i->getType().castTo<MetatypeType>(); if (metaTy->getRepresentation() == MetatypeRepresentation::Thin) { Explosion empty; setLoweredExplosion(i, empty); return; } Explosion e; if (instanceTy.getClassOrBoundGenericClass()) { e.add(getClassMetatype(*this, getClassBaseValue(*this, i->getOperand()), metaTy->getRepresentation(), instanceTy)); } else if (auto arch = instanceTy.getAs<ArchetypeType>()) { if (arch->requiresClass()) { e.add(getClassMetatype(*this, getClassBaseValue(*this, i->getOperand()), metaTy->getRepresentation(), instanceTy)); } else { Address base = getLoweredAddress(i->getOperand()); e.add(emitDynamicTypeOfOpaqueArchetype(*this, base, i->getOperand()->getType())); // FIXME: We need to convert this back to an ObjC class for an // ObjC metatype representation. if (metaTy->getRepresentation() == MetatypeRepresentation::ObjC) unimplemented(i->getLoc().getSourceLoc(), "objc metatype of non-class-bounded archetype"); } } else { emitMetatypeRef(*this, metaTy, e); } setLoweredExplosion(i, e); } void IRGenSILFunction::visitExistentialMetatypeInst( swift::ExistentialMetatypeInst *i) { Explosion result; SILValue op = i->getOperand(); SILType opType = op->getType(); switch (opType.getPreferredExistentialRepresentation(IGM.getSILModule())) { case ExistentialRepresentation::Metatype: { Explosion existential = getLoweredExplosion(op); emitMetatypeOfMetatype(*this, existential, opType, result); break; } case ExistentialRepresentation::Class: { Explosion existential = getLoweredExplosion(op); emitMetatypeOfClassExistential(*this, existential, i->getType(), opType, result); break; } case ExistentialRepresentation::Boxed: { Explosion existential = getLoweredExplosion(op); emitMetatypeOfBoxedExistential(*this, existential, opType, result); break; } case ExistentialRepresentation::Opaque: { Address existential = getLoweredAddress(op); emitMetatypeOfOpaqueExistential(*this, existential, opType, result); break; } case ExistentialRepresentation::None: llvm_unreachable("Bad existential representation"); } setLoweredExplosion(i, result); } static void emitApplyArgument(IRGenSILFunction &IGF, SILValue arg, SILType paramType, Explosion &out) { bool isSubstituted = (arg->getType() != paramType); // For indirect arguments, we just need to pass a pointer. if (paramType.isAddress()) { // This address is of the substituted type. auto addr = IGF.getLoweredAddress(arg); // If a substitution is in play, just bitcast the address. if (isSubstituted) { auto origType = IGF.IGM.getStoragePointerType(paramType); addr = IGF.Builder.CreateBitCast(addr, origType); } out.add(addr.getAddress()); return; } // Otherwise, it's an explosion, which we may need to translate, // both in terms of explosion level and substitution levels. assert(arg->getType().isObject()); // Fast path: avoid an unnecessary temporary explosion. if (!isSubstituted) { IGF.getLoweredExplosion(arg, out); return; } Explosion temp = IGF.getLoweredExplosion(arg); reemitAsUnsubstituted(IGF, paramType, arg->getType(), temp, out); } static llvm::Value *getObjCClassForValue(IRGenSILFunction &IGF, llvm::Value *selfValue, CanAnyMetatypeType selfType) { // If we have a Swift metatype, map it to the heap metadata, which // will be the Class for an ObjC type. switch (selfType->getRepresentation()) { case swift::MetatypeRepresentation::ObjC: return selfValue; case swift::MetatypeRepresentation::Thick: // Convert thick metatype to Objective-C metatype. return emitClassHeapMetadataRefForMetatype(IGF, selfValue, selfType.getInstanceType()); case swift::MetatypeRepresentation::Thin: llvm_unreachable("Cannot convert Thin metatype to ObjC metatype"); } llvm_unreachable("bad metatype representation"); } static llvm::Value *emitWitnessTableForLoweredCallee(IRGenSILFunction &IGF, CanSILFunctionType origCalleeType, SubstitutionList subs) { auto &M = *IGF.getSwiftModule(); llvm::Value *wtable; if (auto *proto = origCalleeType->getDefaultWitnessMethodProtocol(M)) { // The generic signature for a witness method with abstract Self must // have exactly one protocol requirement. // // We recover the witness table from the substitution that was used to // produce the substituted callee type. auto subMap = origCalleeType->getGenericSignature() ->getSubstitutionMap(subs); auto origSelfType = proto->getSelfInterfaceType()->getCanonicalType(); auto substSelfType = origSelfType.subst(subMap)->getCanonicalType(); auto conformance = *subMap.lookupConformance(origSelfType, proto); llvm::Value *argMetadata = IGF.emitTypeMetadataRef(substSelfType); wtable = emitWitnessTableRef(IGF, substSelfType, &argMetadata, conformance); } else { // Otherwise, we have no way of knowing the original protocol or // conformance, since the witness has a concrete self type. // // Protocol witnesses for concrete types are thus not allowed to touch // the witness table; they already know all the witnesses, and we can't // say who they are. wtable = llvm::ConstantPointerNull::get(IGF.IGM.WitnessTablePtrTy); } assert(wtable->getType() == IGF.IGM.WitnessTablePtrTy); return wtable; } static CallEmission getCallEmissionForLoweredValue(IRGenSILFunction &IGF, CanSILFunctionType origCalleeType, CanSILFunctionType substCalleeType, const LoweredValue &lv, llvm::Value *selfValue, SubstitutionList substitutions, WitnessMetadata *witnessMetadata, Explosion &args) { llvm::Value *calleeFn, *calleeData; ForeignFunctionInfo foreignInfo; switch (lv.kind) { case LoweredValue::Kind::StaticFunction: calleeFn = lv.getStaticFunction().getFunction(); calleeData = selfValue; foreignInfo = lv.getStaticFunction().getForeignInfo(); if (origCalleeType->getRepresentation() == SILFunctionType::Representation::WitnessMethod) { llvm::Value *wtable = emitWitnessTableForLoweredCallee( IGF, origCalleeType, substitutions); witnessMetadata->SelfWitnessTable = wtable; } break; case LoweredValue::Kind::ObjCMethod: { assert(selfValue); auto &objcMethod = lv.getObjCMethod(); ObjCMessageKind kind = objcMethod.getMessageKind(); CallEmission emission = prepareObjCMethodRootCall(IGF, objcMethod.getMethod(), origCalleeType, substCalleeType, substitutions, kind); // Convert a metatype 'self' argument to the ObjC Class pointer. // FIXME: Should be represented in SIL. if (auto metatype = dyn_cast<AnyMetatypeType>( origCalleeType->getSelfParameter().getType())) { selfValue = getObjCClassForValue(IGF, selfValue, metatype); } addObjCMethodCallImplicitArguments(IGF, args, objcMethod.getMethod(), selfValue, objcMethod.getSearchType()); return emission; } case LoweredValue::Kind::Explosion: { switch (origCalleeType->getRepresentation()) { case SILFunctionType::Representation::Block: { assert(!selfValue && "block function with self?"); // Grab the block pointer and make it the first physical argument. llvm::Value *blockPtr = lv.getSingletonExplosion(IGF); blockPtr = IGF.Builder.CreateBitCast(blockPtr, IGF.IGM.ObjCBlockPtrTy); args.add(blockPtr); // Extract the invocation pointer for blocks. llvm::Value *invokeAddr = IGF.Builder.CreateStructGEP( /*Ty=*/nullptr, blockPtr, 3); calleeFn = IGF.Builder.CreateLoad(invokeAddr, IGF.IGM.getPointerAlignment()); calleeData = nullptr; break; } case SILFunctionType::Representation::Thin: case SILFunctionType::Representation::CFunctionPointer: case SILFunctionType::Representation::Method: case SILFunctionType::Representation::Closure: case SILFunctionType::Representation::ObjCMethod: case SILFunctionType::Representation::WitnessMethod: case SILFunctionType::Representation::Thick: { Explosion calleeValues = lv.getExplosion(IGF); calleeFn = calleeValues.claimNext(); if (origCalleeType->getRepresentation() == SILFunctionType::Representation::WitnessMethod) { witnessMetadata->SelfWitnessTable = emitWitnessTableForLoweredCallee( IGF, origCalleeType, substitutions); } if (origCalleeType->getRepresentation() == SILFunctionType::Representation::Thick) { // @convention(thick) callees are exploded as a pair // consisting of the function and the self value. assert(!selfValue); calleeData = calleeValues.claimNext(); } else { calleeData = selfValue; } break; } } // Cast the callee pointer to the right function type. llvm::AttributeSet attrs; llvm::FunctionType *fnTy = IGF.IGM.getFunctionType(origCalleeType, attrs, &foreignInfo); calleeFn = IGF.Builder.CreateBitCast(calleeFn, fnTy->getPointerTo()); break; } case LoweredValue::Kind::BoxWithAddress: llvm_unreachable("@box isn't a valid callee"); case LoweredValue::Kind::ContainedAddress: case LoweredValue::Kind::Address: llvm_unreachable("sil address isn't a valid callee"); } Callee callee = Callee::forKnownFunction(origCalleeType, substCalleeType, substitutions, calleeFn, calleeData, foreignInfo); CallEmission callEmission(IGF, callee); if (IGF.CurSILFn->isThunk()) callEmission.addAttribute(llvm::AttributeSet::FunctionIndex, llvm::Attribute::NoInline); return callEmission; } void IRGenSILFunction::visitBuiltinInst(swift::BuiltinInst *i) { auto argValues = i->getArguments(); Explosion args; for (auto argValue : argValues) { // Builtin arguments should never be substituted, so use the value's type // as the parameter type. emitApplyArgument(*this, argValue, argValue->getType(), args); } Explosion result; emitBuiltinCall(*this, i->getName(), i->getType(), args, result, i->getSubstitutions()); setLoweredExplosion(i, result); } void IRGenSILFunction::visitApplyInst(swift::ApplyInst *i) { visitFullApplySite(i); } void IRGenSILFunction::visitTryApplyInst(swift::TryApplyInst *i) { visitFullApplySite(i); } void IRGenSILFunction::visitFullApplySite(FullApplySite site) { const LoweredValue &calleeLV = getLoweredValue(site.getCallee()); auto origCalleeType = site.getOrigCalleeType(); auto substCalleeType = site.getSubstCalleeType(); auto args = site.getArguments(); SILFunctionConventions origConv(origCalleeType, getSILModule()); assert(origConv.getNumSILArguments() == args.size()); // Extract 'self' if it needs to be passed as the context parameter. llvm::Value *selfValue = nullptr; if (origCalleeType->hasSelfParam() && isSelfContextParameter(origCalleeType->getSelfParameter())) { SILValue selfArg = args.back(); args = args.drop_back(); if (selfArg->getType().isObject()) { selfValue = getLoweredSingletonExplosion(selfArg); } else { selfValue = getLoweredAddress(selfArg).getAddress(); } } Explosion llArgs; WitnessMetadata witnessMetadata; CallEmission emission = getCallEmissionForLoweredValue(*this, origCalleeType, substCalleeType, calleeLV, selfValue, site.getSubstitutions(), &witnessMetadata, llArgs); // Lower the arguments and return value in the callee's generic context. GenericContextScope scope(IGM, origCalleeType->getGenericSignature()); // Lower the SIL arguments to IR arguments. // Turn the formal SIL parameters into IR-gen things. for (auto index : indices(args)) { emitApplyArgument(*this, args[index], origConv.getSILArgumentType(index), llArgs); } // Pass the generic arguments. if (hasPolymorphicParameters(origCalleeType)) { SubstitutionMap subMap; if (auto genericSig = origCalleeType->getGenericSignature()) subMap = genericSig->getSubstitutionMap(site.getSubstitutions()); emitPolymorphicArguments(*this, origCalleeType, substCalleeType, subMap, &witnessMetadata, llArgs); } // Add all those arguments. emission.setArgs(llArgs, &witnessMetadata); SILInstruction *i = site.getInstruction(); Explosion result; emission.emitToExplosion(result); if (isa<ApplyInst>(i)) { setLoweredExplosion(i, result); } else { auto tryApplyInst = cast<TryApplyInst>(i); // Load the error value. SILFunctionConventions substConv(substCalleeType, getSILModule()); SILType errorType = substConv.getSILErrorType(); Address errorSlot = getErrorResultSlot(errorType); auto errorValue = Builder.CreateLoad(errorSlot); auto &normalDest = getLoweredBB(tryApplyInst->getNormalBB()); auto &errorDest = getLoweredBB(tryApplyInst->getErrorBB()); // Zero the error slot to maintain the invariant that it always // contains null. This will frequently become a dead store. auto nullError = llvm::Constant::getNullValue(errorValue->getType()); if (!tryApplyInst->getErrorBB()->getSinglePredecessorBlock()) { // Only do that here if we can't move the store to the error block. // See below. Builder.CreateStore(nullError, errorSlot); } // If the error value is non-null, branch to the error destination. auto hasError = Builder.CreateICmpNE(errorValue, nullError); Builder.CreateCondBr(hasError, errorDest.bb, normalDest.bb); // Set up the PHI nodes on the normal edge. unsigned firstIndex = 0; addIncomingExplosionToPHINodes(*this, normalDest, firstIndex, result); assert(firstIndex == normalDest.phis.size()); // Set up the PHI nodes on the error edge. assert(errorDest.phis.size() == 1); errorDest.phis[0]->addIncoming(errorValue, Builder.GetInsertBlock()); if (tryApplyInst->getErrorBB()->getSinglePredecessorBlock()) { // Zeroing out the error slot only in the error block increases the chance // that it will become a dead store. auto origBB = Builder.GetInsertBlock(); Builder.SetInsertPoint(errorDest.bb); Builder.CreateStore(nullError, errorSlot); Builder.SetInsertPoint(origBB); } } } /// If the value is a @convention(witness_method) function, the context /// is the witness table that must be passed to the call. /// /// \param v A value of possibly-polymorphic SILFunctionType. /// \param subs This is the set of substitutions that we are going to be /// applying to 'v'. static std::tuple<llvm::Value*, llvm::Value*, CanSILFunctionType> getPartialApplicationFunction(IRGenSILFunction &IGF, SILValue v, SubstitutionList subs) { LoweredValue &lv = IGF.getLoweredValue(v); auto fnType = v->getType().castTo<SILFunctionType>(); switch (lv.kind) { case LoweredValue::Kind::ContainedAddress: case LoweredValue::Kind::Address: llvm_unreachable("can't partially apply an address"); case LoweredValue::Kind::BoxWithAddress: llvm_unreachable("can't partially apply a @box"); case LoweredValue::Kind::ObjCMethod: llvm_unreachable("objc method partial application shouldn't get here"); case LoweredValue::Kind::StaticFunction: { llvm::Value *context = nullptr; switch (lv.getStaticFunction().getRepresentation()) { case SILFunctionTypeRepresentation::CFunctionPointer: case SILFunctionTypeRepresentation::Block: case SILFunctionTypeRepresentation::ObjCMethod: assert(false && "partial_apply of foreign functions not implemented"); break; case SILFunctionTypeRepresentation::WitnessMethod: context = emitWitnessTableForLoweredCallee(IGF, fnType, subs); break; case SILFunctionTypeRepresentation::Thick: case SILFunctionTypeRepresentation::Thin: case SILFunctionTypeRepresentation::Method: case SILFunctionTypeRepresentation::Closure: break; } return std::make_tuple(lv.getStaticFunction().getFunction(), context, v->getType().castTo<SILFunctionType>()); } case LoweredValue::Kind::Explosion: { Explosion ex = lv.getExplosion(IGF); llvm::Value *fn = ex.claimNext(); llvm::Value *context = nullptr; switch (fnType->getRepresentation()) { case SILFunctionType::Representation::Thin: case SILFunctionType::Representation::Method: case SILFunctionType::Representation::Closure: case SILFunctionType::Representation::ObjCMethod: break; case SILFunctionType::Representation::WitnessMethod: context = emitWitnessTableForLoweredCallee(IGF, fnType, subs); break; case SILFunctionType::Representation::CFunctionPointer: break; case SILFunctionType::Representation::Thick: context = ex.claimNext(); break; case SILFunctionType::Representation::Block: llvm_unreachable("partial application of block not implemented"); } return std::make_tuple(fn, context, fnType); } } llvm_unreachable("Not a valid SILFunctionType."); } void IRGenSILFunction::visitPartialApplyInst(swift::PartialApplyInst *i) { SILValue v(i); // NB: We collect the arguments under the substituted type. auto args = i->getArguments(); auto params = i->getSubstCalleeType()->getParameters(); params = params.slice(params.size() - args.size(), args.size()); Explosion llArgs; { // Lower the parameters in the callee's generic context. GenericContextScope scope(IGM, i->getOrigCalleeType()->getGenericSignature()); for (auto index : indices(args)) { assert(args[index]->getType() == IGM.silConv.getSILType(params[index])); emitApplyArgument(*this, args[index], IGM.silConv.getSILType(params[index]), llArgs); } } auto &lv = getLoweredValue(i->getCallee()); if (lv.kind == LoweredValue::Kind::ObjCMethod) { // Objective-C partial applications require a different path. There's no // actual function pointer to capture, and we semantically can't cache // dispatch, so we need to perform the message send in the partial // application thunk. auto &objcMethod = lv.getObjCMethod(); assert(i->getArguments().size() == 1 && "only partial application of objc method to self implemented"); assert(llArgs.size() == 1 && "objc partial_apply argument is not a single retainable pointer?!"); llvm::Value *selfVal = llArgs.claimNext(); Explosion function; emitObjCPartialApplication(*this, objcMethod, i->getOrigCalleeType(), i->getType().castTo<SILFunctionType>(), selfVal, i->getArguments()[0]->getType(), function); setLoweredExplosion(i, function); return; } // Get the function value. llvm::Value *calleeFn = nullptr; llvm::Value *innerContext = nullptr; CanSILFunctionType origCalleeTy; std::tie(calleeFn, innerContext, origCalleeTy) = getPartialApplicationFunction(*this, i->getCallee(), i->getSubstitutions()); // Create the thunk and function value. Explosion function; emitFunctionPartialApplication(*this, *CurSILFn, calleeFn, innerContext, llArgs, params, i->getSubstitutions(), origCalleeTy, i->getSubstCalleeType(), i->getType().castTo<SILFunctionType>(), function); setLoweredExplosion(v, function); } void IRGenSILFunction::visitIntegerLiteralInst(swift::IntegerLiteralInst *i) { llvm::Value *constant = emitConstantInt(IGM, i); Explosion e; e.add(constant); setLoweredExplosion(i, e); } void IRGenSILFunction::visitFloatLiteralInst(swift::FloatLiteralInst *i) { llvm::Value *constant = emitConstantFP(IGM, i); Explosion e; e.add(constant); setLoweredExplosion(i, e); } void IRGenSILFunction::visitStringLiteralInst(swift::StringLiteralInst *i) { llvm::Value *addr; // Emit a load of a selector. if (i->getEncoding() == swift::StringLiteralInst::Encoding::ObjCSelector) addr = emitObjCSelectorRefLoad(i->getValue()); else addr = emitAddrOfConstantString(IGM, i); Explosion e; e.add(addr); setLoweredExplosion(i, e); } void IRGenSILFunction::visitUnreachableInst(swift::UnreachableInst *i) { Builder.CreateUnreachable(); } static void emitReturnInst(IRGenSILFunction &IGF, SILType resultTy, Explosion &result) { // The invariant on the out-parameter is that it's always zeroed, so // there's nothing to do here. // Even if SIL has a direct return, the IR-level calling convention may // require an indirect return. if (IGF.IndirectReturn.isValid()) { auto &retTI = cast<LoadableTypeInfo>(IGF.getTypeInfo(resultTy)); retTI.initialize(IGF, result, IGF.IndirectReturn); IGF.Builder.CreateRetVoid(); } else { auto funcLang = IGF.CurSILFn->getLoweredFunctionType()->getLanguage(); auto swiftCCReturn = funcLang == SILFunctionLanguage::Swift; assert(swiftCCReturn || funcLang == SILFunctionLanguage::C && "Need to handle all cases"); IGF.emitScalarReturn(resultTy, result, swiftCCReturn); } } void IRGenSILFunction::visitReturnInst(swift::ReturnInst *i) { Explosion result = getLoweredExplosion(i->getOperand()); // Implicitly autorelease the return value if the function's result // convention is autoreleased. auto fnConv = CurSILFn->getConventions(); if (fnConv.getNumDirectSILResults() == 1 && (fnConv.getDirectSILResults().begin()->getConvention() == ResultConvention::Autoreleased)) { Explosion temp; temp.add(emitObjCAutoreleaseReturnValue(*this, result.claimNext())); result = std::move(temp); } emitReturnInst(*this, i->getOperand()->getType(), result); } void IRGenSILFunction::visitThrowInst(swift::ThrowInst *i) { // Store the exception to the error slot. llvm::Value *exn = getLoweredSingletonExplosion(i->getOperand()); Builder.CreateStore(exn, getCallerErrorResultSlot()); // Create a normal return, but leaving the return value undefined. auto fnTy = CurFn->getType()->getPointerElementType(); auto retTy = cast<llvm::FunctionType>(fnTy)->getReturnType(); if (retTy->isVoidTy()) { Builder.CreateRetVoid(); } else { Builder.CreateRet(llvm::UndefValue::get(retTy)); } } static llvm::BasicBlock *emitBBMapForSwitchValue( IRGenSILFunction &IGF, SmallVectorImpl<std::pair<SILValue, llvm::BasicBlock*>> &dests, SwitchValueInst *inst) { for (unsigned i = 0, e = inst->getNumCases(); i < e; ++i) { auto casePair = inst->getCase(i); dests.push_back({casePair.first, IGF.getLoweredBB(casePair.second).bb}); } llvm::BasicBlock *defaultDest = nullptr; if (inst->hasDefault()) defaultDest = IGF.getLoweredBB(inst->getDefaultBB()).bb; return defaultDest; } static llvm::ConstantInt * getSwitchCaseValue(IRGenFunction &IGF, SILValue val) { if (auto *IL = dyn_cast<IntegerLiteralInst>(val)) { return dyn_cast<llvm::ConstantInt>(emitConstantInt(IGF.IGM, IL)); } else { llvm_unreachable("Switch value cases should be integers"); } } static void emitSwitchValueDispatch(IRGenSILFunction &IGF, SILType ty, Explosion &value, ArrayRef<std::pair<SILValue, llvm::BasicBlock*>> dests, llvm::BasicBlock *defaultDest) { // Create an unreachable block for the default if the original SIL // instruction had none. bool unreachableDefault = false; if (!defaultDest) { unreachableDefault = true; defaultDest = llvm::BasicBlock::Create(IGF.IGM.getLLVMContext()); } if (ty.is<BuiltinIntegerType>()) { auto *discriminator = value.claimNext(); auto *i = IGF.Builder.CreateSwitch(discriminator, defaultDest, dests.size()); for (auto &dest : dests) i->addCase(getSwitchCaseValue(IGF, dest.first), dest.second); } else { // Get the value we're testing, which is a function. llvm::Value *val; llvm::BasicBlock *nextTest = nullptr; if (ty.is<SILFunctionType>()) { val = value.claimNext(); // Function pointer. //values.claimNext(); // Ignore the data pointer. } else { llvm_unreachable("switch_value operand has an unknown type"); } for (int i = 0, e = dests.size(); i < e; ++i) { auto casePair = dests[i]; llvm::Value *caseval; auto casevalue = IGF.getLoweredExplosion(casePair.first); if (casePair.first->getType().is<SILFunctionType>()) { caseval = casevalue.claimNext(); // Function pointer. //values.claimNext(); // Ignore the data pointer. } else { llvm_unreachable("switch_value operand has an unknown type"); } // Compare operand with a case tag value. llvm::Value *cond = IGF.Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, val, caseval); if (i == e -1 && !unreachableDefault) { nextTest = nullptr; IGF.Builder.CreateCondBr(cond, casePair.second, defaultDest); } else { nextTest = IGF.createBasicBlock("next-test"); IGF.Builder.CreateCondBr(cond, casePair.second, nextTest); IGF.Builder.emitBlock(nextTest); IGF.Builder.SetInsertPoint(nextTest); } } if (nextTest) { IGF.Builder.CreateBr(defaultDest); } } if (unreachableDefault) { IGF.Builder.emitBlock(defaultDest); IGF.Builder.CreateUnreachable(); } } void IRGenSILFunction::visitSwitchValueInst(SwitchValueInst *inst) { Explosion value = getLoweredExplosion(inst->getOperand()); // Map the SIL dest bbs to their LLVM bbs. SmallVector<std::pair<SILValue, llvm::BasicBlock*>, 4> dests; auto *defaultDest = emitBBMapForSwitchValue(*this, dests, inst); emitSwitchValueDispatch(*this, inst->getOperand()->getType(), value, dests, defaultDest); } // Bind an incoming explosion value to an explosion of LLVM phi node(s). static void addIncomingExplosionToPHINodes(IRGenSILFunction &IGF, ArrayRef<llvm::Value*> phis, Explosion &argValue) { llvm::BasicBlock *curBB = IGF.Builder.GetInsertBlock(); unsigned phiIndex = 0; while (!argValue.empty()) cast<llvm::PHINode>(phis[phiIndex++]) ->addIncoming(argValue.claimNext(), curBB); assert(phiIndex == phis.size() && "explosion doesn't match number of phis"); } // Bind an incoming explosion value to a SILArgument's LLVM phi node(s). static void addIncomingExplosionToPHINodes(IRGenSILFunction &IGF, LoweredBB &lbb, unsigned &phiIndex, Explosion &argValue) { llvm::BasicBlock *curBB = IGF.Builder.GetInsertBlock(); while (!argValue.empty()) lbb.phis[phiIndex++]->addIncoming(argValue.claimNext(), curBB); } // Bind an incoming address value to a SILArgument's LLVM phi node(s). static void addIncomingAddressToPHINodes(IRGenSILFunction &IGF, ArrayRef<llvm::Value*> phis, Address argValue) { llvm::BasicBlock *curBB = IGF.Builder.GetInsertBlock(); assert(phis.size() == 1 && "more than one phi for address?!"); cast<llvm::PHINode>(phis[0])->addIncoming(argValue.getAddress(), curBB); } // Bind an incoming address value to a SILArgument's LLVM phi node(s). static void addIncomingAddressToPHINodes(IRGenSILFunction &IGF, LoweredBB &lbb, unsigned &phiIndex, Address argValue) { llvm::BasicBlock *curBB = IGF.Builder.GetInsertBlock(); lbb.phis[phiIndex++]->addIncoming(argValue.getAddress(), curBB); } // Add branch arguments to destination phi nodes. static void addIncomingSILArgumentsToPHINodes(IRGenSILFunction &IGF, LoweredBB &lbb, OperandValueArrayRef args) { unsigned phiIndex = 0; for (SILValue arg : args) { const LoweredValue &lv = IGF.getLoweredValue(arg); if (lv.isAddress()) { addIncomingAddressToPHINodes(IGF, lbb, phiIndex, lv.getAddress()); continue; } Explosion argValue = lv.getExplosion(IGF); addIncomingExplosionToPHINodes(IGF, lbb, phiIndex, argValue); } } static llvm::BasicBlock *emitBBMapForSwitchEnum( IRGenSILFunction &IGF, SmallVectorImpl<std::pair<EnumElementDecl*, llvm::BasicBlock*>> &dests, SwitchEnumInstBase *inst) { for (unsigned i = 0, e = inst->getNumCases(); i < e; ++i) { auto casePair = inst->getCase(i); // If the destination BB accepts the case argument, set up a waypoint BB so // we can feed the values into the argument's PHI node(s). // // FIXME: This is cheesy when the destination BB has only the switch // as a predecessor. if (!casePair.second->args_empty()) dests.push_back({casePair.first, llvm::BasicBlock::Create(IGF.IGM.getLLVMContext())}); else dests.push_back({casePair.first, IGF.getLoweredBB(casePair.second).bb}); } llvm::BasicBlock *defaultDest = nullptr; if (inst->hasDefault()) defaultDest = IGF.getLoweredBB(inst->getDefaultBB()).bb; return defaultDest; } void IRGenSILFunction::visitSwitchEnumInst(SwitchEnumInst *inst) { Explosion value = getLoweredExplosion(inst->getOperand()); // Map the SIL dest bbs to their LLVM bbs. SmallVector<std::pair<EnumElementDecl*, llvm::BasicBlock*>, 4> dests; llvm::BasicBlock *defaultDest = emitBBMapForSwitchEnum(*this, dests, inst); // Emit the dispatch. auto &EIS = getEnumImplStrategy(IGM, inst->getOperand()->getType()); EIS.emitValueSwitch(*this, value, dests, defaultDest); // Bind arguments for cases that want them. for (unsigned i = 0, e = inst->getNumCases(); i < e; ++i) { auto casePair = inst->getCase(i); if (!casePair.second->args_empty()) { auto waypointBB = dests[i].second; auto &destLBB = getLoweredBB(casePair.second); Builder.emitBlock(waypointBB); Explosion inValue = getLoweredExplosion(inst->getOperand()); Explosion projected; emitProjectLoadableEnum(*this, inst->getOperand()->getType(), inValue, casePair.first, projected); unsigned phiIndex = 0; addIncomingExplosionToPHINodes(*this, destLBB, phiIndex, projected); Builder.CreateBr(destLBB.bb); } } } void IRGenSILFunction::visitSwitchEnumAddrInst(SwitchEnumAddrInst *inst) { Address value = getLoweredAddress(inst->getOperand()); // Map the SIL dest bbs to their LLVM bbs. SmallVector<std::pair<EnumElementDecl*, llvm::BasicBlock*>, 4> dests; llvm::BasicBlock *defaultDest = emitBBMapForSwitchEnum(*this, dests, inst); // Emit the dispatch. emitSwitchAddressOnlyEnumDispatch(*this, inst->getOperand()->getType(), value, dests, defaultDest); } // FIXME: We could lower select_enum directly to LLVM select in a lot of cases. // For now, just emit a switch and phi nodes, like a chump. template<class C, class T> static llvm::BasicBlock * emitBBMapForSelect(IRGenSILFunction &IGF, Explosion &resultPHI, SmallVectorImpl<std::pair<T, llvm::BasicBlock*>> &BBs, llvm::BasicBlock *&defaultBB, SelectInstBase<C, T> *inst) { auto origBB = IGF.Builder.GetInsertBlock(); // Set up a continuation BB and phi nodes to receive the result value. llvm::BasicBlock *contBB = IGF.createBasicBlock("select_enum"); IGF.Builder.SetInsertPoint(contBB); // Emit an explosion of phi node(s) to receive the value. SmallVector<llvm::Value*, 4> phis; auto &ti = IGF.getTypeInfo(inst->getType()); emitPHINodesForType(IGF, inst->getType(), ti, inst->getNumCases() + inst->hasDefault(), phis); resultPHI.add(phis); IGF.Builder.SetInsertPoint(origBB); auto addIncoming = [&](SILValue value) { if (value->getType().isAddress()) { addIncomingAddressToPHINodes(IGF, resultPHI.getAll(), IGF.getLoweredAddress(value)); } else { Explosion ex = IGF.getLoweredExplosion(value); addIncomingExplosionToPHINodes(IGF, resultPHI.getAll(), ex); } }; for (unsigned i = 0, e = inst->getNumCases(); i < e; ++i) { auto casePair = inst->getCase(i); // Create a basic block destination for this case. llvm::BasicBlock *destBB = IGF.createBasicBlock(""); IGF.Builder.emitBlock(destBB); // Feed the corresponding result into the phi nodes. addIncoming(casePair.second); // Jump immediately to the continuation. IGF.Builder.CreateBr(contBB); BBs.push_back(std::make_pair(casePair.first, destBB)); } if (inst->hasDefault()) { defaultBB = IGF.createBasicBlock(""); IGF.Builder.emitBlock(defaultBB); addIncoming(inst->getDefaultResult()); IGF.Builder.CreateBr(contBB); } else { defaultBB = nullptr; } IGF.Builder.emitBlock(contBB); IGF.Builder.SetInsertPoint(origBB); return contBB; } // Try to map the value of a select_enum directly to an int type with a simple // cast from the tag value to the result type. Optionally also by adding a // constant offset. // This is useful, e.g. for rawValue or hashValue of C-like enums. static llvm::Value * mapTriviallyToInt(IRGenSILFunction &IGF, const EnumImplStrategy &EIS, SelectEnumInst *inst) { // All cases must be covered if (inst->hasDefault()) return nullptr; auto &ti = IGF.getTypeInfo(inst->getType()); ExplosionSchema schema = ti.getSchema(); // Check if the select_enum's result is a single integer scalar. if (schema.size() != 1) return nullptr; if (!schema[0].isScalar()) return nullptr; llvm::Type *type = schema[0].getScalarType(); llvm::IntegerType *resultType = dyn_cast<llvm::IntegerType>(type); if (!resultType) return nullptr; // Check if the case values directly map to the tag values, maybe with a // constant offset. APInt commonOffset; bool offsetValid = false; for (unsigned i = 0, e = inst->getNumCases(); i < e; ++i) { auto casePair = inst->getCase(i); int64_t index = EIS.getDiscriminatorIndex(casePair.first); if (index < 0) return nullptr; IntegerLiteralInst *intLit = dyn_cast<IntegerLiteralInst>(casePair.second); if (!intLit) return nullptr; APInt caseValue = intLit->getValue(); APInt offset = caseValue - index; if (offsetValid) { if (offset != commonOffset) return nullptr; } else { commonOffset = offset; offsetValid = true; } } // Ask the enum implementation strategy to extract the enum tag as an integer // value. Explosion enumValue = IGF.getLoweredExplosion(inst->getEnumOperand()); llvm::Value *result = EIS.emitExtractDiscriminator(IGF, enumValue); if (!result) { (void)enumValue.claimAll(); return nullptr; } // Cast to the result type. result = IGF.Builder.CreateIntCast(result, resultType, false); if (commonOffset != 0) { // The offset, if any. auto *offsetConst = llvm::ConstantInt::get(resultType, commonOffset); result = IGF.Builder.CreateAdd(result, offsetConst); } return result; } template <class C, class T> static LoweredValue getLoweredValueForSelect(IRGenSILFunction &IGF, Explosion &result, SelectInstBase<C, T> *inst) { if (inst->getType().isAddress()) // FIXME: Loses potentially better alignment info we might have. return LoweredValue(Address(result.claimNext(), IGF.getTypeInfo(inst->getType()).getBestKnownAlignment())); return LoweredValue(result); } static void emitSingleEnumMemberSelectResult(IRGenSILFunction &IGF, SelectEnumInstBase *inst, llvm::Value *isTrue, Explosion &result) { assert((inst->getNumCases() == 1 && inst->hasDefault()) || (inst->getNumCases() == 2 && !inst->hasDefault())); // Extract the true values. auto trueValue = inst->getCase(0).second; SmallVector<llvm::Value*, 4> TrueValues; if (trueValue->getType().isAddress()) { TrueValues.push_back(IGF.getLoweredAddress(trueValue).getAddress()); } else { Explosion ex = IGF.getLoweredExplosion(trueValue); while (!ex.empty()) TrueValues.push_back(ex.claimNext()); } // Extract the false values. auto falseValue = inst->hasDefault() ? inst->getDefaultResult() : inst->getCase(1).second; SmallVector<llvm::Value*, 4> FalseValues; if (falseValue->getType().isAddress()) { FalseValues.push_back(IGF.getLoweredAddress(falseValue).getAddress()); } else { Explosion ex = IGF.getLoweredExplosion(falseValue); while (!ex.empty()) FalseValues.push_back(ex.claimNext()); } assert(TrueValues.size() == FalseValues.size() && "explosions didn't produce same element count?"); for (unsigned i = 0, e = FalseValues.size(); i != e; ++i) { auto *TV = TrueValues[i], *FV = FalseValues[i]; // It is pretty common to select between zero and 1 as the result of the // select. Instead of emitting an obviously dumb select, emit nothing or // a zext. if (auto *TC = dyn_cast<llvm::ConstantInt>(TV)) if (auto *FC = dyn_cast<llvm::ConstantInt>(FV)) if (TC->isOne() && FC->isZero()) { result.add(IGF.Builder.CreateZExtOrBitCast(isTrue, TV->getType())); continue; } result.add(IGF.Builder.CreateSelect(isTrue, TV, FalseValues[i])); } } void IRGenSILFunction::visitSelectEnumInst(SelectEnumInst *inst) { auto &EIS = getEnumImplStrategy(IGM, inst->getEnumOperand()->getType()); Explosion result; if (llvm::Value *R = mapTriviallyToInt(*this, EIS, inst)) { result.add(R); } else if ((inst->getNumCases() == 1 && inst->hasDefault()) || (inst->getNumCases() == 2 && !inst->hasDefault())) { // If this is testing for one case, do simpler codegen. This is // particularly common when testing optionals. Explosion value = getLoweredExplosion(inst->getEnumOperand()); auto isTrue = EIS.emitValueCaseTest(*this, value, inst->getCase(0).first); emitSingleEnumMemberSelectResult(*this, inst, isTrue, result); } else { Explosion value = getLoweredExplosion(inst->getEnumOperand()); // Map the SIL dest bbs to their LLVM bbs. SmallVector<std::pair<EnumElementDecl*, llvm::BasicBlock*>, 4> dests; llvm::BasicBlock *defaultDest; llvm::BasicBlock *contBB = emitBBMapForSelect(*this, result, dests, defaultDest, inst); // Emit the dispatch. EIS.emitValueSwitch(*this, value, dests, defaultDest); // emitBBMapForSelectEnum set up a continuation block and phi nodes to // receive the result. Builder.SetInsertPoint(contBB); } setLoweredValue(inst, getLoweredValueForSelect(*this, result, inst)); } void IRGenSILFunction::visitSelectEnumAddrInst(SelectEnumAddrInst *inst) { Address value = getLoweredAddress(inst->getEnumOperand()); Explosion result; if ((inst->getNumCases() == 1 && inst->hasDefault()) || (inst->getNumCases() == 2 && !inst->hasDefault())) { auto &EIS = getEnumImplStrategy(IGM, inst->getEnumOperand()->getType()); // If this is testing for one case, do simpler codegen. This is // particularly common when testing optionals. auto isTrue = EIS.emitIndirectCaseTest(*this, inst->getEnumOperand()->getType(), value, inst->getCase(0).first); emitSingleEnumMemberSelectResult(*this, inst, isTrue, result); } else { // Map the SIL dest bbs to their LLVM bbs. SmallVector<std::pair<EnumElementDecl*, llvm::BasicBlock*>, 4> dests; llvm::BasicBlock *defaultDest; llvm::BasicBlock *contBB = emitBBMapForSelect(*this, result, dests, defaultDest, inst); // Emit the dispatch. emitSwitchAddressOnlyEnumDispatch(*this, inst->getEnumOperand()->getType(), value, dests, defaultDest); // emitBBMapForSelectEnum set up a phi node to receive the result. Builder.SetInsertPoint(contBB); } setLoweredValue(inst, getLoweredValueForSelect(*this, result, inst)); } void IRGenSILFunction::visitSelectValueInst(SelectValueInst *inst) { Explosion value = getLoweredExplosion(inst->getOperand()); // Map the SIL dest bbs to their LLVM bbs. SmallVector<std::pair<SILValue, llvm::BasicBlock*>, 4> dests; llvm::BasicBlock *defaultDest; Explosion result; auto *contBB = emitBBMapForSelect(*this, result, dests, defaultDest, inst); // Emit the dispatch. emitSwitchValueDispatch(*this, inst->getOperand()->getType(), value, dests, defaultDest); // emitBBMapForSelectEnum set up a continuation block and phi nodes to // receive the result. Builder.SetInsertPoint(contBB); setLoweredValue(inst, getLoweredValueForSelect(*this, result, inst)); } void IRGenSILFunction::visitDynamicMethodBranchInst(DynamicMethodBranchInst *i){ LoweredBB &hasMethodBB = getLoweredBB(i->getHasMethodBB()); LoweredBB &noMethodBB = getLoweredBB(i->getNoMethodBB()); // Emit the respondsToSelector: call. StringRef selector; llvm::SmallString<64> selectorBuffer; if (auto fnDecl = dyn_cast<FuncDecl>(i->getMember().getDecl())) selector = fnDecl->getObjCSelector().getString(selectorBuffer); else if (auto var = dyn_cast<AbstractStorageDecl>(i->getMember().getDecl())) selector = var->getObjCGetterSelector().getString(selectorBuffer); else llvm_unreachable("Unhandled dynamic method branch query"); llvm::Value *object = getLoweredExplosion(i->getOperand()).claimNext(); if (object->getType() != IGM.ObjCPtrTy) object = Builder.CreateBitCast(object, IGM.ObjCPtrTy); llvm::Value *loadSel = emitObjCSelectorRefLoad(selector); llvm::Value *respondsToSelector = emitObjCSelectorRefLoad("respondsToSelector:"); llvm::Constant *messenger = IGM.getObjCMsgSendFn(); llvm::Type *argTys[] = { IGM.ObjCPtrTy, IGM.Int8PtrTy, IGM.Int8PtrTy, }; auto respondsToSelectorTy = llvm::FunctionType::get(IGM.Int1Ty, argTys, /*isVarArg*/ false) ->getPointerTo(); messenger = llvm::ConstantExpr::getBitCast(messenger, respondsToSelectorTy); llvm::CallInst *call = Builder.CreateCall(messenger, {object, respondsToSelector, loadSel}); call->setDoesNotThrow(); // FIXME: Assume (probably safely) that the hasMethodBB has only us as a // predecessor, and cannibalize its bb argument so we can represent is as an // ObjCMethod lowered value. This is hella gross but saves us having to // implement ObjCMethod-to-Explosion lowering and creating a thunk we don't // want. assert(std::next(i->getHasMethodBB()->pred_begin()) == i->getHasMethodBB()->pred_end() && "lowering dynamic_method_br with multiple preds for destination " "not implemented"); // Kill the existing lowered value for the bb arg and its phi nodes. SILValue methodArg = i->getHasMethodBB()->args_begin()[0]; Explosion formerLLArg = getLoweredExplosion(methodArg); for (llvm::Value *val : formerLLArg.claimAll()) { auto phi = cast<llvm::PHINode>(val); assert(phi->getNumIncomingValues() == 0 && "phi already used"); phi->removeFromParent(); delete phi; } LoweredValues.erase(methodArg); // Replace the lowered value with an ObjCMethod lowering. setLoweredObjCMethod(methodArg, i->getMember()); // Create the branch. Builder.CreateCondBr(call, hasMethodBB.bb, noMethodBB.bb); } void IRGenSILFunction::visitBranchInst(swift::BranchInst *i) { LoweredBB &lbb = getLoweredBB(i->getDestBB()); addIncomingSILArgumentsToPHINodes(*this, lbb, i->getArgs()); Builder.CreateBr(lbb.bb); } void IRGenSILFunction::visitCondBranchInst(swift::CondBranchInst *i) { LoweredBB &trueBB = getLoweredBB(i->getTrueBB()); LoweredBB &falseBB = getLoweredBB(i->getFalseBB()); llvm::Value *condValue = getLoweredExplosion(i->getCondition()).claimNext(); addIncomingSILArgumentsToPHINodes(*this, trueBB, i->getTrueArgs()); addIncomingSILArgumentsToPHINodes(*this, falseBB, i->getFalseArgs()); Builder.CreateCondBr(condValue, trueBB.bb, falseBB.bb); } void IRGenSILFunction::visitRetainValueInst(swift::RetainValueInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); Explosion out; cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType())) .copy(*this, in, out, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); (void)out.claimAll(); } void IRGenSILFunction::visitCopyValueInst(swift::CopyValueInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); Explosion out; cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType())) .copy(*this, in, out, getDefaultAtomicity()); setLoweredExplosion(i, out); } // TODO: Implement this more generally for arbitrary values. Currently the // SIL verifier restricts it to single-refcounted-pointer types. void IRGenSILFunction::visitAutoreleaseValueInst(swift::AutoreleaseValueInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); auto val = in.claimNext(); emitObjCAutoreleaseCall(val); } void IRGenSILFunction::visitSetDeallocatingInst(SetDeallocatingInst *i) { auto *ARI = dyn_cast<AllocRefInst>(i->getOperand()); if (ARI && StackAllocs.count(ARI)) { // A small peep-hole optimization: If the operand is allocated on stack and // there is no "significant" code between the set_deallocating and the final // dealloc_ref, the set_deallocating is not required. // %0 = alloc_ref [stack] // ... // set_deallocating %0 // not needed // // code which does not depend on the RC_DEALLOCATING_FLAG flag. // dealloc_ref %0 // not needed (stems from the inlined deallocator) // ... // dealloc_ref [stack] %0 SILBasicBlock::iterator Iter(i); SILBasicBlock::iterator End = i->getParent()->end(); for (++Iter; Iter != End; ++Iter) { SILInstruction *I = &*Iter; if (auto *DRI = dyn_cast<DeallocRefInst>(I)) { if (DRI->getOperand() == ARI) { // The set_deallocating is followed by a dealloc_ref -> we can ignore // it. return; } } // Assume that any instruction with side-effects may depend on the // RC_DEALLOCATING_FLAG flag. if (I->mayHaveSideEffects()) break; } } Explosion lowered = getLoweredExplosion(i->getOperand()); emitNativeSetDeallocating(lowered.claimNext()); } void IRGenSILFunction::visitReleaseValueInst(swift::ReleaseValueInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType())) .consume(*this, in, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); } void IRGenSILFunction::visitDestroyValueInst(swift::DestroyValueInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType())) .consume(*this, in, getDefaultAtomicity()); } void IRGenSILFunction::visitStructInst(swift::StructInst *i) { Explosion out; for (SILValue elt : i->getElements()) out.add(getLoweredExplosion(elt).claimAll()); setLoweredExplosion(i, out); } void IRGenSILFunction::visitTupleInst(swift::TupleInst *i) { Explosion out; for (SILValue elt : i->getElements()) out.add(getLoweredExplosion(elt).claimAll()); setLoweredExplosion(i, out); } void IRGenSILFunction::visitEnumInst(swift::EnumInst *i) { Explosion data = (i->hasOperand()) ? getLoweredExplosion(i->getOperand()) : Explosion(); Explosion out; emitInjectLoadableEnum(*this, i->getType(), i->getElement(), data, out); setLoweredExplosion(i, out); } void IRGenSILFunction::visitInitEnumDataAddrInst(swift::InitEnumDataAddrInst *i) { Address enumAddr = getLoweredAddress(i->getOperand()); Address dataAddr = emitProjectEnumAddressForStore(*this, i->getOperand()->getType(), enumAddr, i->getElement()); setLoweredAddress(i, dataAddr); } void IRGenSILFunction::visitUncheckedEnumDataInst(swift::UncheckedEnumDataInst *i) { Explosion enumVal = getLoweredExplosion(i->getOperand()); Explosion data; emitProjectLoadableEnum(*this, i->getOperand()->getType(), enumVal, i->getElement(), data); setLoweredExplosion(i, data); } void IRGenSILFunction::visitUncheckedTakeEnumDataAddrInst(swift::UncheckedTakeEnumDataAddrInst *i) { Address enumAddr = getLoweredAddress(i->getOperand()); Address dataAddr = emitDestructiveProjectEnumAddressForLoad(*this, i->getOperand()->getType(), enumAddr, i->getElement()); setLoweredAddress(i, dataAddr); } void IRGenSILFunction::visitInjectEnumAddrInst(swift::InjectEnumAddrInst *i) { Address enumAddr = getLoweredAddress(i->getOperand()); emitStoreEnumTagToAddress(*this, i->getOperand()->getType(), enumAddr, i->getElement()); } void IRGenSILFunction::visitTupleExtractInst(swift::TupleExtractInst *i) { Explosion fullTuple = getLoweredExplosion(i->getOperand()); Explosion output; SILType baseType = i->getOperand()->getType(); projectTupleElementFromExplosion(*this, baseType, fullTuple, i->getFieldNo(), output); (void)fullTuple.claimAll(); setLoweredExplosion(i, output); } void IRGenSILFunction::visitTupleElementAddrInst(swift::TupleElementAddrInst *i) { Address base = getLoweredAddress(i->getOperand()); SILType baseType = i->getOperand()->getType(); Address field = projectTupleElementAddress(*this, base, baseType, i->getFieldNo()); setLoweredAddress(i, field); } void IRGenSILFunction::visitStructExtractInst(swift::StructExtractInst *i) { Explosion operand = getLoweredExplosion(i->getOperand()); Explosion lowered; SILType baseType = i->getOperand()->getType(); projectPhysicalStructMemberFromExplosion(*this, baseType, operand, i->getField(), lowered); (void)operand.claimAll(); setLoweredExplosion(i, lowered); } void IRGenSILFunction::visitStructElementAddrInst( swift::StructElementAddrInst *i) { Address base = getLoweredAddress(i->getOperand()); SILType baseType = i->getOperand()->getType(); Address field = projectPhysicalStructMemberAddress(*this, base, baseType, i->getField()); setLoweredAddress(i, field); } void IRGenSILFunction::visitRefElementAddrInst(swift::RefElementAddrInst *i) { Explosion base = getLoweredExplosion(i->getOperand()); llvm::Value *value = base.claimNext(); SILType baseTy = i->getOperand()->getType(); Address field = projectPhysicalClassMemberAddress(*this, value, baseTy, i->getType(), i->getField()) .getAddress(); setLoweredAddress(i, field); } void IRGenSILFunction::visitRefTailAddrInst(RefTailAddrInst *i) { SILValue Ref = i->getOperand(); llvm::Value *RefValue = getLoweredExplosion(Ref).claimNext(); Address TailAddr = emitTailProjection(*this, RefValue, Ref->getType(), i->getTailType()); setLoweredAddress(i, TailAddr); } static bool isInvariantAddress(SILValue v) { auto root = getUnderlyingAddressRoot(v); if (auto ptrRoot = dyn_cast<PointerToAddressInst>(root)) { return ptrRoot->isInvariant(); } // TODO: We could be more aggressive about considering addresses based on // `let` variables as invariant when the type of the address is known not to // have any sharably-mutable interior storage (in other words, no weak refs, // atomics, etc.) return false; } void IRGenSILFunction::visitLoadInst(swift::LoadInst *i) { Explosion lowered; Address source = getLoweredAddress(i->getOperand()); SILType objType = i->getType().getObjectType(); const auto &typeInfo = cast<LoadableTypeInfo>(getTypeInfo(objType)); switch (i->getOwnershipQualifier()) { case LoadOwnershipQualifier::Unqualified: case LoadOwnershipQualifier::Trivial: case LoadOwnershipQualifier::Take: typeInfo.loadAsTake(*this, source, lowered); break; case LoadOwnershipQualifier::Copy: typeInfo.loadAsCopy(*this, source, lowered); break; } if (isInvariantAddress(i->getOperand())) { // It'd be better to push this down into `loadAs` methods, perhaps... for (auto value : lowered.getAll()) if (auto load = dyn_cast<llvm::LoadInst>(value)) setInvariantLoad(load); } setLoweredExplosion(i, lowered); } void IRGenSILFunction::visitStoreInst(swift::StoreInst *i) { Explosion source = getLoweredExplosion(i->getSrc()); Address dest = getLoweredAddress(i->getDest()); SILType objType = i->getSrc()->getType().getObjectType(); const auto &typeInfo = cast<LoadableTypeInfo>(getTypeInfo(objType)); switch (i->getOwnershipQualifier()) { case StoreOwnershipQualifier::Unqualified: case StoreOwnershipQualifier::Init: case StoreOwnershipQualifier::Trivial: typeInfo.initialize(*this, source, dest); break; case StoreOwnershipQualifier::Assign: typeInfo.assign(*this, source, dest); break; } } /// Emit the artificial error result argument. void IRGenSILFunction::emitErrorResultVar(SILResultInfo ErrorInfo, DebugValueInst *DbgValue) { // We don't need a shadow error variable for debugging on ABI's that return // swifterror in a register. if (IGM.IsSwiftErrorInRegister) return; auto ErrorResultSlot = getErrorResultSlot(IGM.silConv.getSILType(ErrorInfo)); SILDebugVariable Var = DbgValue->getVarInfo(); auto Storage = emitShadowCopy(ErrorResultSlot.getAddress(), getDebugScope(), Var.Name, Var.ArgNo); DebugTypeInfo DTI(nullptr, ErrorInfo.getType(), ErrorResultSlot->getType(), IGM.getPointerSize(), IGM.getPointerAlignment()); IGM.DebugInfo->emitVariableDeclaration(Builder, Storage, DTI, getDebugScope(), nullptr, Var.Name, Var.ArgNo, IndirectValue, ArtificialValue); } void IRGenSILFunction::visitDebugValueInst(DebugValueInst *i) { if (!IGM.DebugInfo) return; auto SILVal = i->getOperand(); if (isa<SILUndef>(SILVal)) { // We cannot track the location of inlined error arguments because it has no // representation in SIL. if (!i->getDebugScope()->InlinedCallSite && i->getVarInfo().Name == "$error") { auto funcTy = CurSILFn->getLoweredFunctionType(); emitErrorResultVar(funcTy->getErrorResult(), i); } return; } StringRef Name = getVarName(i); DebugTypeInfo DbgTy; SILType SILTy = SILVal->getType(); auto RealTy = SILVal->getType().getSwiftRValueType(); if (VarDecl *Decl = i->getDecl()) { DbgTy = DebugTypeInfo::getLocalVariable( CurSILFn->getDeclContext(), Decl, RealTy, getTypeInfo(SILVal->getType()), /*Unwrap=*/false); } else if (i->getFunction()->isBare() && !SILTy.hasArchetype() && !Name.empty()) { // Preliminary support for .sil debug information. DbgTy = DebugTypeInfo::getFromTypeInfo(CurSILFn->getDeclContext(), RealTy, getTypeInfo(SILTy)); } else return; // Put the value into a stack slot at -Onone. llvm::SmallVector<llvm::Value *, 8> Copy; Explosion e = getLoweredExplosion(SILVal); unsigned ArgNo = i->getVarInfo().ArgNo; emitShadowCopy(e.claimAll(), i->getDebugScope(), Name, ArgNo, Copy); emitDebugVariableDeclaration(Copy, DbgTy, SILTy, i->getDebugScope(), i->getDecl(), Name, ArgNo); } void IRGenSILFunction::visitDebugValueAddrInst(DebugValueAddrInst *i) { if (!IGM.DebugInfo) return; VarDecl *Decl = i->getDecl(); if (!Decl) return; auto SILVal = i->getOperand(); if (isa<SILUndef>(SILVal)) return; StringRef Name = getVarName(i); auto Addr = getLoweredAddress(SILVal).getAddress(); SILType SILTy = SILVal->getType(); auto RealType = SILTy.getSwiftRValueType(); if (SILTy.isAddress()) RealType = CanInOutType::get(RealType); // Unwrap implicitly indirect types and types that are passed by // reference only at the SIL level and below. // // FIXME: Should this check if the lowered SILType is address only // instead? Otherwise optionals of archetypes etc will still have // 'Unwrap' set to false. bool Unwrap = i->getVarInfo().Constant || SILTy.is<ArchetypeType>(); auto DbgTy = DebugTypeInfo::getLocalVariable( CurSILFn->getDeclContext(), Decl, RealType, getTypeInfo(SILVal->getType()), Unwrap); // Put the value's address into a stack slot at -Onone and emit a debug // intrinsic. unsigned ArgNo = i->getVarInfo().ArgNo; emitDebugVariableDeclaration( emitShadowCopy(Addr, i->getDebugScope(), Name, ArgNo), DbgTy, i->getType(), i->getDebugScope(), Decl, Name, ArgNo, DbgTy.isImplicitlyIndirect() ? DirectValue : IndirectValue); } void IRGenSILFunction::visitLoadWeakInst(swift::LoadWeakInst *i) { Address source = getLoweredAddress(i->getOperand()); auto &weakTI = cast<WeakTypeInfo>(getTypeInfo(i->getOperand()->getType())); Explosion result; if (i->isTake()) { weakTI.weakTakeStrong(*this, source, result); } else { weakTI.weakLoadStrong(*this, source, result); } setLoweredExplosion(i, result); } void IRGenSILFunction::visitStoreWeakInst(swift::StoreWeakInst *i) { Explosion source = getLoweredExplosion(i->getSrc()); Address dest = getLoweredAddress(i->getDest()); auto &weakTI = cast<WeakTypeInfo>(getTypeInfo(i->getDest()->getType())); if (i->isInitializationOfDest()) { weakTI.weakInit(*this, source, dest); } else { weakTI.weakAssign(*this, source, dest); } } void IRGenSILFunction::visitFixLifetimeInst(swift::FixLifetimeInst *i) { if (i->getOperand()->getType().isAddress()) { // Just pass in the address to fix lifetime if we have one. We will not do // anything to it so nothing bad should happen. emitFixLifetime(getLoweredAddress(i->getOperand()).getAddress()); return; } // Handle objects. Explosion in = getLoweredExplosion(i->getOperand()); cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType())) .fixLifetime(*this, in); } void IRGenSILFunction::visitMarkDependenceInst(swift::MarkDependenceInst *i) { // Dependency-marking is purely for SIL. Just forward the input as // the result. SILValue value = i->getValue(); if (value->getType().isAddress()) { setLoweredAddress(i, getLoweredAddress(value)); } else { Explosion temp = getLoweredExplosion(value); setLoweredExplosion(i, temp); } } void IRGenSILFunction::visitCopyBlockInst(CopyBlockInst *i) { Explosion lowered = getLoweredExplosion(i->getOperand()); llvm::Value *copied = emitBlockCopyCall(lowered.claimNext()); Explosion result; result.add(copied); setLoweredExplosion(i, result); } void IRGenSILFunction::visitStrongPinInst(swift::StrongPinInst *i) { Explosion lowered = getLoweredExplosion(i->getOperand()); llvm::Value *object = lowered.claimNext(); llvm::Value *pinHandle = emitNativeTryPin(object, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); Explosion result; result.add(pinHandle); setLoweredExplosion(i, result); } void IRGenSILFunction::visitStrongUnpinInst(swift::StrongUnpinInst *i) { Explosion lowered = getLoweredExplosion(i->getOperand()); llvm::Value *pinHandle = lowered.claimNext(); emitNativeUnpin(pinHandle, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); } void IRGenSILFunction::visitStrongRetainInst(swift::StrongRetainInst *i) { Explosion lowered = getLoweredExplosion(i->getOperand()); auto &ti = cast<ReferenceTypeInfo>(getTypeInfo(i->getOperand()->getType())); ti.strongRetain(*this, lowered, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); } void IRGenSILFunction::visitStrongReleaseInst(swift::StrongReleaseInst *i) { Explosion lowered = getLoweredExplosion(i->getOperand()); auto &ti = cast<ReferenceTypeInfo>(getTypeInfo(i->getOperand()->getType())); ti.strongRelease(*this, lowered, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); } /// Given a SILType which is a ReferenceStorageType, return the type /// info for the underlying reference type. static const ReferenceTypeInfo &getReferentTypeInfo(IRGenFunction &IGF, SILType silType) { auto type = silType.castTo<ReferenceStorageType>().getReferentType(); return cast<ReferenceTypeInfo>(IGF.getTypeInfoForLowered(type)); } void IRGenSILFunction:: visitStrongRetainUnownedInst(swift::StrongRetainUnownedInst *i) { Explosion lowered = getLoweredExplosion(i->getOperand()); auto &ti = getReferentTypeInfo(*this, i->getOperand()->getType()); ti.strongRetainUnowned(*this, lowered, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); } void IRGenSILFunction::visitUnownedRetainInst(swift::UnownedRetainInst *i) { Explosion lowered = getLoweredExplosion(i->getOperand()); auto &ti = getReferentTypeInfo(*this, i->getOperand()->getType()); ti.unownedRetain(*this, lowered, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); } void IRGenSILFunction::visitUnownedReleaseInst(swift::UnownedReleaseInst *i) { Explosion lowered = getLoweredExplosion(i->getOperand()); auto &ti = getReferentTypeInfo(*this, i->getOperand()->getType()); ti.unownedRelease(*this, lowered, i->isAtomic() ? irgen::Atomicity::Atomic : irgen::Atomicity::NonAtomic); } void IRGenSILFunction::visitLoadUnownedInst(swift::LoadUnownedInst *i) { Address source = getLoweredAddress(i->getOperand()); auto &ti = getReferentTypeInfo(*this, i->getOperand()->getType()); Explosion result; if (i->isTake()) { ti.unownedTakeStrong(*this, source, result); } else { ti.unownedLoadStrong(*this, source, result); } setLoweredExplosion(i, result); } void IRGenSILFunction::visitStoreUnownedInst(swift::StoreUnownedInst *i) { Explosion source = getLoweredExplosion(i->getSrc()); Address dest = getLoweredAddress(i->getDest()); auto &ti = getReferentTypeInfo(*this, i->getDest()->getType()); if (i->isInitializationOfDest()) { ti.unownedInit(*this, source, dest); } else { ti.unownedAssign(*this, source, dest); } } static bool hasReferenceSemantics(IRGenSILFunction &IGF, SILType silType) { auto operType = silType.getSwiftRValueType(); auto valueType = operType->getAnyOptionalObjectType(); auto objType = valueType ? valueType : operType; return (objType->mayHaveSuperclass() || objType->isClassExistentialType() || objType->is<BuiltinNativeObjectType>() || objType->is<BuiltinBridgeObjectType>() || objType->is<BuiltinUnknownObjectType>()); } static llvm::Value *emitIsUnique(IRGenSILFunction &IGF, SILValue operand, SourceLoc loc, bool checkPinned) { if (!hasReferenceSemantics(IGF, operand->getType())) { llvm::Function *trapIntrinsic = llvm::Intrinsic::getDeclaration( &IGF.IGM.Module, llvm::Intrinsic::ID::trap); IGF.Builder.CreateCall(trapIntrinsic, {}); return llvm::UndefValue::get(IGF.IGM.Int1Ty); } auto &operTI = cast<LoadableTypeInfo>(IGF.getTypeInfo(operand->getType())); LoadedRef ref = operTI.loadRefcountedPtr(IGF, loc, IGF.getLoweredAddress(operand)); return IGF.emitIsUniqueCall(ref.getValue(), loc, ref.isNonNull(), checkPinned); } void IRGenSILFunction::visitIsUniqueInst(swift::IsUniqueInst *i) { llvm::Value *result = emitIsUnique(*this, i->getOperand(), i->getLoc().getSourceLoc(), false); Explosion out; out.add(result); setLoweredExplosion(i, out); } void IRGenSILFunction:: visitIsUniqueOrPinnedInst(swift::IsUniqueOrPinnedInst *i) { llvm::Value *result = emitIsUnique(*this, i->getOperand(), i->getLoc().getSourceLoc(), true); Explosion out; out.add(result); setLoweredExplosion(i, out); } static bool tryDeferFixedSizeBufferInitialization(IRGenSILFunction &IGF, SILInstruction *allocInst, const TypeInfo &ti, Address fixedSizeBuffer, const llvm::Twine &name) { // There's no point in doing this for fixed-sized types, since we'll allocate // an appropriately-sized buffer for them statically. if (ti.isFixedSize()) return false; // TODO: More interesting dominance analysis could be done here to see // if the alloc_stack is dominated by copy_addrs into it on all paths. // For now, check only that the copy_addr is the first use within the same // block. for (auto ii = std::next(allocInst->getIterator()), ie = std::prev(allocInst->getParent()->end()); ii != ie; ++ii) { auto *inst = &*ii; // Does this instruction use the allocation? If not, continue. auto Ops = inst->getAllOperands(); if (std::none_of(Ops.begin(), Ops.end(), [allocInst](const Operand &Op) { return Op.get() == allocInst; })) continue; // Is this a copy? auto *copy = dyn_cast<swift::CopyAddrInst>(inst); if (!copy) return false; // Destination must be the allocation. if (copy->getDest() != SILValue(allocInst)) return false; // Copy must be an initialization. if (!copy->isInitializationOfDest()) return false; // We can defer to this initialization. Allocate the fixed-size buffer // now, but don't allocate the value inside it. if (!fixedSizeBuffer.getAddress()) { fixedSizeBuffer = IGF.createFixedSizeBufferAlloca(name); IGF.Builder.CreateLifetimeStart(fixedSizeBuffer, getFixedBufferSize(IGF.IGM)); } IGF.setContainerOfUnallocatedAddress(allocInst, fixedSizeBuffer); return true; } return false; } void IRGenSILFunction::emitDebugInfoForAllocStack(AllocStackInst *i, const TypeInfo &type, llvm::Value *addr) { VarDecl *Decl = i->getDecl(); if (IGM.DebugInfo && Decl) { // Ignore compiler-generated patterns but not optional bindings. if (auto *Pattern = Decl->getParentPattern()) if (Pattern->isImplicit() && Pattern->getKind() != PatternKind::OptionalSome) return; SILType SILTy = i->getType(); auto RealType = SILTy.getSwiftRValueType(); auto DbgTy = DebugTypeInfo::getLocalVariable(CurSILFn->getDeclContext(), Decl, RealType, type, false); StringRef Name = getVarName(i); if (auto DS = i->getDebugScope()) emitDebugVariableDeclaration(addr, DbgTy, SILTy, DS, Decl, Name, i->getVarInfo().ArgNo); } } void IRGenSILFunction::visitAllocStackInst(swift::AllocStackInst *i) { const TypeInfo &type = getTypeInfo(i->getElementType()); // Derive name from SIL location. VarDecl *Decl = i->getDecl(); StringRef dbgname; # ifndef NDEBUG // If this is a DEBUG build, use pretty names for the LLVM IR. dbgname = getVarName(i); # endif (void) Decl; bool isEntryBlock = i->getParentBlock() == i->getFunction()->getEntryBlock(); auto addr = type.allocateStack(*this, i->getElementType(), isEntryBlock, dbgname); emitDebugInfoForAllocStack(i, type, addr.getAddress().getAddress()); setLoweredStackAddress(i, addr); } static void buildTailArrays(IRGenSILFunction &IGF, SmallVectorImpl<std::pair<SILType, llvm::Value *>> &TailArrays, AllocRefInstBase *ARI) { auto Types = ARI->getTailAllocatedTypes(); auto Counts = ARI->getTailAllocatedCounts(); for (unsigned Idx = 0, NumTypes = Types.size(); Idx < NumTypes; ++Idx) { Explosion ElemCount = IGF.getLoweredExplosion(Counts[Idx].get()); TailArrays.push_back({Types[Idx], ElemCount.claimNext()}); } } void IRGenSILFunction::visitAllocRefInst(swift::AllocRefInst *i) { int StackAllocSize = -1; if (i->canAllocOnStack()) { estimateStackSize(); // Is there enough space for stack allocation? StackAllocSize = IGM.IRGen.Opts.StackPromotionSizeLimit - EstimatedStackSize; } SmallVector<std::pair<SILType, llvm::Value *>, 4> TailArrays; buildTailArrays(*this, TailArrays, i); llvm::Value *alloced = emitClassAllocation(*this, i->getType(), i->isObjC(), StackAllocSize, TailArrays); if (StackAllocSize >= 0) { // Remember that this alloc_ref allocates the object on the stack. StackAllocs.insert(i); EstimatedStackSize += StackAllocSize; } Explosion e; e.add(alloced); setLoweredExplosion(i, e); } void IRGenSILFunction::visitAllocRefDynamicInst(swift::AllocRefDynamicInst *i) { SmallVector<std::pair<SILType, llvm::Value *>, 4> TailArrays; buildTailArrays(*this, TailArrays, i); Explosion metadata = getLoweredExplosion(i->getMetatypeOperand()); auto metadataValue = metadata.claimNext(); llvm::Value *alloced = emitClassAllocationDynamic(*this, metadataValue, i->getType(), i->isObjC(), TailArrays); Explosion e; e.add(alloced); setLoweredExplosion(i, e); } void IRGenSILFunction::visitDeallocStackInst(swift::DeallocStackInst *i) { auto allocatedType = i->getOperand()->getType(); const TypeInfo &allocatedTI = getTypeInfo(allocatedType); StackAddress stackAddr = getLoweredStackAddress(i->getOperand()); allocatedTI.deallocateStack(*this, stackAddr, allocatedType); } void IRGenSILFunction::visitDeallocRefInst(swift::DeallocRefInst *i) { // Lower the operand. Explosion self = getLoweredExplosion(i->getOperand()); auto selfValue = self.claimNext(); auto *ARI = dyn_cast<AllocRefInst>(i->getOperand()); if (!i->canAllocOnStack()) { if (ARI && StackAllocs.count(ARI)) { // We can ignore dealloc_refs (without [stack]) for stack allocated // objects. // // %0 = alloc_ref [stack] // ... // dealloc_ref %0 // not needed (stems from the inlined deallocator) // ... // dealloc_ref [stack] %0 return; } auto classType = i->getOperand()->getType(); emitClassDeallocation(*this, classType, selfValue); return; } // It's a dealloc_ref [stack]. Even if the alloc_ref did not allocate the // object on the stack, we don't have to deallocate it, because it is // deallocated in the final release. assert(ARI->canAllocOnStack()); if (StackAllocs.count(ARI)) { if (IGM.IRGen.Opts.EmitStackPromotionChecks) { selfValue = Builder.CreateBitCast(selfValue, IGM.RefCountedPtrTy); emitVerifyEndOfLifetimeCall(selfValue); } else { // This has two purposes: // 1. Tell LLVM the lifetime of the allocated stack memory. // 2. Avoid tail-call optimization which may convert the call to the final // release to a jump, which is done after the stack frame is // destructed. Builder.CreateLifetimeEnd(selfValue); } } } void IRGenSILFunction::visitDeallocPartialRefInst(swift::DeallocPartialRefInst *i) { Explosion self = getLoweredExplosion(i->getInstance()); auto selfValue = self.claimNext(); Explosion metadata = getLoweredExplosion(i->getMetatype()); auto metadataValue = metadata.claimNext(); auto classType = i->getInstance()->getType(); emitPartialClassDeallocation(*this, classType, selfValue, metadataValue); } void IRGenSILFunction::visitDeallocBoxInst(swift::DeallocBoxInst *i) { Explosion owner = getLoweredExplosion(i->getOperand()); llvm::Value *ownerPtr = owner.claimNext(); auto boxTy = i->getOperand()->getType().castTo<SILBoxType>(); emitDeallocateBox(*this, ownerPtr, boxTy); } void IRGenSILFunction::visitAllocBoxInst(swift::AllocBoxInst *i) { assert(i->getBoxType()->getLayout()->getFields().size() == 1 && "multi field boxes not implemented yet"); const TypeInfo &type = getTypeInfo(i->getBoxType() ->getFieldType(IGM.getSILModule(), 0)); // Derive name from SIL location. VarDecl *Decl = i->getDecl(); StringRef Name = getVarName(i); StringRef DbgName = # ifndef NDEBUG // If this is a DEBUG build, use pretty names for the LLVM IR. Name; # else ""; # endif auto boxTy = i->getType().castTo<SILBoxType>(); OwnedAddress boxWithAddr = emitAllocateBox(*this, boxTy, CurSILFn->getGenericEnvironment(), DbgName); setLoweredBox(i, boxWithAddr); if (IGM.DebugInfo && Decl) { // FIXME: This is a workaround to not produce local variables for // capture list arguments like "[weak self]". The better solution // would be to require all variables to be described with a // SILDebugValue(Addr) and then not describe capture list // arguments. if (Name == IGM.Context.Id_self.str()) return; assert(i->getBoxType()->getLayout()->getFields().size() == 1 && "box for a local variable should only have one field"); auto SILTy = i->getBoxType()->getFieldType(IGM.getSILModule(), 0); auto RealType = SILTy.getSwiftRValueType(); if (SILTy.isAddress()) RealType = CanInOutType::get(RealType); auto DbgTy = DebugTypeInfo::getLocalVariable( CurSILFn->getDeclContext(), Decl, RealType, type, /*Unwrap=*/false); if (isInlinedGeneric(Decl, i->getDebugScope())) return; IGM.DebugInfo->emitVariableDeclaration( Builder, emitShadowCopy(boxWithAddr.getAddress(), i->getDebugScope(), Name, 0), DbgTy, i->getDebugScope(), Decl, Name, 0, DbgTy.isImplicitlyIndirect() ? DirectValue : IndirectValue); } } void IRGenSILFunction::visitProjectBoxInst(swift::ProjectBoxInst *i) { auto boxTy = i->getOperand()->getType().castTo<SILBoxType>(); const LoweredValue &val = getLoweredValue(i->getOperand()); if (val.isBoxWithAddress()) { // The operand is an alloc_box. We can directly reuse the address. setLoweredAddress(i, val.getAddressOfBox()); } else { // The slow-path: we have to emit code to get from the box to it's // value address. Explosion box = val.getExplosion(*this); auto addr = emitProjectBox(*this, box.claimNext(), boxTy); setLoweredAddress(i, addr); } } static void emitBeginAccess(IRGenSILFunction &IGF, BeginAccessInst *access, Address addr) { switch (access->getEnforcement()) { case SILAccessEnforcement::Unknown: llvm_unreachable("unknown access enforcement in IRGen!"); case SILAccessEnforcement::Static: case SILAccessEnforcement::Unsafe: // nothing to do return; case SILAccessEnforcement::Dynamic: // TODO return; } llvm_unreachable("bad access enforcement"); } static void emitEndAccess(IRGenSILFunction &IGF, BeginAccessInst *access) { switch (access->getEnforcement()) { case SILAccessEnforcement::Unknown: llvm_unreachable("unknown access enforcement in IRGen!"); case SILAccessEnforcement::Static: case SILAccessEnforcement::Unsafe: // nothing to do return; case SILAccessEnforcement::Dynamic: // TODO return; } llvm_unreachable("bad access enforcement"); } void IRGenSILFunction::visitBeginAccessInst(BeginAccessInst *i) { Address addr = getLoweredAddress(i->getOperand()); emitBeginAccess(*this, i, addr); setLoweredAddress(i, addr); } void IRGenSILFunction::visitEndAccessInst(EndAccessInst *i) { emitEndAccess(*this, i->getBeginAccess()); } void IRGenSILFunction::visitConvertFunctionInst(swift::ConvertFunctionInst *i) { // This instruction is specified to be a no-op. Explosion temp = getLoweredExplosion(i->getOperand()); setLoweredExplosion(i, temp); } void IRGenSILFunction::visitThinFunctionToPointerInst( swift::ThinFunctionToPointerInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); llvm::Value *fn = in.claimNext(); fn = Builder.CreateBitCast(fn, IGM.Int8PtrTy); Explosion out; out.add(fn); setLoweredExplosion(i, out); } void IRGenSILFunction::visitPointerToThinFunctionInst( swift::PointerToThinFunctionInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); llvm::Value *fn = in.claimNext(); fn = Builder.CreateBitCast(fn, IGM.FunctionPtrTy); Explosion out; out.add(fn); setLoweredExplosion(i, out); } void IRGenSILFunction::visitAddressToPointerInst(swift::AddressToPointerInst *i) { Explosion to; llvm::Value *addrValue = getLoweredAddress(i->getOperand()).getAddress(); if (addrValue->getType() != IGM.Int8PtrTy) addrValue = Builder.CreateBitCast(addrValue, IGM.Int8PtrTy); to.add(addrValue); setLoweredExplosion(i, to); } // Ignores the isStrict flag because Swift TBAA is not lowered into LLVM IR. void IRGenSILFunction::visitPointerToAddressInst(swift::PointerToAddressInst *i) { Explosion from = getLoweredExplosion(i->getOperand()); llvm::Value *ptrValue = from.claimNext(); auto &ti = getTypeInfo(i->getType()); llvm::Type *destType = ti.getStorageType()->getPointerTo(); ptrValue = Builder.CreateBitCast(ptrValue, destType); setLoweredAddress(i, ti.getAddressForPointer(ptrValue)); } static void emitPointerCastInst(IRGenSILFunction &IGF, SILValue src, SILValue dest, const TypeInfo &ti) { Explosion from = IGF.getLoweredExplosion(src); llvm::Value *ptrValue = from.claimNext(); // The input may have witness tables or other additional data, but the class // reference is always first. (void)from.claimAll(); auto schema = ti.getSchema(); assert(schema.size() == 1 && schema[0].isScalar() && "pointer schema is not a single scalar?!"); auto castToType = schema[0].getScalarType(); // A retainable pointer representation may be wrapped in an optional, so we // need to provide inttoptr/ptrtoint in addition to bitcast. ptrValue = IGF.Builder.CreateBitOrPointerCast(ptrValue, castToType); Explosion to; to.add(ptrValue); IGF.setLoweredExplosion(dest, to); } void IRGenSILFunction::visitUncheckedRefCastInst( swift::UncheckedRefCastInst *i) { auto &ti = getTypeInfo(i->getType()); emitPointerCastInst(*this, i->getOperand(), i, ti); } // TODO: Although runtime checks are not required, we get them anyway when // asking the runtime to perform this cast. If this is a performance impact, we // can add a CheckedCastMode::Unchecked. void IRGenSILFunction:: visitUncheckedRefCastAddrInst(swift::UncheckedRefCastAddrInst *i) { Address dest = getLoweredAddress(i->getDest()); Address src = getLoweredAddress(i->getSrc()); emitCheckedCast(*this, src, i->getSourceType(), dest, i->getTargetType(), i->getConsumptionKind(), CheckedCastMode::Unconditional); } void IRGenSILFunction::visitUncheckedAddrCastInst( swift::UncheckedAddrCastInst *i) { auto addr = getLoweredAddress(i->getOperand()); auto &ti = getTypeInfo(i->getType()); auto result = Builder.CreateBitCast(addr,ti.getStorageType()->getPointerTo()); setLoweredAddress(i, result); } static bool isStructurallySame(const llvm::Type *T1, const llvm::Type *T2) { if (T1 == T2) return true; if (auto *S1 = dyn_cast<llvm::StructType>(T1)) if (auto *S2 = dyn_cast<llvm::StructType>(T2)) return S1->isLayoutIdentical(const_cast<llvm::StructType*>(S2)); return false; } // Emit a trap in the event a type does not match expected layout constraints. // // We can hit this case in specialized functions even for correct user code. // If the user dynamically checks for correct type sizes in the generic // function, a specialized function can contain the (not executed) bitcast // with mismatching fixed sizes. // Usually llvm can eliminate this code again because the user's safety // check should be constant foldable on llvm level. static void emitTrapAndUndefValue(IRGenSILFunction &IGF, Explosion &in, Explosion &out, const LoadableTypeInfo &outTI) { llvm::BasicBlock *failBB = llvm::BasicBlock::Create(IGF.IGM.getLLVMContext()); IGF.Builder.CreateBr(failBB); IGF.FailBBs.push_back(failBB); IGF.Builder.emitBlock(failBB); llvm::Function *trapIntrinsic = llvm::Intrinsic::getDeclaration( &IGF.IGM.Module, llvm::Intrinsic::ID::trap); IGF.Builder.CreateCall(trapIntrinsic, {}); IGF.Builder.CreateUnreachable(); llvm::BasicBlock *contBB = llvm::BasicBlock::Create(IGF.IGM.getLLVMContext()); IGF.Builder.emitBlock(contBB); (void)in.claimAll(); for (auto schema : outTI.getSchema()) out.add(llvm::UndefValue::get(schema.getScalarType())); } static void emitUncheckedValueBitCast(IRGenSILFunction &IGF, SourceLoc loc, Explosion &in, const LoadableTypeInfo &inTI, Explosion &out, const LoadableTypeInfo &outTI) { // If the transfer is doable bitwise, and if the elements of the explosion are // the same type, then just transfer the elements. if (inTI.isBitwiseTakable(ResilienceExpansion::Maximal) && outTI.isBitwiseTakable(ResilienceExpansion::Maximal) && isStructurallySame(inTI.getStorageType(), outTI.getStorageType())) { in.transferInto(out, in.size()); return; } // TODO: We could do bitcasts entirely in the value domain in some cases, but // for simplicity, let's just always go through the stack for now. // Create the allocation. auto inStorage = IGF.createAlloca(inTI.getStorageType(), std::max(inTI.getFixedAlignment(), outTI.getFixedAlignment()), "bitcast"); auto maxSize = std::max(inTI.getFixedSize(), outTI.getFixedSize()); IGF.Builder.CreateLifetimeStart(inStorage, maxSize); // Store the 'in' value. inTI.initialize(IGF, in, inStorage); // Load the 'out' value as the destination type. auto outStorage = IGF.Builder.CreateBitCast(inStorage, outTI.getStorageType()->getPointerTo()); outTI.loadAsTake(IGF, outStorage, out); IGF.Builder.CreateLifetimeEnd(inStorage, maxSize); return; } static void emitValueBitwiseCast(IRGenSILFunction &IGF, SourceLoc loc, Explosion &in, const LoadableTypeInfo &inTI, Explosion &out, const LoadableTypeInfo &outTI) { // Unfortunately, we can't check this invariant until we get to IRGen, since // the AST and SIL don't know anything about type layout. if (inTI.getFixedSize() < outTI.getFixedSize()) { emitTrapAndUndefValue(IGF, in, out, outTI); return; } emitUncheckedValueBitCast(IGF, loc, in, inTI, out, outTI); } void IRGenSILFunction::visitUncheckedTrivialBitCastInst( swift::UncheckedTrivialBitCastInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); Explosion out; emitValueBitwiseCast(*this, i->getLoc().getSourceLoc(), in, cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType())), out, cast<LoadableTypeInfo>(getTypeInfo(i->getType()))); setLoweredExplosion(i, out); } void IRGenSILFunction:: visitUncheckedBitwiseCastInst(swift::UncheckedBitwiseCastInst *i) { Explosion in = getLoweredExplosion(i->getOperand()); Explosion out; emitValueBitwiseCast(*this, i->getLoc().getSourceLoc(), in, cast<LoadableTypeInfo>(getTypeInfo(i->getOperand()->getType())), out, cast<LoadableTypeInfo>(getTypeInfo(i->getType()))); setLoweredExplosion(i, out); } void IRGenSILFunction::visitRefToRawPointerInst( swift::RefToRawPointerInst *i) { auto &ti = getTypeInfo(i->getType()); emitPointerCastInst(*this, i->getOperand(), i, ti); } void IRGenSILFunction::visitRawPointerToRefInst(swift::RawPointerToRefInst *i) { auto &ti = getTypeInfo(i->getType()); emitPointerCastInst(*this, i->getOperand(), i, ti); } // SIL scalar conversions which never change the IR type. // FIXME: Except for optionals, which get bit-packed into an integer. static void trivialRefConversion(IRGenSILFunction &IGF, SILValue input, SILValue result) { Explosion temp = IGF.getLoweredExplosion(input); auto &inputTI = IGF.getTypeInfo(input->getType()); auto &resultTI = IGF.getTypeInfo(result->getType()); // If the types are the same, forward the existing value. if (inputTI.getStorageType() == resultTI.getStorageType()) { IGF.setLoweredExplosion(result, temp); return; } auto schema = resultTI.getSchema(); Explosion out; for (auto schemaElt : schema) { auto resultTy = schemaElt.getScalarType(); llvm::Value *value = temp.claimNext(); if (value->getType() == resultTy) { // Nothing to do. This happens with the unowned conversions. } else if (resultTy->isPointerTy()) { value = IGF.Builder.CreateIntToPtr(value, resultTy); } else { value = IGF.Builder.CreatePtrToInt(value, resultTy); } out.add(value); } IGF.setLoweredExplosion(result, out); } // SIL scalar conversions which never change the IR type. // FIXME: Except for optionals, which get bit-packed into an integer. #define NOOP_CONVERSION(KIND) \ void IRGenSILFunction::visit##KIND##Inst(swift::KIND##Inst *i) { \ ::trivialRefConversion(*this, i->getOperand(), i); \ } NOOP_CONVERSION(UnownedToRef) NOOP_CONVERSION(RefToUnowned) NOOP_CONVERSION(UnmanagedToRef) NOOP_CONVERSION(RefToUnmanaged) #undef NOOP_CONVERSION void IRGenSILFunction::visitThinToThickFunctionInst( swift::ThinToThickFunctionInst *i) { // Take the incoming function pointer and add a null context pointer to it. Explosion from = getLoweredExplosion(i->getOperand()); Explosion to; to.add(from.claimNext()); to.add(IGM.RefCountedNull); setLoweredExplosion(i, to); } void IRGenSILFunction::visitThickToObjCMetatypeInst(ThickToObjCMetatypeInst *i){ Explosion from = getLoweredExplosion(i->getOperand()); llvm::Value *swiftMeta = from.claimNext(); CanType instanceType(i->getType().castTo<AnyMetatypeType>().getInstanceType()); Explosion to; llvm::Value *classPtr = emitClassHeapMetadataRefForMetatype(*this, swiftMeta, instanceType); to.add(Builder.CreateBitCast(classPtr, IGM.ObjCClassPtrTy)); setLoweredExplosion(i, to); } void IRGenSILFunction::visitObjCToThickMetatypeInst( ObjCToThickMetatypeInst *i) { Explosion from = getLoweredExplosion(i->getOperand()); llvm::Value *classPtr = from.claimNext(); // Fetch the metadata for that class. Explosion to; auto metadata = emitObjCMetadataRefForMetadata(*this, classPtr); to.add(metadata); setLoweredExplosion(i, to); } void IRGenSILFunction::visitUnconditionalCheckedCastInst( swift::UnconditionalCheckedCastInst *i) { Explosion value = getLoweredExplosion(i->getOperand()); Explosion ex; emitScalarCheckedCast(*this, value, i->getOperand()->getType(), i->getType(), CheckedCastMode::Unconditional, ex); setLoweredExplosion(i, ex); } void IRGenSILFunction::visitObjCMetatypeToObjectInst( ObjCMetatypeToObjectInst *i){ // Bitcast the @objc metatype reference, which is already an ObjC object, to // the destination type. Explosion from = getLoweredExplosion(i->getOperand()); llvm::Value *value = from.claimNext(); value = Builder.CreateBitCast(value, IGM.UnknownRefCountedPtrTy); Explosion to; to.add(value); setLoweredExplosion(i, to); } void IRGenSILFunction::visitObjCExistentialMetatypeToObjectInst( ObjCExistentialMetatypeToObjectInst *i){ // Bitcast the @objc metatype reference, which is already an ObjC object, to // the destination type. The metatype may carry additional witness tables we // can drop. Explosion from = getLoweredExplosion(i->getOperand()); llvm::Value *value = from.claimNext(); (void)from.claimAll(); value = Builder.CreateBitCast(value, IGM.UnknownRefCountedPtrTy); Explosion to; to.add(value); setLoweredExplosion(i, to); } void IRGenSILFunction::visitObjCProtocolInst(ObjCProtocolInst *i) { // Get the protocol reference. llvm::Value *protoRef = emitReferenceToObjCProtocol(*this, i->getProtocol()); // Bitcast it to the class reference type. protoRef = Builder.CreateBitCast(protoRef, getTypeInfo(i->getType()).getStorageType()); Explosion ex; ex.add(protoRef); setLoweredExplosion(i, ex); } void IRGenSILFunction::visitRefToBridgeObjectInst( swift::RefToBridgeObjectInst *i) { Explosion refEx = getLoweredExplosion(i->getConverted()); llvm::Value *ref = refEx.claimNext(); Explosion bitsEx = getLoweredExplosion(i->getBitsOperand()); llvm::Value *bits = bitsEx.claimNext(); // Mask the bits into the pointer representation. llvm::Value *val = Builder.CreatePtrToInt(ref, IGM.SizeTy); val = Builder.CreateOr(val, bits); val = Builder.CreateIntToPtr(val, IGM.BridgeObjectPtrTy); Explosion resultEx; resultEx.add(val); setLoweredExplosion(i, resultEx); } void IRGenSILFunction::visitBridgeObjectToRefInst( swift::BridgeObjectToRefInst *i) { Explosion boEx = getLoweredExplosion(i->getConverted()); llvm::Value *bo = boEx.claimNext(); Explosion resultEx; auto &refTI = getTypeInfo(i->getType()); llvm::Type *refType = refTI.getSchema()[0].getScalarType(); // If the value is an ObjC tagged pointer, pass it through verbatim. llvm::BasicBlock *taggedCont = nullptr, *tagged = nullptr, *notTagged = nullptr; llvm::Value *taggedRef = nullptr; llvm::Value *boBits = nullptr; ClassDecl *Cl = i->getType().getClassOrBoundGenericClass(); if (IGM.TargetInfo.hasObjCTaggedPointers() && (!Cl || !isKnownNotTaggedPointer(IGM, Cl))) { boBits = Builder.CreatePtrToInt(bo, IGM.SizeTy); APInt maskValue = IGM.TargetInfo.ObjCPointerReservedBits.asAPInt(); llvm::Value *mask = llvm::ConstantInt::get(IGM.getLLVMContext(), maskValue); llvm::Value *reserved = Builder.CreateAnd(boBits, mask); llvm::Value *cond = Builder.CreateICmpEQ(reserved, llvm::ConstantInt::get(IGM.SizeTy, 0)); tagged = createBasicBlock("tagged-pointer"), notTagged = createBasicBlock("not-tagged-pointer"); taggedCont = createBasicBlock("tagged-cont"); Builder.CreateCondBr(cond, notTagged, tagged); Builder.emitBlock(tagged); taggedRef = Builder.CreateBitCast(bo, refType); Builder.CreateBr(taggedCont); // If it's not a tagged pointer, mask off the spare bits. Builder.emitBlock(notTagged); } // Mask off the spare bits (if they exist). auto &spareBits = IGM.getHeapObjectSpareBits(); llvm::Value *result; if (spareBits.any()) { APInt maskValue = ~spareBits.asAPInt(); if (!boBits) boBits = Builder.CreatePtrToInt(bo, IGM.SizeTy); llvm::Value *mask = llvm::ConstantInt::get(IGM.getLLVMContext(), maskValue); llvm::Value *masked = Builder.CreateAnd(boBits, mask); result = Builder.CreateIntToPtr(masked, refType); } else { result = Builder.CreateBitCast(bo, refType); } if (taggedCont) { Builder.CreateBr(taggedCont); Builder.emitBlock(taggedCont); auto phi = Builder.CreatePHI(refType, 2); phi->addIncoming(taggedRef, tagged); phi->addIncoming(result, notTagged); result = phi; } resultEx.add(result); setLoweredExplosion(i, resultEx); } void IRGenSILFunction::visitBridgeObjectToWordInst( swift::BridgeObjectToWordInst *i) { Explosion boEx = getLoweredExplosion(i->getConverted()); llvm::Value *val = boEx.claimNext(); val = Builder.CreatePtrToInt(val, IGM.SizeTy); Explosion wordEx; wordEx.add(val); setLoweredExplosion(i, wordEx); } void IRGenSILFunction::visitUnconditionalCheckedCastAddrInst( swift::UnconditionalCheckedCastAddrInst *i) { Address dest = getLoweredAddress(i->getDest()); Address src = getLoweredAddress(i->getSrc()); emitCheckedCast(*this, src, i->getSourceType(), dest, i->getTargetType(), i->getConsumptionKind(), CheckedCastMode::Unconditional); } void IRGenSILFunction::visitUnconditionalCheckedCastValueInst( swift::UnconditionalCheckedCastValueInst *i) { llvm_unreachable("unsupported instruction during IRGen"); } void IRGenSILFunction::visitCheckedCastValueBranchInst( swift::CheckedCastValueBranchInst *i) { llvm_unreachable("unsupported instruction during IRGen"); } void IRGenSILFunction::visitCheckedCastBranchInst( swift::CheckedCastBranchInst *i) { SILType destTy = i->getCastType(); FailableCastResult castResult; Explosion ex; if (i->isExact()) { auto operand = i->getOperand(); Explosion source = getLoweredExplosion(operand); castResult = emitClassIdenticalCast(*this, source.claimNext(), operand->getType(), destTy); } else { Explosion value = getLoweredExplosion(i->getOperand()); emitScalarCheckedCast(*this, value, i->getOperand()->getType(), i->getCastType(), CheckedCastMode::Conditional, ex); auto val = ex.claimNext(); castResult.casted = val; llvm::Value *nil = llvm::ConstantPointerNull::get(cast<llvm::PointerType>(val->getType())); castResult.succeeded = Builder.CreateICmpNE(val, nil); } // Branch on the success of the cast. // All cast operations currently return null on failure. auto &successBB = getLoweredBB(i->getSuccessBB()); llvm::Type *toTy = IGM.getTypeInfo(destTy).getStorageType(); if (toTy->isPointerTy()) castResult.casted = Builder.CreateBitCast(castResult.casted, toTy); Builder.CreateCondBr(castResult.succeeded, successBB.bb, getLoweredBB(i->getFailureBB()).bb); // Feed the cast result into the nonnull branch. unsigned phiIndex = 0; Explosion ex2; ex2.add(castResult.casted); ex2.add(ex.claimAll()); addIncomingExplosionToPHINodes(*this, successBB, phiIndex, ex2); } void IRGenSILFunction::visitCheckedCastAddrBranchInst( swift::CheckedCastAddrBranchInst *i) { Address dest = getLoweredAddress(i->getDest()); Address src = getLoweredAddress(i->getSrc()); llvm::Value *castSucceeded = emitCheckedCast(*this, src, i->getSourceType(), dest, i->getTargetType(), i->getConsumptionKind(), CheckedCastMode::Conditional); Builder.CreateCondBr(castSucceeded, getLoweredBB(i->getSuccessBB()).bb, getLoweredBB(i->getFailureBB()).bb); } void IRGenSILFunction::visitIsNonnullInst(swift::IsNonnullInst *i) { // Get the value we're testing, which may be a function, an address or an // instance pointer. llvm::Value *val; const LoweredValue &lv = getLoweredValue(i->getOperand()); if (i->getOperand()->getType().is<SILFunctionType>()) { Explosion values = lv.getExplosion(*this); val = values.claimNext(); // Function pointer. values.claimNext(); // Ignore the data pointer. } else if (lv.isAddress()) { val = lv.getAddress().getAddress(); } else { Explosion values = lv.getExplosion(*this); val = values.claimNext(); } // Check that the result isn't null. auto *valTy = cast<llvm::PointerType>(val->getType()); llvm::Value *result = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, val, llvm::ConstantPointerNull::get(valTy)); Explosion out; out.add(result); setLoweredExplosion(i, out); } void IRGenSILFunction::visitUpcastInst(swift::UpcastInst *i) { auto toTy = getTypeInfo(i->getType()).getSchema()[0].getScalarType(); // If we have an address, just bitcast, don't explode. if (i->getOperand()->getType().isAddress()) { Address fromAddr = getLoweredAddress(i->getOperand()); llvm::Value *toValue = Builder.CreateBitCast( fromAddr.getAddress(), toTy->getPointerTo()); Address Addr(toValue, fromAddr.getAlignment()); setLoweredAddress(i, Addr); return; } Explosion from = getLoweredExplosion(i->getOperand()); Explosion to; assert(from.size() == 1 && "class should explode to single value"); llvm::Value *fromValue = from.claimNext(); to.add(Builder.CreateBitCast(fromValue, toTy)); setLoweredExplosion(i, to); } void IRGenSILFunction::visitIndexAddrInst(swift::IndexAddrInst *i) { Address base = getLoweredAddress(i->getBase()); Explosion indexValues = getLoweredExplosion(i->getIndex()); llvm::Value *index = indexValues.claimNext(); auto baseTy = i->getBase()->getType(); auto &ti = getTypeInfo(baseTy); Address dest = ti.indexArray(*this, base, index, baseTy); setLoweredAddress(i, dest); } void IRGenSILFunction::visitTailAddrInst(swift::TailAddrInst *i) { Address base = getLoweredAddress(i->getBase()); Explosion indexValues = getLoweredExplosion(i->getIndex()); llvm::Value *index = indexValues.claimNext(); SILType baseTy = i->getBase()->getType(); const TypeInfo &baseTI = getTypeInfo(baseTy); Address dest = baseTI.indexArray(*this, base, index, baseTy); const TypeInfo &TailTI = getTypeInfo(i->getTailType()); dest = TailTI.roundUpToTypeAlignment(*this, dest, i->getTailType()); llvm::Type *destType = TailTI.getStorageType()->getPointerTo(); dest = Builder.CreateBitCast(dest, destType); setLoweredAddress(i, dest); } void IRGenSILFunction::visitIndexRawPointerInst(swift::IndexRawPointerInst *i) { Explosion baseValues = getLoweredExplosion(i->getBase()); llvm::Value *base = baseValues.claimNext(); Explosion indexValues = getLoweredExplosion(i->getIndex()); llvm::Value *index = indexValues.claimNext(); // We don't expose a non-inbounds GEP operation. llvm::Value *destValue = Builder.CreateInBoundsGEP(base, index); Explosion result; result.add(destValue); setLoweredExplosion(i, result); } void IRGenSILFunction::visitAllocValueBufferInst( swift::AllocValueBufferInst *i) { Address buffer = getLoweredAddress(i->getOperand()); auto valueType = i->getValueType(); Address value; if (getSILModule().getOptions().UseCOWExistentials) { value = emitAllocateValueInBuffer(*this, valueType, buffer); } else { value = getTypeInfo(valueType).allocateBuffer(*this, buffer, valueType); } setLoweredAddress(i, value); } void IRGenSILFunction::visitProjectValueBufferInst( swift::ProjectValueBufferInst *i) { Address buffer = getLoweredAddress(i->getOperand()); auto valueType = i->getValueType(); Address value; if (getSILModule().getOptions().UseCOWExistentials) { value = emitProjectValueInBuffer(*this, valueType, buffer); } else { value = getTypeInfo(valueType).projectBuffer(*this, buffer, valueType); } setLoweredAddress(i, value); } void IRGenSILFunction::visitDeallocValueBufferInst( swift::DeallocValueBufferInst *i) { Address buffer = getLoweredAddress(i->getOperand()); auto valueType = i->getValueType(); if (getSILModule().getOptions().UseCOWExistentials) { emitDeallocateValueInBuffer(*this, valueType, buffer); return; } getTypeInfo(valueType).deallocateBuffer(*this, buffer, valueType); } void IRGenSILFunction::visitInitExistentialAddrInst(swift::InitExistentialAddrInst *i) { Address container = getLoweredAddress(i->getOperand()); SILType destType = i->getOperand()->getType(); Address buffer = emitOpaqueExistentialContainerInit(*this, container, destType, i->getFormalConcreteType(), i->getLoweredConcreteType(), i->getConformances()); auto srcType = i->getLoweredConcreteType(); auto &srcTI = getTypeInfo(srcType); // Allocate a COW box for the value if neceesary. if (getSILModule().getOptions().UseCOWExistentials) { auto *genericEnv = CurSILFn->getGenericEnvironment(); setLoweredAddress(i, emitAllocateBoxedOpaqueExistentialBuffer( *this, destType, srcType, container, genericEnv)); return; } // See if we can defer initialization of the buffer to a copy_addr into it. if (tryDeferFixedSizeBufferInitialization(*this, i, srcTI, buffer, "")) return; // Allocate in the destination fixed-size buffer. Address address = srcTI.allocateBuffer(*this, buffer, srcType); setLoweredAddress(i, address); } void IRGenSILFunction::visitInitExistentialOpaqueInst( swift::InitExistentialOpaqueInst *i) { llvm_unreachable("unsupported instruction during IRGen"); } void IRGenSILFunction::visitInitExistentialMetatypeInst( InitExistentialMetatypeInst *i) { Explosion metatype = getLoweredExplosion(i->getOperand()); Explosion result; emitExistentialMetatypeContainer(*this, result, i->getType(), metatype.claimNext(), i->getOperand()->getType(), i->getConformances()); setLoweredExplosion(i, result); } void IRGenSILFunction::visitInitExistentialRefInst(InitExistentialRefInst *i) { Explosion instance = getLoweredExplosion(i->getOperand()); Explosion result; emitClassExistentialContainer(*this, result, i->getType(), instance.claimNext(), i->getFormalConcreteType(), i->getOperand()->getType(), i->getConformances()); setLoweredExplosion(i, result); } void IRGenSILFunction::visitDeinitExistentialAddrInst( swift::DeinitExistentialAddrInst *i) { Address container = getLoweredAddress(i->getOperand()); // Deallocate the COW box for the value if neceesary. if (getSILModule().getOptions().UseCOWExistentials) { emitDeallocateBoxedOpaqueExistentialBuffer( *this, i->getOperand()->getType(), container); return; } emitOpaqueExistentialContainerDeinit(*this, container, i->getOperand()->getType()); } void IRGenSILFunction::visitDeinitExistentialOpaqueInst( swift::DeinitExistentialOpaqueInst *i) { llvm_unreachable("unsupported instruction during IRGen"); } void IRGenSILFunction::visitOpenExistentialAddrInst(OpenExistentialAddrInst *i) { SILType baseTy = i->getOperand()->getType(); Address base = getLoweredAddress(i->getOperand()); auto openedArchetype = cast<ArchetypeType>( i->getType().getSwiftRValueType()); // Insert a copy of the boxed value for COW semantics if necessary. if (getSILModule().getOptions().UseCOWExistentials) { auto accessKind = i->getAccessKind(); Address object = emitOpaqueBoxedExistentialProjection( *this, accessKind, base, baseTy, openedArchetype); setLoweredAddress(i, object); return; } Address object = emitOpaqueExistentialProjection(*this, base, baseTy, openedArchetype); setLoweredAddress(i, object); } void IRGenSILFunction::visitOpenExistentialRefInst(OpenExistentialRefInst *i) { SILType baseTy = i->getOperand()->getType(); Explosion base = getLoweredExplosion(i->getOperand()); auto openedArchetype = cast<ArchetypeType>( i->getType().getSwiftRValueType()); Explosion result; llvm::Value *instance = emitClassExistentialProjection(*this, base, baseTy, openedArchetype); result.add(instance); setLoweredExplosion(i, result); } void IRGenSILFunction::visitOpenExistentialMetatypeInst( OpenExistentialMetatypeInst *i) { SILType baseTy = i->getOperand()->getType(); Explosion base = getLoweredExplosion(i->getOperand()); auto openedTy = i->getType().getSwiftRValueType(); llvm::Value *metatype = emitExistentialMetatypeProjection(*this, base, baseTy, openedTy); Explosion result; result.add(metatype); setLoweredExplosion(i, result); } void IRGenSILFunction::visitOpenExistentialOpaqueInst( OpenExistentialOpaqueInst *i) { llvm_unreachable("unsupported instruction during IRGen"); } void IRGenSILFunction::visitProjectBlockStorageInst(ProjectBlockStorageInst *i){ // TODO Address block = getLoweredAddress(i->getOperand()); Address capture = projectBlockStorageCapture(*this, block, i->getOperand()->getType().castTo<SILBlockStorageType>()); setLoweredAddress(i, capture); } void IRGenSILFunction::visitInitBlockStorageHeaderInst( InitBlockStorageHeaderInst *i) { auto addr = getLoweredAddress(i->getBlockStorage()); // We currently only support static invoke functions. auto &invokeVal = getLoweredValue(i->getInvokeFunction()); llvm::Function *invokeFn = nullptr; ForeignFunctionInfo foreignInfo; if (invokeVal.kind != LoweredValue::Kind::StaticFunction) { IGM.unimplemented(i->getLoc().getSourceLoc(), "non-static block invoke function"); } else { invokeFn = invokeVal.getStaticFunction().getFunction(); foreignInfo = invokeVal.getStaticFunction().getForeignInfo(); } assert(foreignInfo.ClangInfo && "no clang info for block function?"); // Initialize the header. emitBlockHeader(*this, addr, i->getBlockStorage()->getType().castTo<SILBlockStorageType>(), invokeFn, i->getInvokeFunction()->getType().castTo<SILFunctionType>(), foreignInfo); // Cast the storage to the block type to produce the result value. llvm::Value *asBlock = Builder.CreateBitCast(addr.getAddress(), IGM.ObjCBlockPtrTy); Explosion e; e.add(asBlock); setLoweredExplosion(i, e); } void IRGenSILFunction::visitAllocExistentialBoxInst(AllocExistentialBoxInst *i){ OwnedAddress boxWithAddr = emitBoxedExistentialContainerAllocation(*this, i->getExistentialType(), i->getFormalConcreteType(), i->getConformances()); setLoweredBox(i, boxWithAddr); } void IRGenSILFunction::visitDeallocExistentialBoxInst( DeallocExistentialBoxInst *i) { Explosion box = getLoweredExplosion(i->getOperand()); emitBoxedExistentialContainerDeallocation(*this, box, i->getOperand()->getType(), i->getConcreteType()); } void IRGenSILFunction::visitOpenExistentialBoxInst(OpenExistentialBoxInst *i) { Explosion box = getLoweredExplosion(i->getOperand()); auto openedArchetype = cast<ArchetypeType>(i->getType().getSwiftRValueType()); auto addr = emitOpenExistentialBox(*this, box, i->getOperand()->getType(), openedArchetype); setLoweredAddress(i, addr); } void IRGenSILFunction::visitProjectExistentialBoxInst(ProjectExistentialBoxInst *i) { const LoweredValue &val = getLoweredValue(i->getOperand()); if (val.isBoxWithAddress()) { // The operand is an alloc_existential_box. // We can directly reuse the address. setLoweredAddress(i, val.getAddressOfBox()); } else { Explosion box = getLoweredExplosion(i->getOperand()); auto caddr = emitBoxedExistentialProjection(*this, box, i->getOperand()->getType(), i->getType().getSwiftRValueType()); setLoweredAddress(i, caddr.getAddress()); } } void IRGenSILFunction::visitDynamicMethodInst(DynamicMethodInst *i) { assert(i->getMember().isForeign && "dynamic_method requires [objc] method"); setLoweredObjCMethod(i, i->getMember()); return; } void IRGenSILFunction::visitWitnessMethodInst(swift::WitnessMethodInst *i) { // For Objective-C classes we need to arrange for a msgSend // to happen when the method is called. if (i->getMember().isForeign) { setLoweredObjCMethod(i, i->getMember()); return; } CanType baseTy = i->getLookupType(); ProtocolConformanceRef conformance = i->getConformance(); SILDeclRef member = i->getMember(); // It would be nice if this weren't discarded. llvm::Value *baseMetadataCache = nullptr; Explosion lowered; emitWitnessMethodValue(*this, baseTy, &baseMetadataCache, member, conformance, lowered); setLoweredExplosion(i, lowered); } void IRGenSILFunction::setAllocatedAddressForBuffer(SILValue v, const Address &allocedAddress) { overwriteAllocatedAddress(v, allocedAddress); // Emit the debug info for the variable if any. if (auto allocStack = dyn_cast<AllocStackInst>(v)) { emitDebugInfoForAllocStack(allocStack, getTypeInfo(v->getType()), allocedAddress.getAddress()); } } void IRGenSILFunction::visitCopyAddrInst(swift::CopyAddrInst *i) { SILType addrTy = i->getSrc()->getType(); const TypeInfo &addrTI = getTypeInfo(addrTy); Address src = getLoweredAddress(i->getSrc()); // See whether we have a deferred fixed-size buffer initialization. auto &loweredDest = getLoweredValue(i->getDest()); if (loweredDest.isUnallocatedAddressInBuffer()) { // We should never have a deferred initialization with COW existentials. assert(!getSILModule().getOptions().UseCOWExistentials && "Should never have an unallocated buffer and COW existentials"); assert(i->isInitializationOfDest() && "need to initialize an unallocated buffer"); Address cont = loweredDest.getContainerOfAddress(); if (i->isTakeOfSrc()) { Address addr = addrTI.initializeBufferWithTake(*this, cont, src, addrTy); setAllocatedAddressForBuffer(i->getDest(), addr); } else { Address addr = addrTI.initializeBufferWithCopy(*this, cont, src, addrTy); setAllocatedAddressForBuffer(i->getDest(), addr); } } else { Address dest = loweredDest.getAddress(); if (i->isInitializationOfDest()) { if (i->isTakeOfSrc()) { addrTI.initializeWithTake(*this, dest, src, addrTy); } else { addrTI.initializeWithCopy(*this, dest, src, addrTy); } } else { if (i->isTakeOfSrc()) { addrTI.assignWithTake(*this, dest, src, addrTy); } else { addrTI.assignWithCopy(*this, dest, src, addrTy); } } } } // This is a no-op because we do not lower Swift TBAA info to LLVM IR, and it // does not produce any values. void IRGenSILFunction::visitBindMemoryInst(swift::BindMemoryInst *) {} void IRGenSILFunction::visitDestroyAddrInst(swift::DestroyAddrInst *i) { SILType addrTy = i->getOperand()->getType(); const TypeInfo &addrTI = getTypeInfo(addrTy); // Otherwise, do the normal thing. Address base = getLoweredAddress(i->getOperand()); addrTI.destroy(*this, base, addrTy); } void IRGenSILFunction::visitCondFailInst(swift::CondFailInst *i) { Explosion e = getLoweredExplosion(i->getOperand()); llvm::Value *cond = e.claimNext(); // Emit individual fail blocks so that we can map the failure back to a source // line. llvm::BasicBlock *failBB = llvm::BasicBlock::Create(IGM.getLLVMContext()); llvm::BasicBlock *contBB = llvm::BasicBlock::Create(IGM.getLLVMContext()); Builder.CreateCondBr(cond, failBB, contBB); Builder.emitBlock(failBB); if (IGM.IRGen.Opts.Optimize) { // Emit unique side-effecting inline asm calls in order to eliminate // the possibility that an LLVM optimization or code generation pass // will merge these blocks back together again. We emit an empty asm // string with the side-effect flag set, and with a unique integer // argument for each cond_fail we see in the function. llvm::IntegerType *asmArgTy = IGM.Int32Ty; llvm::Type *argTys = { asmArgTy }; llvm::FunctionType *asmFnTy = llvm::FunctionType::get(IGM.VoidTy, argTys, false /* = isVarArg */); llvm::InlineAsm *inlineAsm = llvm::InlineAsm::get(asmFnTy, "", "n", true /* = SideEffects */); Builder.CreateCall(inlineAsm, llvm::ConstantInt::get(asmArgTy, NumCondFails++)); } // Emit the trap instruction. llvm::Function *trapIntrinsic = llvm::Intrinsic::getDeclaration(&IGM.Module, llvm::Intrinsic::ID::trap); Builder.CreateCall(trapIntrinsic, {}); Builder.CreateUnreachable(); Builder.emitBlock(contBB); FailBBs.push_back(failBB); } void IRGenSILFunction::visitSuperMethodInst(swift::SuperMethodInst *i) { if (i->getMember().isForeign) { setLoweredObjCMethodBounded(i, i->getMember(), i->getOperand()->getType(), /*startAtSuper=*/true); return; } auto base = getLoweredExplosion(i->getOperand()); auto baseType = i->getOperand()->getType(); llvm::Value *baseValue = base.claimNext(); auto method = i->getMember(); auto methodType = i->getType().castTo<SILFunctionType>(); llvm::Value *fnValue = emitVirtualMethodValue(*this, baseValue, baseType, method, methodType, /*useSuperVTable*/ true); fnValue = Builder.CreateBitCast(fnValue, IGM.Int8PtrTy); Explosion e; e.add(fnValue); setLoweredExplosion(i, e); } void IRGenSILFunction::visitClassMethodInst(swift::ClassMethodInst *i) { // For Objective-C classes we need to arrange for a msgSend // to happen when the method is called. if (i->getMember().isForeign) { setLoweredObjCMethod(i, i->getMember()); return; } Explosion base = getLoweredExplosion(i->getOperand()); llvm::Value *baseValue = base.claimNext(); SILDeclRef method = i->getMember(); auto methodType = i->getType().castTo<SILFunctionType>(); // For Swift classes, get the method implementation from the vtable. // FIXME: better explosion kind, map as static. llvm::Value *fnValue = emitVirtualMethodValue(*this, baseValue, i->getOperand()->getType(), method, methodType, /*useSuperVTable*/ false); fnValue = Builder.CreateBitCast(fnValue, IGM.Int8PtrTy); Explosion e; e.add(fnValue); setLoweredExplosion(i, e); } void IRGenModule::emitSILStaticInitializers() { SmallVector<SILFunction *, 8> StaticInitializers; for (SILGlobalVariable &Global : getSILModule().getSILGlobals()) { if (!Global.getInitializer()) continue; auto *IRGlobal = Module.getGlobalVariable(Global.getName(), true /* = AllowLocal */); // A check for multi-threaded compilation: Is this the llvm module where the // global is defined and not only referenced (or not referenced at all). if (!IRGlobal || !IRGlobal->hasInitializer()) continue; auto *InitValue = Global.getValueOfStaticInitializer(); // Set the IR global's initializer to the constant for this SIL // struct. if (auto *SI = dyn_cast<StructInst>(InitValue)) { IRGlobal->setInitializer(emitConstantStruct(*this, SI)); continue; } // Set the IR global's initializer to the constant for this SIL // tuple. auto *TI = cast<TupleInst>(InitValue); IRGlobal->setInitializer(emitConstantTuple(*this, TI)); } }
apache-2.0
takari/bpm
bpm-engine-api/src/main/java/io/takari/bpm/model/diagram/ProcessDiagram.java
798
package io.takari.bpm.model.diagram; import java.io.Serializable; import java.util.Collections; import java.util.List; public class ProcessDiagram implements Serializable { private static final long serialVersionUID = 1L; private final String id; private final List<Shape> shapes; private final List<Edge> edges; public ProcessDiagram(String id) { this(id, Collections.emptyList(), Collections.emptyList()); } public ProcessDiagram(String id, List<Shape> shapes, List<Edge> edges) { this.id = id; this.shapes = shapes; this.edges = edges; } public List<Edge> getEdges() { return edges; } public List<Shape> getShapes() { return shapes; } public String getId() { return id; } }
apache-2.0
mdebruyn-trip/puppet-prometheus
spec/acceptance/collectd_exporter_spec.rb
771
require 'spec_helper_acceptance' describe 'prometheus collectd exporter' do it 'collectd_exporter works idempotently with no errors' do if default[:platform] =~ %r{ubuntu-18.04-amd64} pp = "package{'iproute2': ensure => present}" apply_manifest(pp, catch_failures: true) end pp = 'include prometheus::collectd_exporter' # Run it twice and test for idempotency apply_manifest(pp, catch_failures: true) apply_manifest(pp, catch_changes: true) end describe service('collectd_exporter') do it { is_expected.to be_running } it { is_expected.to be_enabled } end # the class installs an the collectd_exporter that listens on port 9103 describe port(9103) do it { is_expected.to be_listening.with('tcp6') } end end
apache-2.0
jawilson/home-assistant
homeassistant/components/squeezebox/media_player.py
19137
"""Support for interfacing to the Logitech SqueezeBox API.""" import asyncio import json import logging from pysqueezebox import Server, async_discover import voluptuous as vol from homeassistant import config_entries from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerEntity from homeassistant.components.media_player.const import ( ATTR_MEDIA_ENQUEUE, MEDIA_TYPE_MUSIC, MEDIA_TYPE_PLAYLIST, SUPPORT_BROWSE_MEDIA, SUPPORT_CLEAR_PLAYLIST, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK, SUPPORT_SHUFFLE_SET, SUPPORT_STOP, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, ) from homeassistant.config_entries import SOURCE_INTEGRATION_DISCOVERY from homeassistant.const import ( ATTR_COMMAND, CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_USERNAME, EVENT_HOMEASSISTANT_START, STATE_IDLE, STATE_OFF, STATE_PAUSED, STATE_PLAYING, ) from homeassistant.core import callback from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.device_registry import format_mac from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send, ) from homeassistant.util.dt import utcnow from .browse_media import build_item_response, generate_playlist, library_payload from .const import ( DEFAULT_PORT, DISCOVERY_TASK, DOMAIN, KNOWN_PLAYERS, PLAYER_DISCOVERY_UNSUB, ) SERVICE_CALL_METHOD = "call_method" SERVICE_CALL_QUERY = "call_query" SERVICE_SYNC = "sync" SERVICE_UNSYNC = "unsync" ATTR_QUERY_RESULT = "query_result" ATTR_SYNC_GROUP = "sync_group" SIGNAL_PLAYER_REDISCOVERED = "squeezebox_player_rediscovered" _LOGGER = logging.getLogger(__name__) DISCOVERY_INTERVAL = 60 SUPPORT_SQUEEZEBOX = ( SUPPORT_BROWSE_MEDIA | SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | SUPPORT_SEEK | SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_PLAY_MEDIA | SUPPORT_PLAY | SUPPORT_SHUFFLE_SET | SUPPORT_CLEAR_PLAYLIST | SUPPORT_STOP ) PLATFORM_SCHEMA = vol.All( cv.deprecated(CONF_HOST), cv.deprecated(CONF_PORT), cv.deprecated(CONF_PASSWORD), cv.deprecated(CONF_USERNAME), PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_USERNAME): cv.string, } ), ) KNOWN_SERVERS = "known_servers" ATTR_PARAMETERS = "parameters" ATTR_OTHER_PLAYER = "other_player" ATTR_TO_PROPERTY = [ ATTR_QUERY_RESULT, ATTR_SYNC_GROUP, ] SQUEEZEBOX_MODE = { "pause": STATE_PAUSED, "play": STATE_PLAYING, "stop": STATE_IDLE, } async def start_server_discovery(hass): """Start a server discovery task.""" def _discovered_server(server): asyncio.create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_INTEGRATION_DISCOVERY}, data={ CONF_HOST: server.host, CONF_PORT: int(server.port), "uuid": server.uuid, }, ) ) hass.data.setdefault(DOMAIN, {}) if DISCOVERY_TASK not in hass.data[DOMAIN]: _LOGGER.debug("Adding server discovery task for squeezebox") hass.data[DOMAIN][DISCOVERY_TASK] = hass.async_create_task( async_discover(_discovered_server) ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up squeezebox platform from platform entry in configuration.yaml (deprecated).""" if config: await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=config ) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up an LMS Server from a config entry.""" config = config_entry.data _LOGGER.debug("Reached async_setup_entry for host=%s", config[CONF_HOST]) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) host = config[CONF_HOST] port = config[CONF_PORT] hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN].setdefault(config_entry.entry_id, {}) known_players = hass.data[DOMAIN].setdefault(KNOWN_PLAYERS, []) session = async_get_clientsession(hass) _LOGGER.debug("Creating LMS object for %s", host) lms = Server(session, host, port, username, password) async def _discovery(now=None): """Discover squeezebox players by polling server.""" async def _discovered_player(player): """Handle a (re)discovered player.""" entity = next( ( known for known in known_players if known.unique_id == player.player_id ), None, ) if entity: await player.async_update() async_dispatcher_send( hass, SIGNAL_PLAYER_REDISCOVERED, player.player_id, player.connected ) if not entity: _LOGGER.debug("Adding new entity: %s", player) entity = SqueezeBoxEntity(player) known_players.append(entity) async_add_entities([entity]) if players := await lms.async_get_players(): for player in players: hass.async_create_task(_discovered_player(player)) hass.data[DOMAIN][config_entry.entry_id][ PLAYER_DISCOVERY_UNSUB ] = hass.helpers.event.async_call_later(DISCOVERY_INTERVAL, _discovery) _LOGGER.debug("Adding player discovery job for LMS server: %s", host) asyncio.create_task(_discovery()) # Register entity services platform = entity_platform.async_get_current_platform() platform.async_register_entity_service( SERVICE_CALL_METHOD, { vol.Required(ATTR_COMMAND): cv.string, vol.Optional(ATTR_PARAMETERS): vol.All( cv.ensure_list, vol.Length(min=1), [cv.string] ), }, "async_call_method", ) platform.async_register_entity_service( SERVICE_CALL_QUERY, { vol.Required(ATTR_COMMAND): cv.string, vol.Optional(ATTR_PARAMETERS): vol.All( cv.ensure_list, vol.Length(min=1), [cv.string] ), }, "async_call_query", ) platform.async_register_entity_service( SERVICE_SYNC, {vol.Required(ATTR_OTHER_PLAYER): cv.string}, "async_sync", ) platform.async_register_entity_service(SERVICE_UNSYNC, None, "async_unsync") # Start server discovery task if not already running if hass.is_running: asyncio.create_task(start_server_discovery(hass)) else: hass.bus.async_listen_once( EVENT_HOMEASSISTANT_START, start_server_discovery(hass) ) return True class SqueezeBoxEntity(MediaPlayerEntity): """ Representation of a SqueezeBox device. Wraps a pysqueezebox.Player() object. """ def __init__(self, player): """Initialize the SqueezeBox device.""" self._player = player self._last_update = None self._query_result = {} self._available = True self._remove_dispatcher = None @property def extra_state_attributes(self): """Return device-specific attributes.""" squeezebox_attr = { attr: getattr(self, attr) for attr in ATTR_TO_PROPERTY if getattr(self, attr) is not None } return squeezebox_attr @property def name(self): """Return the name of the device.""" return self._player.name @property def unique_id(self): """Return a unique ID.""" return format_mac(self._player.player_id) @property def available(self): """Return True if device connected to LMS server.""" return self._available @callback def rediscovered(self, unique_id, connected): """Make a player available again.""" if unique_id == self.unique_id and connected: self._available = True _LOGGER.info("Player %s is available again", self.name) self._remove_dispatcher() @property def state(self): """Return the state of the device.""" if not self._player.power: return STATE_OFF if self._player.mode: return SQUEEZEBOX_MODE.get(self._player.mode) return None async def async_update(self): """Update the Player() object.""" # only update available players, newly available players will be rediscovered and marked available if self._available: last_media_position = self.media_position await self._player.async_update() if self.media_position != last_media_position: self._last_update = utcnow() if self._player.connected is False: _LOGGER.info("Player %s is not available", self.name) self._available = False # start listening for restored players self._remove_dispatcher = async_dispatcher_connect( self.hass, SIGNAL_PLAYER_REDISCOVERED, self.rediscovered ) async def async_will_remove_from_hass(self): """Remove from list of known players when removed from hass.""" self.hass.data[DOMAIN][KNOWN_PLAYERS].remove(self) @property def volume_level(self): """Volume level of the media player (0..1).""" if self._player.volume: return int(float(self._player.volume)) / 100.0 @property def is_volume_muted(self): """Return true if volume is muted.""" return self._player.muting @property def media_content_id(self): """Content ID of current playing media.""" if not self._player.playlist: return None if len(self._player.playlist) > 1: urls = [{"url": track["url"]} for track in self._player.playlist] return json.dumps({"index": self._player.current_index, "urls": urls}) return self._player.url @property def media_content_type(self): """Content type of current playing media.""" if not self._player.playlist: return None if len(self._player.playlist) > 1: return MEDIA_TYPE_PLAYLIST return MEDIA_TYPE_MUSIC @property def media_duration(self): """Duration of current playing media in seconds.""" return self._player.duration @property def media_position(self): """Position of current playing media in seconds.""" return self._player.time @property def media_position_updated_at(self): """Last time status was updated.""" return self._last_update @property def media_image_url(self): """Image url of current playing media.""" return self._player.image_url @property def media_title(self): """Title of current playing media.""" return self._player.title @property def media_artist(self): """Artist of current playing media.""" return self._player.artist @property def media_album_name(self): """Album of current playing media.""" return self._player.album @property def shuffle(self): """Boolean if shuffle is enabled.""" return self._player.shuffle @property def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_SQUEEZEBOX @property def sync_group(self): """List players we are synced with.""" player_ids = { p.unique_id: p.entity_id for p in self.hass.data[DOMAIN][KNOWN_PLAYERS] } sync_group = [] for player in self._player.sync_group: if player in player_ids: sync_group.append(player_ids[player]) return sync_group @property def query_result(self): """Return the result from the call_query service.""" return self._query_result async def async_turn_off(self): """Turn off media player.""" await self._player.async_set_power(False) async def async_volume_up(self): """Volume up media player.""" await self._player.async_set_volume("+5") async def async_volume_down(self): """Volume down media player.""" await self._player.async_set_volume("-5") async def async_set_volume_level(self, volume): """Set volume level, range 0..1.""" volume_percent = str(int(volume * 100)) await self._player.async_set_volume(volume_percent) async def async_mute_volume(self, mute): """Mute (true) or unmute (false) media player.""" await self._player.async_set_muting(mute) async def async_media_stop(self): """Send stop command to media player.""" await self._player.async_stop() async def async_media_play_pause(self): """Send pause command to media player.""" await self._player.async_toggle_pause() async def async_media_play(self): """Send play command to media player.""" await self._player.async_play() async def async_media_pause(self): """Send pause command to media player.""" await self._player.async_pause() async def async_media_next_track(self): """Send next track command.""" await self._player.async_index("+1") async def async_media_previous_track(self): """Send next track command.""" await self._player.async_index("-1") async def async_media_seek(self, position): """Send seek command.""" await self._player.async_time(position) async def async_turn_on(self): """Turn the media player on.""" await self._player.async_set_power(True) async def async_play_media(self, media_type, media_id, **kwargs): """ Send the play_media command to the media player. If ATTR_MEDIA_ENQUEUE is True, add `media_id` to the current playlist. """ cmd = "play" index = None if kwargs.get(ATTR_MEDIA_ENQUEUE): cmd = "add" if media_type == MEDIA_TYPE_MUSIC: await self._player.async_load_url(media_id, cmd) return if media_type == MEDIA_TYPE_PLAYLIST: try: # a saved playlist by number payload = { "search_id": int(media_id), "search_type": MEDIA_TYPE_PLAYLIST, } playlist = await generate_playlist(self._player, payload) except ValueError: # a list of urls content = json.loads(media_id) playlist = content["urls"] index = content["index"] else: payload = { "search_id": media_id, "search_type": media_type, } playlist = await generate_playlist(self._player, payload) _LOGGER.debug("Generated playlist: %s", playlist) await self._player.async_load_playlist(playlist, cmd) if index is not None: await self._player.async_index(index) async def async_set_shuffle(self, shuffle): """Enable/disable shuffle mode.""" shuffle_mode = "song" if shuffle else "none" await self._player.async_set_shuffle(shuffle_mode) async def async_clear_playlist(self): """Send the media player the command for clear playlist.""" await self._player.async_clear_playlist() async def async_call_method(self, command, parameters=None): """ Call Squeezebox JSON/RPC method. Additional parameters are added to the command to form the list of positional parameters (p0, p1..., pN) passed to JSON/RPC server. """ all_params = [command] if parameters: for parameter in parameters: all_params.append(parameter) await self._player.async_query(*all_params) async def async_call_query(self, command, parameters=None): """ Call Squeezebox JSON/RPC method where we care about the result. Additional parameters are added to the command to form the list of positional parameters (p0, p1..., pN) passed to JSON/RPC server. """ all_params = [command] if parameters: for parameter in parameters: all_params.append(parameter) self._query_result = await self._player.async_query(*all_params) _LOGGER.debug("call_query got result %s", self._query_result) async def async_sync(self, other_player): """ Add another Squeezebox player to this player's sync group. If the other player is a member of a sync group, it will leave the current sync group without asking. """ player_ids = { p.entity_id: p.unique_id for p in self.hass.data[DOMAIN][KNOWN_PLAYERS] } if other_player_id := player_ids.get(other_player): await self._player.async_sync(other_player_id) else: _LOGGER.info("Could not find player_id for %s. Not syncing", other_player) async def async_unsync(self): """Unsync this Squeezebox player.""" await self._player.async_unsync() async def async_browse_media(self, media_content_type=None, media_content_id=None): """Implement the websocket media browsing helper.""" _LOGGER.debug( "Reached async_browse_media with content_type %s and content_id %s", media_content_type, media_content_id, ) if media_content_type in [None, "library"]: return await library_payload(self._player) payload = { "search_type": media_content_type, "search_id": media_content_id, } return await build_item_response(self, self._player, payload) async def async_get_browse_image( self, media_content_type, media_content_id, media_image_id=None ): """Get album art from Squeezebox server.""" if media_image_id: image_url = self._player.generate_image_url_from_track_id(media_image_id) result = await self._async_fetch_image(image_url) if result == (None, None): _LOGGER.debug("Error retrieving proxied album art from %s", image_url) return result return (None, None)
apache-2.0
mephux/envdb
vendor/github.com/mephux/gotalk/sock.go
18443
package gotalk import ( "crypto/tls" "encoding/json" "errors" "fmt" "io" "net" "runtime" "sync" "time" ) // Returned by (Sock)BufferRequest when a streaming response is recieved var ErrUnexpectedStreamingRes = errors.New("unexpected streaming response") type pendingResMap map[string]chan Response type pendingReqMap map[string]chan []byte type Sock struct { // Handlers associated with this socket Handlers *Handlers // Associate some application-specific data with this socket UserData interface{} // Enable streaming requests and set the limit for how many streaming requests this socket // can handle at the same time. Setting this to `0` disables streaming requests alltogether // (the default) while setting this to a large number might be cause for security concerns // as a malicious peer could send many "start stream" messages, but never sending // any "end stream" messages, slowly exhausting memory. StreamReqLimit int // A function to be called when the socket closes. // If the socket was closed because of a protocol error, `code` is >=0 and represents a // ProtocolError* constant. CloseHandler func(s *Sock, code int) // Automatically retry requests which can be retried AutoRetryRequests bool // HeartbeatInterval controls how much time a socket waits between sending its heartbeats. // If this is 0, automatic sending of heartbeats is disabled. Defaults to 20 seconds. HeartbeatInterval time.Duration // If not nil, this function is invoked when a heartbeat is recevied OnHeartbeat func(load int, t time.Time) // ------------------------------------------------------------------------- // Used by connected sockets wmu sync.Mutex // guards writes on conn conn io.ReadWriteCloser // non-nil after successful call to Connect or accept closeCode int // protocol error, or -1 // Used for sending requests: nextOpID uint32 pendingRes pendingResMap pendingResMu sync.RWMutex // Used for handling streaming requests: pendingReq pendingReqMap pendingReqMu sync.RWMutex } func NewSock(h *Handlers) *Sock { return &Sock{Handlers: h, closeCode: -1, HeartbeatInterval: 20 * time.Second} } // Creates two sockets which are connected to eachother without any resource limits. // If `handlers` is nil, DefaultHandlers are used. If `limits` is nil, DefaultLimits are used. func Pipe(handlers *Handlers, limits Limits) (*Sock, *Sock, error) { if handlers == nil { handlers = DefaultHandlers } c1, c2 := net.Pipe() s1 := NewSock(handlers) s2 := NewSock(handlers) s1.Adopt(c1) s2.Adopt(c2) // Note: We deliberately ignore performing a handshake if limits == nil { limits = DefaultLimits } go s1.Read(limits) go s2.Read(limits) return s1, s2, nil } // Connect to a server via `how` at `addr`. Unless there's an error, the returned socket is // already reading in a different goroutine and is ready to be used. func Connect(how, addr string, config *tls.Config) (*Sock, error) { s := NewSock(DefaultHandlers) return s, s.Connect(how, addr, config, DefaultLimits) } // Adopt an I/O stream, which should already be in a "connected" state. // After adopting a new connection, you should call Handshake to perform the protocol // handshake, followed by Read to read messages. func (s *Sock) Adopt(c io.ReadWriteCloser) { s.conn = c s.closeCode = -1 } // ---------------------------------------------------------------------------------------------- // Connect to a server via `how` at `addr` func (s *Sock) Connect(how, addr string, config *tls.Config, limits Limits) error { c, err := tls.Dial(how, addr, config) if err != nil { return err } s.Adopt(c) if err := s.Handshake(); err != nil { return err } go s.Read(limits) return nil } // Access the socket's underlying connection func (s *Sock) Conn() io.ReadWriteCloser { return s.conn } // ---------------------------------------------------------------------------------------------- func (s *Sock) getResChan(id string) chan Response { s.pendingResMu.RLock() defer s.pendingResMu.RUnlock() if s.pendingRes == nil { return nil } return s.pendingRes[id] } func (s *Sock) allocResChan(ch chan Response) string { s.pendingResMu.Lock() defer s.pendingResMu.Unlock() id := string(FormatRequestID(s.nextOpID)) s.nextOpID++ if s.pendingRes == nil { s.pendingRes = make(pendingResMap) } s.pendingRes[id] = ch return id } func (s *Sock) deallocResChan(id string) { s.pendingResMu.Lock() defer s.pendingResMu.Unlock() delete(s.pendingRes, id) } // ---------------------------------------------------------------------------------------------- func (s *Sock) getReqChan(id string) chan []byte { s.pendingReqMu.RLock() defer s.pendingReqMu.RUnlock() if s.pendingReq == nil { return nil } return s.pendingReq[id] } func (s *Sock) allocReqChan(id string) chan []byte { ch := make(chan []byte, 1) s.pendingReqMu.Lock() defer s.pendingReqMu.Unlock() if s.pendingReq == nil { s.pendingReq = make(pendingReqMap) } if s.pendingReq[id] != nil { panic("identical request ID in two different requests") } s.pendingReq[id] = ch return ch } func (s *Sock) deallocReqChan(id string) { s.pendingReqMu.Lock() defer s.pendingReqMu.Unlock() delete(s.pendingReq, id) } // ---------------------------------------------------------------------------------------------- var errNotConnected = errors.New("not connected") func (s *Sock) writeMsg(t MsgType, id, op string, wait int, buf []byte) error { if s.conn == nil { return errNotConnected } s.wmu.Lock() defer s.wmu.Unlock() if _, err := s.conn.Write(MakeMsg(t, id, op, wait, len(buf))); err != nil { return err } if len(buf) != 0 { _, err := s.conn.Write(buf) return err } return nil } func (s *Sock) writeMsgString(t MsgType, id, op string, wait int, str string) error { if s.conn == nil { return errNotConnected } s.wmu.Lock() defer s.wmu.Unlock() if _, err := s.conn.Write(MakeMsg(t, id, op, wait, len(str))); err != nil { return err } if len(str) != 0 { _, err := io.WriteString(s.conn, str) return err } return nil } // Send a single-buffer request. A response should be received from reschan. func (s *Sock) SendRequest(r *Request, reschan chan Response) error { id := s.allocResChan(reschan) if err := s.writeMsg(r.MsgType, id, r.Op, 0, r.Data); err != nil { s.deallocResChan(id) if s.closeCode != -1 { return protocolError(s.closeCode) } return err } return nil } // Send a single-buffer request, wait for and return the response. // Automatically retries the request if needed. func (s *Sock) BufferRequest(op string, buf []byte) ([]byte, error) { reschan := make(chan Response) req := NewRequest(op, buf) for { err := s.SendRequest(req, reschan) if err != nil { return nil, err } res := <-reschan if res.IsError() { return nil, &res } else if res.IsStreaming() { return nil, ErrUnexpectedStreamingRes } else if res.IsRetry() { if res.Wait != 0 { time.Sleep(res.Wait) } } else { return res.Data, nil } } } // Send a single-value request where the input and output values are JSON-encoded func (s *Sock) Request(op string, in interface{}, out interface{}) error { inbuf, err := json.Marshal(in) if err != nil { return err } outbuf, err := s.BufferRequest(op, inbuf) if err != nil { return err } return json.Unmarshal(outbuf, out) } // Send a multi-buffer streaming request func (s *Sock) StreamRequest(op string) (*StreamRequest, chan Response) { reschan := make(chan Response) id := s.allocResChan(reschan) return &StreamRequest{sock: s, op: op, id: id}, reschan } // Send a single-buffer notification func (s *Sock) BufferNotify(name string, buf []byte) error { return s.writeMsg(MsgTypeNotification, "", name, 0, buf) } // Send a single-value request where the value is JSON-encoded func (s *Sock) Notify(name string, v interface{}) error { if buf, err := json.Marshal(v); err != nil { return err } else { return s.BufferNotify(name, buf) } } // ---------------------------------------------------------------------------------------------- func (s *Sock) readDiscard(readz int) error { if readz != 0 { // todo: is there a better way to read data w/o copying it into a buffer? _, err := readn(s.conn, make([]byte, readz)) return err } return nil } func (s *Sock) respondError(readz int, id, msg string) error { if err := s.readDiscard(readz); err != nil { return err } return s.writeMsg(MsgTypeErrorRes, id, "", 0, []byte(msg)) } func (s *Sock) respondRetry(readz int, id string, wait int, msg string) error { if err := s.readDiscard(readz); err != nil { return err } return s.writeMsg(MsgTypeRetryRes, id, "", wait, []byte(msg)) } func (s *Sock) respondOK(id string, b []byte) error { return s.writeMsg(MsgTypeSingleRes, id, "", 0, b) } type readDeadline interface { SetReadDeadline(time.Time) error } func (s *Sock) readBufferReq(limits Limits, id, op string, size int) error { if limits.incBufferReq() == false { return s.respondRetry(size, id, limitWaitBufferReq(), "request rate limit") } handler := s.Handlers.FindBufferRequestHandler(op) if handler == nil { err := s.respondError(size, id, "unknown operation \""+op+"\"") limits.decBufferReq() return err } // Read complete payload inbuf := make([]byte, size) if _, err := readn(s.conn, inbuf); err != nil { limits.decBufferReq() return err } // Dispatch handler go func() { defer func() { if r := recover(); r != nil { if s.conn != nil { if err := s.respondError(0, id, fmt.Sprint(r)); err != nil { s.Close() } } } limits.decBufferReq() }() outbuf, err := handler(s, op, inbuf) if err != nil { if err := s.respondError(0, id, err.Error()); err != nil { s.Close() } } else { if err := s.respondOK(id, outbuf); err != nil { s.Close() } } }() return nil } // ----------------------------------------------------------------------------------------------- type streamWriter struct { s *Sock id string wroteEOS bool } func (w *streamWriter) Write(b []byte) (int, error) { z := len(b) if z == 0 { w.wroteEOS = true } return z, w.s.writeMsg(MsgTypeStreamRes, w.id, "", 0, b) } func (w *streamWriter) WriteString(s string) (n int, err error) { z := len(s) if z == 0 { w.wroteEOS = true } return z, w.s.writeMsgString(MsgTypeStreamRes, w.id, "", 0, s) } func (w *streamWriter) Close() error { if !w.wroteEOS { w.wroteEOS = true return w.s.writeMsg(MsgTypeStreamRes, w.id, "", 0, nil) } return nil } func (s *Sock) readStreamReq(limits Limits, id, op string, size int) error { if limits.incStreamReq() == false { if limits.streamReqEnabled() { return s.respondRetry(size, id, limitWaitStreamReq(), "request rate limit") } else { return s.respondError(size, id, "stream requests not supported") } } handler := s.Handlers.FindStreamRequestHandler(op) if handler == nil { err := s.respondError(size, id, "unknown operation \""+op+"\"") limits.decStreamReq() return err } // Read first buff inbuf := make([]byte, size) if _, err := readn(s.conn, inbuf); err != nil { limits.decStreamReq() return err } // Create read chan rch := s.allocReqChan(id) rch <- inbuf // Dispatch handler go func() { // TODO: recover? out := &streamWriter{s, id, false} if err := handler(s, op, rch, out); err != nil { s.deallocReqChan(id) if err := s.respondError(0, id, err.Error()); err != nil { s.Close() } } if err := out.Close(); err != nil { s.Close() } limits.decStreamReq() }() return nil } func (s *Sock) readStreamReqPart(limits Limits, id string, size int) error { rch := s.getReqChan(id) if rch == nil { return errors.New("illegal message") // There was no "start stream" message } var b []byte = nil if size != 0 { b = make([]byte, size) if _, err := readn(s.conn, b); err != nil { limits.decStreamReq() return err } } rch <- b return nil } // ----------------------------------------------------------------------------------------------- func (s *Sock) readResponse(t MsgType, id string, wait, size int) error { ch := s.getResChan(id) if ch == nil { // Unexpected response: discard and ignore return s.readDiscard(size) } if t != MsgTypeStreamRes || size == 0 { s.deallocResChan(id) } // read payload var buf []byte if size != 0 { buf = make([]byte, size) if _, err := readn(s.conn, buf); err != nil { return err } } ch <- Response{t, buf, time.Duration(wait) * time.Millisecond} return nil } func (s *Sock) readNotification(name string, size int) error { handler := s.Handlers.FindNotificationHandler(name) if handler == nil { // read any payload and ignore notification return s.readDiscard(size) } // Read any payload var buf []byte if size != 0 { buf = make([]byte, size) if _, err := readn(s.conn, buf); err != nil { return err } } handler(s, name, buf) return nil } // Before reading any messages over a socket, handshake must happen. This function will block // until the handshake either succeeds or fails. func (s *Sock) Handshake() error { // Write, read and compare version if _, err := WriteVersion(s.conn); err != nil { s.Close() return err } if _, err := ReadVersion(s.conn); err != nil { s.Close() return err } return nil } var ( ErrAbnormal = errors.New("abnormal condition") ErrUnsupported = errors.New("unsupported protocol") ErrInvalidMsg = errors.New("invalid protocol message") ErrTimeout = errors.New("timeout") ) func protocolError(code int) error { switch code { case ProtocolErrorAbnormal: return ErrAbnormal case ProtocolErrorUnsupported: return ErrUnsupported case ProtocolErrorInvalidMsg: return ErrInvalidMsg case ProtocolErrorTimeout: return ErrTimeout default: return errors.New("unknown error") } } func (s *Sock) sendHeartbeats(stopChan chan bool) { // Sleep for a very short amount of time to allow modification of HeartbeatInterval after // e.g. a call to Connect time.Sleep(time.Millisecond) for { // load is just the number of current goroutines. There has to be a more interesting "load" // number to convey... g := float32(runtime.NumGoroutine()-3) / 100000.0 if g > 1 { g = 1 } else if g < 0 { g = 0 } if err := s.SendHeartbeat(g); err != nil { return } select { case <-time.After(s.HeartbeatInterval): continue case <-stopChan: return } } } func (s *Sock) SendHeartbeat(load float32) error { s.wmu.Lock() defer s.wmu.Unlock() if s.conn == nil { return errors.New("not connected") } msg := MakeHeartbeatMsg(uint16(load * float32(HeartbeatMsgMaxLoad))) _, err := s.conn.Write(msg) return err } type netLocalAddressable interface { LocalAddr() net.Addr } // After completing a succesful handshake, call this function to read messages received to this // socket. Does not return until the socket is closed. // If HeartbeatInterval > 0 this method also sends automatic heartbeats. func (s *Sock) Read(limits Limits) error { readTimeout := limits.ReadTimeout() hasReadDeadline := readTimeout != time.Duration(0) var rd readDeadline // Pipes doesn't support deadlines netaddr, ok := s.conn.(netLocalAddressable) isPipe := ok && netaddr.LocalAddr().Network() == "pipe" if hasReadDeadline && isPipe { hasReadDeadline = false } // Start sending heartbeats var heartbeatStopChan chan bool if s.HeartbeatInterval > 0 && !isPipe { if s.HeartbeatInterval < time.Millisecond { panic("HeartbeatInterval < time.Millisecond") } heartbeatStopChan = make(chan bool) go s.sendHeartbeats(heartbeatStopChan) } var err error readloop: for s.conn != nil { // debug: read a chunk and print it // b := make([]byte, 128) // if _, err := s.conn.Read(b); err != nil { // log.Println(err) // break // } // fmt.Printf("Read: %v\n", string(b)) // continue // debug: force close with error // s.CloseError(ProtocolErrorInvalidMsg) // return ErrInvalidMsg // Set read timeout if hasReadDeadline { var ok bool if rd, ok = s.conn.(readDeadline); ok { readTimeoutAt := time.Now().Add(readTimeout) // fmt.Printf("setting read timeout to %v %v\n", readTimeout, readTimeoutAt) if err = rd.SetReadDeadline(readTimeoutAt); err != nil { panic("SetReadDeadline failed: " + err.Error()) } } } // Read next message t, id, name, wait, size, err1 := ReadMsg(s.conn) err = err1 if err == nil { // fmt.Printf("Read: msg: t=%c id=%q name=%q size=%v\n", byte(t), id, name, size) switch t { case MsgTypeSingleReq: err = s.readBufferReq(limits, id, name, int(size)) case MsgTypeStreamReq: err = s.readStreamReq(limits, id, name, int(size)) case MsgTypeStreamReqPart: err = s.readStreamReqPart(limits, id, int(size)) case MsgTypeSingleRes, MsgTypeStreamRes, MsgTypeErrorRes, MsgTypeRetryRes: err = s.readResponse(t, id, int(wait), int(size)) case MsgTypeNotification: err = s.readNotification(name, int(size)) case MsgTypeHeartbeat: if s.OnHeartbeat != nil { s.OnHeartbeat(int(wait), time.Unix(int64(size), 0)) } case MsgTypeProtocolError: code := int(size) s.closeCode = code s.Close() err = protocolError(code) break readloop default: s.CloseError(ProtocolErrorInvalidMsg) err = ErrInvalidMsg break readloop } } if err != nil { if err == io.EOF { s.Close() } else if neterr, ok := err.(net.Error); ok && neterr.Timeout() { s.CloseError(ProtocolErrorTimeout) } else { s.CloseError(ProtocolErrorInvalidMsg) } } } if heartbeatStopChan != nil { heartbeatStopChan <- true } return err } // Address of this socket func (s *Sock) Addr() string { if s.conn != nil { if netconn, ok := s.conn.(net.Conn); ok { return netconn.RemoteAddr().String() } } return "" } // Close this socket because of a protocol error func (s *Sock) CloseError(code int) error { if s.conn != nil { s.closeCode = code s.wmu.Lock() s.conn.Write(MakeMsg(MsgTypeProtocolError, "", "", 0, code)) s.wmu.Unlock() return s.Close() } return nil } // Close this socket func (s *Sock) Close() error { if s.conn != nil { err := s.conn.Close() s.conn = nil if s.CloseHandler != nil { s.CloseHandler(s, s.closeCode) } return err } return nil }
apache-2.0
goozi/data.gov.cn
src/com/dhccity/base/servlet/SecurityAction.java
6367
package com.dhccity.base.servlet; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.light.*; import com.dhccity.base.business.*; import com.dhccity.base.entity.*; /** * <p>Title: BASE_SECURITY ±í¹ÜÀíServletÀà</p> * <p>Description:BASE_SECURITY</p> * <p>Company: dhccity</p> * <p>CreateDate: 2006-02-14 13:51</p> * @author liuxd * @version 1.0 * <servlet><servlet-name>SecurityAction</servlet-name><servlet-class>com.dhccity.base.servlet.SecurityAction</servlet-class></servlet> <servlet-mapping><servlet-name>SecurityAction</servlet-name><url-pattern>/baseSecurityAction</url-pattern></servlet-mapping> */ public class SecurityAction extends ServletAction { private final String SYSTEM_NAME = "ϵͳά»¤×Óϵͳ"; private final String MODULE_NAME = "ȨÏÞ¹ÜÀí"; private final int WINDOW_TYPE = 1; //0±íʾÎÞЧ¡¢1±íʾµ÷ת¡¢2±íʾ¹Ø±Õ /** * Ôö¼ÓÊý¾Ý */ public void addData(HttpRequest request, HttpServletResponse response, User user) throws ServletException, IOException { String name = request.getString("name"); int sequ = request.getInt("sequ"); long parentId = request.getLong("parentId"); String value = request.getString("value"); int type = request.getInt("type"); String explain = request.getString("explain"); String meno = request.getString("meno"); int securityLevel = request.getInt("securityLevel"); //н¨Ò»¸ö¶ÔÏó BaseSecurity baseSecurity = new BaseSecurity(); baseSecurity.setName(name); baseSecurity.setState(1); baseSecurity.setSequ(sequ); baseSecurity.setParentId(parentId); baseSecurity.setValue(value); baseSecurity.setType(type); baseSecurity.setDescription(explain); baseSecurity.setMeno(meno); baseSecurity.setSecurityLevel(securityLevel); baseSecurity.add(); //Ôö¼Ó¼Ç¼ //Ôö¼ÓÏà¹ØÍøÖ·²ÎÊý String[] urls = request.getStringArray("urls"); String[] query = request.getStringArray("querys"); for (int i = 0; i < urls.length; i++) { if (!urls[i].equals("")) { BaseSecurityUrl baseSecurityUrl = new BaseSecurityUrl(); baseSecurityUrl.setSecurityId(baseSecurity.getId()); baseSecurityUrl.setUrl(urls[i]); baseSecurityUrl.setQuery(query[i]); baseSecurityUrl.add(); //Ôö¼Ó¼Ç¼ } } user.addLog(SYSTEM_NAME, MODULE_NAME, "Ôö¼Ó¼Ç¼[" + name + "]"); doReturn(response, WINDOW_TYPE, "security_list.jsp?searchField=id&searchValue=" + baseSecurity.getId() + "&search=ËÑË÷"); } /** * ÐÞ¸ÄÊý¾Ý */ public void updateData(HttpRequest request, HttpServletResponse response, User user) throws ServletException, IOException { long id = request.getLong("id"); String name = request.getString("name"); int sequ = request.getInt("sequ"); long parentId = request.getLong("parentId"); String value = request.getString("value"); int type = request.getInt("type"); String explain = request.getString("explain"); String meno = request.getString("meno"); int securityLevel = request.getInt("securityLevel"); //н¨Ò»¸ö¶ÔÏó BaseSecurity baseSecurity = (BaseSecurity)new BaseSecurity().findById(id); baseSecurity.setName(name); baseSecurity.setSequ(sequ); baseSecurity.setParentId(parentId); baseSecurity.setValue(value); baseSecurity.setType(type); baseSecurity.setDescription(explain); baseSecurity.setMeno(meno); baseSecurity.setSecurityLevel(securityLevel); baseSecurity.update(); //Ð޸ļǼ //ÐÞ¸ÄÏà¹ØÍøÖ·²ÎÊý String[] urls = request.getStringArray("urls"); String[] query = request.getStringArray("querys"); long[] ids = request.getLongArray("ids"); BaseSecurityUrl.deleteBySecurityId(baseSecurity.getId(), ids); for (int i = 0; i < urls.length; i++) { if (!urls[i].equals("") && ids[i] > 0) { BaseSecurityUrl baseSecurityUrl = (BaseSecurityUrl)new BaseSecurityUrl().findById(ids[i]); baseSecurityUrl.setSecurityId(baseSecurity.getId()); baseSecurityUrl.setUrl(urls[i]); baseSecurityUrl.setQuery(query[i]); baseSecurityUrl.update(); //Ð޸ļǼ } if (!urls[i].equals("") && ids[i] == 0) { BaseSecurityUrl baseSecurityUrl = new BaseSecurityUrl(); baseSecurityUrl.setSecurityId(baseSecurity.getId()); baseSecurityUrl.setUrl(urls[i]); baseSecurityUrl.setQuery(query[i]); baseSecurityUrl.add(); //Ôö¼Ó¼Ç¼ } } user.addLog(SYSTEM_NAME, MODULE_NAME, "Ð޸ļǼ[" + name + "]"); doReturn(response, WINDOW_TYPE, "security_list.jsp?searchField=id&searchValue=" + baseSecurity.getId() + "&search=ËÑË÷"); } /** * ¸Ä±ä״̬ */ public void updateState(HttpRequest request, HttpServletResponse response, User user) throws ServletException, IOException { long[] idArray = request.getLongArray("idArray"); int state = request.getInt("state"); String log = ""; if (idArray != null) { for (int i = 0; i < idArray.length; i++) { BaseSecurity baseSecurity = (BaseSecurity)new BaseSecurity().findById(idArray[i]); baseSecurity.setState(state); baseSecurity.update(); log += baseSecurity.getName() + ";"; } } if (state == 0) { user.addLog(SYSTEM_NAME, MODULE_NAME, "ɾ³ý¼Ç¼[" + log + "]"); } else { user.addLog(SYSTEM_NAME, MODULE_NAME, "»Ö¸´¼Ç¼[" + log + "]"); } } /** * ´´½¨µ¥Ñ¡Ê÷XML */ public void createRadioTreeXml(HttpRequest request, HttpServletResponse response, User user) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.print(SecurityApp.createRadioTreeXml()); } /** * ´´½¨Ê÷ÐÎXML */ public void createTreeXml(HttpRequest request, HttpServletResponse response, User user) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.print(TreeApp.createTreeXml("Security")); } /** * ¼ì²â´úÂëÊÇ·ñ´æÔÚ */ public void checkCode(HttpRequest request, HttpServletResponse response, User user) throws ServletException, IOException { String code = request.getString("code"); long id = request.getLong("id"); long parentId = request.getLong("parentId"); int type = request.getInt("type"); PrintWriter out = response.getWriter(); if (BaseSecurity.isHadCode(id, code, parentId, type)) { out.print("false"); } else { out.print("true"); } } }
apache-2.0
kapilt/cloud-custodian
tests/test_iamgen.py
3515
# Copyright 2020 Amazon.com, Inc. or its affiliates. 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. from .common import BaseTest, load_data from c7n.config import Config, Bag from c7n import manager import fnmatch class TestIamGen(BaseTest): def check_permissions(self, perm_db, perm_set, path): invalid = [] for p in perm_set: if ':' not in p: invalid.append(p) continue s, a = p.split(':', 1) if s not in perm_db: invalid.append(p) continue if '*' in a: if not fnmatch.filter(perm_db[s], a): invalid.append(p) continue elif a not in perm_db[s]: invalid.append(p) if not invalid: return [] return [(path, invalid)] def test_iam_permissions_validity(self): cfg = Config.empty() missing = set() all_invalid = [] perms = load_data('iam-actions.json') for k, v in manager.resources.items(): p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'}) ctx = self.get_context(config=cfg, policy=p) mgr = v(ctx, p) invalid = [] # if getattr(mgr, 'permissions', None): # print(mgr) found = False for s in (mgr.resource_type.service, getattr(mgr.resource_type, 'permission_prefix', None)): if s in perms: found = True if not found: missing.add("%s->%s" % (k, mgr.resource_type.service)) continue invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k)) for n, a in v.action_registry.items(): p['actions'] = [n] invalid.extend( self.check_permissions( perms, a({}, mgr).get_permissions(), "{k}.actions.{n}".format(k=k, n=n))) for n, f in v.filter_registry.items(): if n in ('or', 'and', 'not', 'missing'): continue p['filters'] = [n] invalid.extend( self.check_permissions( perms, f({}, mgr).get_permissions(), "{k}.filters.{n}".format(k=k, n=n))) if invalid: for k, perm_set in invalid: perm_set = [i for i in perm_set if not i.startswith('elasticloadbalancing')] if perm_set: all_invalid.append((k, perm_set)) if missing: raise ValueError( "resources missing service %s" % ('\n'.join(sorted(missing)))) if all_invalid: raise ValueError( "invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
apache-2.0
domaframework/doma
doma-core/src/main/java/org/seasar/doma/internal/jdbc/util/SqlFileUtil.java
884
package org.seasar.doma.internal.jdbc.util; import java.io.File; import org.seasar.doma.internal.Constants; import org.seasar.doma.jdbc.dialect.Dialect; public final class SqlFileUtil { private static final String PREFIX = Constants.SQL_PATH_PREFIX; private static final String SUFFIX = Constants.SQL_PATH_SUFFIX; public static String buildPath(String className, String methodName) { return FileUtil.buildPath(PREFIX, SUFFIX, className, methodName); } public static String buildPath(String className) { return FileUtil.buildPath(PREFIX, SUFFIX, className); } public static boolean isSqlFile(File file, String methodName) { return FileUtil.isFile(PREFIX, SUFFIX, file, methodName); } public static String convertToDbmsSpecificPath(String path, Dialect dialect) { return FileUtil.convertToDbmsSpecificPath(PREFIX, SUFFIX, path, dialect); } }
apache-2.0
nimble-platform/frontend-service
src/app/catalogue/model/publish/code.ts
1115
/* * Copyright 2020 * SRDC - Software Research & Development Consultancy; Ankara; Turkey In collaboration with * SRFG - Salzburg Research Forschungsgesellschaft mbH; Salzburg; Austria * UB - University of Bremen, Faculty of Production Engineering; Bremen; Germany * BIBA - Bremer Institut für Produktion und Logistik GmbH; Bremen; Germany 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. */ export class Code { constructor(public value: string = "", public name: string = "", public uri: string = "", public listID: string = "", public listURI: string = "") { } }
apache-2.0
radez/packstack
packstack/plugins/puppet_950.py
9838
""" Installs and configures puppet """ import sys import logging import os import platform import time from packstack.installer import utils from packstack.installer import basedefs, output_messages from packstack.installer.exceptions import ScriptRuntimeError from packstack.modules.common import filtered_hosts from packstack.modules.ospluginutils import manifestfiles from packstack.modules.puppet import scan_logfile, validate_logfile # Controller object will be initialized from main flow controller = None # Plugin name PLUGIN_NAME = "OSPUPPET" PLUGIN_NAME_COLORED = utils.color_text(PLUGIN_NAME, 'blue') logging.debug("plugin %s loaded", __name__) PUPPETDIR = os.path.abspath(os.path.join(basedefs.DIR_PROJECT_DIR, 'puppet')) MODULEDIR = os.path.join(PUPPETDIR, "modules") def initConfig(controllerObject): global controller controller = controllerObject logging.debug("Adding OpenStack Puppet configuration") paramsList = [ ] groupDict = {"GROUP_NAME" : "PUPPET", "DESCRIPTION" : "Puppet Config parameters", "PRE_CONDITION" : lambda x: 'yes', "PRE_CONDITION_MATCH" : "yes", "POST_CONDITION" : False, "POST_CONDITION_MATCH" : True} controller.addGroup(groupDict, paramsList) def initSequences(controller): puppetpresteps = [ {'title': 'Clean Up', 'functions':[runCleanup]}, ] controller.insertSequence("Clean Up", [], [], puppetpresteps, index=0) puppetsteps = [ {'title': 'Installing Dependencies', 'functions': [installdeps]}, {'title': 'Copying Puppet modules and manifests', 'functions': [copyPuppetModules]}, {'title': 'Applying Puppet manifests', 'functions': [applyPuppetManifest]}, {'title': 'Finalizing', 'functions': [finalize]} ] controller.addSequence("Puppet", [], [], puppetsteps) def runCleanup(config): localserver = utils.ScriptRunner() localserver.append("rm -rf %s/*pp" % basedefs.PUPPET_MANIFEST_DIR) localserver.execute() def installdeps(config): for hostname in filtered_hosts(config): server = utils.ScriptRunner(hostname) for package in ("puppet", "openssh-clients", "tar", "nc"): server.append("rpm -q %s || yum install -y %s" % (package, package)) server.execute() def copyPuppetModules(config): os_modules = ' '.join(('apache', 'ceilometer', 'cinder', 'concat', 'create_resources', 'firewall', 'glance', 'heat', 'horizon', 'inifile', 'keystone', 'memcached', 'mongodb', 'mysql', 'neutron', 'nova', 'openstack', 'packstack', 'qpid', 'rsync', 'ssh', 'stdlib', 'swift', 'sysctl', 'tempest', 'vcsrepo', 'vlan', 'vswitch', 'xinetd')) # write puppet manifest to disk manifestfiles.writeManifests() server = utils.ScriptRunner() tar_opts = "" if platform.linux_distribution()[0] == "Fedora": tar_opts += "--exclude create_resources " for hostname in filtered_hosts(config): host_dir = controller.temp_map[hostname] server.append("cd %s/puppet" % basedefs.DIR_PROJECT_DIR) # copy Packstack facts server.append("tar %s --dereference -cpzf - facts | " "ssh -o StrictHostKeyChecking=no " "-o UserKnownHostsFile=/dev/null " "root@%s tar -C %s -xpzf -" % (tar_opts, hostname, host_dir)) # copy Packstack manifests server.append("cd %s" % basedefs.PUPPET_MANIFEST_DIR) server.append("tar %s --dereference -cpzf - ../manifests | " "ssh -o StrictHostKeyChecking=no " "-o UserKnownHostsFile=/dev/null " "root@%s tar -C %s -xpzf -" % (tar_opts, hostname, host_dir)) # copy resources for path, localname in controller.resources.get(hostname, []): server.append("scp -o StrictHostKeyChecking=no " "-o UserKnownHostsFile=/dev/null %s root@%s:%s/resources/%s" % (path, hostname, host_dir, localname)) # copy Puppet modules required by Packstack server.append("cd %s/puppet/modules" % basedefs.DIR_PROJECT_DIR) server.append("tar %s --dereference -cpzf - %s | " "ssh -o StrictHostKeyChecking=no " "-o UserKnownHostsFile=/dev/null " "root@%s tar -C %s -xpzf -" % (tar_opts, os_modules, hostname, os.path.join(host_dir, 'modules'))) server.execute() def waitforpuppet(currently_running): global controller log_len = 0 twirl = ["-","\\","|","/"] while currently_running: for hostname, finished_logfile in currently_running: log_file = os.path.splitext(os.path.basename(finished_logfile))[0] space_len = basedefs.SPACE_LEN - len(log_file) if len(log_file) > log_len: log_len = len(log_file) if hasattr(sys.stdout, "isatty") and sys.stdout.isatty(): twirl = twirl[-1:] + twirl[:-1] sys.stdout.write(("\rTesting if puppet apply is finished : %s" % log_file).ljust(40 + log_len)) sys.stdout.write("[ %s ]" % twirl[0]) sys.stdout.flush() try: # Once a remote puppet run has finished, we retrieve the log # file and check it for errors local_server = utils.ScriptRunner() log = os.path.join(basedefs.PUPPET_MANIFEST_DIR, os.path.basename(finished_logfile).replace(".finished", ".log")) local_server.append('scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@%s:%s %s' % (hostname, finished_logfile, log)) # To not pollute logs we turn of logging of command execution local_server.execute(log=False) # If we got to this point the puppet apply has finished currently_running.remove((hostname, finished_logfile)) # clean off the last "testing apply" msg if hasattr(sys.stdout, "isatty") and sys.stdout.isatty(): sys.stdout.write(("\r").ljust(45 + log_len)) except ScriptRuntimeError: # the test raises an exception if the file doesn't exist yet # TO-DO: We need to start testing 'e' for unexpected exceptions time.sleep(3) continue # check log file for relevant notices controller.MESSAGES.extend(scan_logfile(log)) # check the log file for errors validate_logfile(log) sys.stdout.write(("\r%s : " % log_file).ljust(space_len)) print ("[ " + utils.color_text(output_messages.INFO_DONE, 'green') + " ]") def applyPuppetManifest(config): print currently_running = [] lastmarker = None for manifest, marker in manifestfiles.getFiles(): # if the marker has changed then we don't want to proceed until # all of the previous puppet runs have finished if lastmarker != None and lastmarker != marker: waitforpuppet(currently_running) lastmarker = marker for hostname in filtered_hosts(config): if "%s_" % hostname not in manifest: continue host_dir = controller.temp_map[hostname] print "Applying " + manifest server = utils.ScriptRunner(hostname) man_path = os.path.join(controller.temp_map[hostname], basedefs.PUPPET_MANIFEST_RELATIVE, manifest) running_logfile = "%s.running" % man_path finished_logfile = "%s.finished" % man_path currently_running.append((hostname, finished_logfile)) # The apache puppet module doesn't work if we set FACTERLIB # https://github.com/puppetlabs/puppetlabs-apache/pull/138 if not (manifest.endswith('_horizon.pp') or manifest.endswith('_nagios.pp')): server.append("export FACTERLIB=$FACTERLIB:%s/facts" % host_dir) server.append("touch %s" % running_logfile) server.append("chmod 600 %s" % running_logfile) server.append("export PACKSTACK_VAR_DIR=%s" % host_dir) loglevel = '' if logging.root.level <= logging.DEBUG: loglevel = '--debug' command = "( flock %s/ps.lock puppet apply %s --modulepath %s/modules %s > %s 2>&1 < /dev/null ; mv %s %s ) > /dev/null 2>&1 < /dev/null &" % (host_dir, loglevel, host_dir, man_path, running_logfile, running_logfile, finished_logfile) server.append(command) server.execute() # wait for outstanding puppet runs befor exiting waitforpuppet(currently_running) def finalize(config): for hostname in filtered_hosts(config): server = utils.ScriptRunner(hostname) server.append("installed=$(rpm -q kernel --last | head -n1 | " "sed 's/kernel-\([a-z0-9\.\_\-]*\).*/\\1/g')") server.append("loaded=$(uname -r | head -n1)") server.append('[ "$loaded" == "$installed" ]') try: rc, out = server.execute() except ScriptRuntimeError: controller.MESSAGES.append('Because of the kernel update the host ' '%s requires reboot.' % hostname)
apache-2.0
gallandarakhneorg/afc
advanced/gis/gisbus/src/test/java/org/arakhne/afc/gis/bus/network/TestEventHandler.java
6043
/* * $Id$ * This file is a part of the Arakhne Foundation Classes, http://www.arakhne.org/afc * * Copyright (c) 2000-2012 Stephane GALLAND. * Copyright (c) 2005-10, Multiagent Team, Laboratoire Systemes et Transports, * Universite de Technologie de Belfort-Montbeliard. * Copyright (c) 2013-2020 The original authors, and other 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. */ package org.arakhne.afc.gis.bus.network; import static org.junit.jupiter.api.Assertions.fail; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.arakhne.afc.gis.bus.network.BusChangeEvent.BusChangeEventType; /** * Event handler for the unit tests. * * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ * @since 14.0 */ @SuppressWarnings("all") public class TestEventHandler implements BusChangeListener { /** */ private boolean run; /** */ private final List<BusChangeEvent> busChanged = new ArrayList<>(); /** */ private final List<BusChangeEvent> busShapeAttrChanged = new ArrayList<>(); /** */ private final List<BusChangeEvent> busShapeChanged = new ArrayList<>(); /** */ public TestEventHandler() { clear(); } /** */ public void clear() { this.run = false; this.busChanged.clear(); this.busShapeAttrChanged.clear(); this.busShapeChanged.clear(); } /** * {@inheritDoc} */ @Override public void onBusPrimitiveChanged(BusChangeEvent event) { this.run = true; this.busChanged.add(event); } /** * {@inheritDoc} */ @Override public void onBusPrimitiveGraphicalAttributeChanged(BusChangeEvent event) { this.run = true; this.busShapeAttrChanged.add(event); } /** * {@inheritDoc} */ @Override public void onBusPrimitiveShapeChanged(BusChangeEvent event) { this.run = true; this.busShapeChanged.add(event); } /** Assert no event. */ public void assertNoEvent() { assertFalse("Event was fired", this.run); //$NON-NLS-1$ assertTrue("Event was fired", this.busChanged.isEmpty()); //$NON-NLS-1$ assertTrue("Event was fired", this.busShapeChanged.isEmpty()); //$NON-NLS-1$ assertTrue("Event was fired", this.busShapeAttrChanged.isEmpty()); //$NON-NLS-1$ } /** Assert no general event. */ public void assertNoBusChangedEvent() { assertTrue("Event was fired:" //$NON-NLS-1$ +this.busChanged.toString(), this.busChanged.isEmpty()); } /** Assert no shape event. */ public void assertNoBusShapeChangedEvent() { assertTrue("Event was fired:" //$NON-NLS-1$ +this.busShapeChanged.toString(), this.busShapeChanged.isEmpty()); } /** Assert no shape attribute event. */ public void assertNoBusShapeAttrChangedEvent() { assertTrue("Event was fired:" //$NON-NLS-1$ +this.busShapeAttrChanged.toString(), this.busShapeAttrChanged.isEmpty()); } private static BusChangeEvent event(BusChangeEventType desiredType, Object desiredPrimitive, List<BusChangeEvent> events) { Iterator<BusChangeEvent> iterator = events.iterator(); BusChangeEvent event; while(iterator.hasNext()) { event = iterator.next(); if (event.getEventType()==desiredType && event.getChangedObject()==desiredPrimitive) { iterator.remove(); return event; } } return null; } /** Assert the event corresponds to the given parameters. * * @param desiredType is the desired type of event. * @param desiredPrimitive is the desired changed primitive. */ public void assertBusChangedEvent(BusChangeEventType desiredType, Object desiredPrimitive) { assertTrue("Event was not fired", this.run); //$NON-NLS-1$ assertNotNull("Event not found", event(desiredType, desiredPrimitive, this.busChanged)); //$NON-NLS-1$ } /** Assert the event corresponds to the given parameters. * * @param desiredType is the desired type of event. * @param desiredPrimitive is the desired changed primitive. */ public void assertBusShapeChangedEvent(BusChangeEventType desiredType, Object desiredPrimitive) { assertTrue("Event was not fired", this.run); //$NON-NLS-1$ assertNotNull("Event not found", event(desiredType, desiredPrimitive, this.busShapeChanged)); //$NON-NLS-1$ } /** Assert the event corresponds to the given parameters. * * @param desiredType is the desired type of event. * @param desiredPrimitive is the desired changed primitive. */ public void assertBusShapeAttrChangedEvent(BusChangeEventType desiredType, Object desiredPrimitive) { assertTrue("Event was not fired", this.run); //$NON-NLS-1$ assertNotNull("Event not found", event(desiredType, desiredPrimitive, this.busShapeAttrChanged)); //$NON-NLS-1$ } private static void assertTrue(String message, boolean value) { if (!value) { StringBuilder m = new StringBuilder(message); m.append("; expected: "); //$NON-NLS-1$ m.append(Boolean.TRUE); m.append("; actual: "); //$NON-NLS-1$ m.append(value); fail(message); } } private static void assertFalse(String message, boolean value) { if (value) { StringBuilder m = new StringBuilder(message); m.append("; expected: "); //$NON-NLS-1$ m.append(Boolean.TRUE); m.append("; actual: "); //$NON-NLS-1$ m.append(value); fail(message); } } private static void assertNotNull(String message, Object actual) { if (actual==null) { StringBuilder m = new StringBuilder(message); m.append("; no null expected"); //$NON-NLS-1$ m.append("; actual: "); //$NON-NLS-1$ m.append(actual); fail(m.toString()); } } }
apache-2.0
thbonk/electron-openui5-boilerplate
libs/openui5-runtime/resources/sap/ui/rta/command/CreateContainer-dbg.js
1332
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2017 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['jquery.sap.global', 'sap/ui/rta/command/FlexCommand'], function(jQuery, FlexCommand) { "use strict"; /** * Create new container * * @class * @extends sap.ui.rta.command.FlexCommand * @author SAP SE * @version 1.50.8 * @constructor * @private * @since 1.34 * @alias sap.ui.rta.command.CreateContainer * @experimental Since 1.34. This class is experimental and provides only limited functionality. Also the API might be * changed in future. */ var CreateContainer = FlexCommand.extend("sap.ui.rta.command.CreateContainer", { metadata : { library : "sap.ui.rta", properties : { index : { type : "int" }, newControlId : { type : "string" }, label : { type : "string" } }, associations : {}, events : {} } }); CreateContainer.prototype._getChangeSpecificData = function(bForward) { var mSpecificInfo = { changeType : this.getChangeType(), index : this.getIndex(), newControlId : this.getNewControlId(), newLabel : this.getLabel() }; return mSpecificInfo; }; return CreateContainer; }, /* bExport= */true);
apache-2.0
opscode-cookbooks/opscode-erlang
providers/otp_build.rb
3060
# OTP build LWRP # # Build from source, either a local dir or a git repo. # Results in a tarball. # use_inline_resources action :build do @run_context.include_recipe "erlang_binary::default" @run_context.include_recipe "erlang_binary::rebar" # destination dir in case it doesn't exist dest_dir = ::File.dirname(new_resource.tarball) directory dest_dir do owner new_resource.owner group new_resource.group mode new_resource.dir_mode recursive true not_if "test -d #{dest_dir}" end if new_resource.source =~ /^git/ # Source is a git reference. Sync git repo. @run_context.include_recipe "git" src_dir = "#{new_resource.src_root_dir}/#{new_resource.name}" git_source_repo src_dir else # source is a local directory src_dir = new_resource.source ruby_block "signal_rebuild" do block do Chef::Log.info("*** Signalling a rebuild of #{new_resource.source}") end notifies :create, "ruby_block[rebuild_#{new_resource.name}]", :immediately end end # Encapsulates clean build logic. ruby_block "cleanbuild_#{new_resource.name}" do block do Chef::Log.info("*** Clean build #{new_resource.name}") end notifies :run, "execute[distclean_#{new_resource.name}]", :immediately notifies :create, "ruby_block[rebuild_#{new_resource.name}]", :immediately action :nothing end # Encapsulates build logic and service restart. ruby_block "rebuild_#{new_resource.name}" do block do Chef::Log.info("*** Rebuild #{new_resource.name}") end notifies :run, "execute[rel_#{new_resource.name}]", :immediately notifies :run, "execute[tar_#{new_resource.name}]", :immediately action :nothing end # erlexec needs HOME env var to be set. If it's not set, it errors out. # This seems to happen when chef-client runs daemonized. unless ENV['HOME'] environment({'HOME' => '/root'}) end # `make distclean` execute "distclean_#{new_resource.name}" do command "make distclean" cwd src_dir action :nothing end # `make relclean rel` execute "rel_#{new_resource.name}" do command "make relclean rel" cwd src_dir action :nothing end # tar it up execute "tar_#{new_resource.name}" do command "tar czf #{new_resource.tarball} #{new_resource.name}" cwd "#{src_dir}/rel" action :nothing end end def git_source_repo(src_dir) if new_resource.force_clean_src Chef::Log.info("*** Force cleanup of #{src_dir}") execute "cleanup_#{new_resource.name}_src" do command "rm -Rf #{src_dir}" end end directory src_dir do owner new_resource.owner group new_resource.group mode new_resource.dir_mode recursive true end git "#{new_resource.name}_source" do destination src_dir repository new_resource.source # "git@github.com:opscode/#{app_name}.git" revision new_resource.revision user new_resource.owner group new_resource.group notifies :create, "ruby_block[cleanbuild_#{new_resource.name}]", :immediately end end
apache-2.0
imangit/Advertise
Advertise/Advertise.Mapping/Profiles/Categories/CategoryFollowProfile.cs
1354
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Advertise.DomainClasses.Entities.Categories; using Advertise.ViewModel.Models.Categories; using Advertise.ViewModel.Models.Categories.CategoryFollow; using AutoMapper; namespace Advertise.Mapping.Profiles.Categories { public class CategoryFollowProfile : Profile { public CategoryFollowProfile() { CreateMap<CategoryFollow, CategoryFollowCreateViewModel>() .ProjectUsing(src => new CategoryFollowCreateViewModel { IsFollow = src.IsFollow }); CreateMap<CategoryFollowCreateViewModel, CategoryFollow>() .ForMember(dest => dest.IsFollow, opts => opts.MapFrom(src => src.IsFollow)) .ForAllOtherMembers(opt => opt.Ignore()); CreateMap<CategoryFollow, CategoryFollowEditViewModel >() .ProjectUsing(src => new CategoryFollowEditViewModel { IsFollow = src.IsFollow }); CreateMap<CategoryFollowEditViewModel, CategoryFollow>() .ForMember(dest => dest.IsFollow, opts => opts.MapFrom(src => src.IsFollow)) .ForAllOtherMembers(opt => opt.Ignore()); } } }
apache-2.0
ZSD123/uniqueWeather
src/adapter/ChatAdapter.java
8879
package adapter; import activity.fragmentChat; import android.content.Context; import android.graphics.Color; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.sharefriend.app.R; import cn.bmob.newim.bean.BmobIMConversation; import cn.bmob.newim.bean.BmobIMMessage; import cn.bmob.newim.bean.BmobIMMessageType; import cn.bmob.v3.BmobUser; /** * @author :smile * @project:ChatAdapter * @date :2016-01-22-14:18 */ public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{ //Îı¾ private final int TYPE_RECEIVER_TXT = 0; private final int TYPE_SEND_TXT = 1; //ͼƬ private final int TYPE_SEND_IMAGE = 2; private final int TYPE_RECEIVER_IMAGE = 3; //λÖà private final int TYPE_SEND_LOCATION = 4; private final int TYPE_RECEIVER_LOCATION = 5; //ÓïÒô private final int TYPE_SEND_VOICE =6; private final int TYPE_RECEIVER_VOICE = 7; //ÊÓÆµ private final int TYPE_SEND_VIDEO =8; private final int TYPE_RECEIVER_VIDEO = 9; //ͬÒâÌí¼ÓºÃÓѳɹ¦ºóµÄÑùʽ private int TYPE_AGREE = 10; private Context mContext; /** * ÏÔʾʱ¼ä¼ä¸ô:10·ÖÖÓ */ private final long TIME_INTERVAL = 10 * 60 * 1000; private List<BmobIMMessage> msgs = new ArrayList<BmobIMMessage>(); private String currentUid=""; BmobIMConversation c; public ChatAdapter(Context context,BmobIMConversation c) { try { currentUid = BmobUser.getCurrentUser().getObjectId(); mContext=context; } catch (Exception e) { e.printStackTrace(); } this.c =c; } public int findPosition(BmobIMMessage message) { int index = this.getCount(); int position = -1; while(index-- > 0) { if(message.equals(this.getItem(index))) { position = index; break; } } return position; } public int findPosition(long id) { int index = this.getCount(); int position = -1; while(index-- > 0) { if(this.getItemId(index) == id) { position = index; break; } } return position; } public int getCount() { return this.msgs == null?0:this.msgs.size(); } public void addMessages(List<BmobIMMessage> messages) { msgs.addAll(0, messages); notifyDataSetChanged(); } public void addMessage(BmobIMMessage message) { msgs.addAll(Arrays.asList(message)); notifyDataSetChanged(); } /**»ñÈ¡ÏûÏ¢ * @param position * @return */ public BmobIMMessage getItem(int position){ return this.msgs == null?null:(position >= this.msgs.size()?null:this.msgs.get(position)); } /**ÒÆ³ýÏûÏ¢ * @param position */ public void remove(int position){ msgs.remove(position); notifyDataSetChanged(); } public BmobIMMessage getFirstMessage() { if (null != msgs && msgs.size() > 0) { return msgs.get(0); } else { return null; } } public List<BmobIMMessage> getMessages(){ if (null != msgs && msgs.size() > 0) { return msgs; } else { return null; } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == TYPE_SEND_TXT) { return new SendTextHolder(parent.getContext(), parent,c,onRecyclerViewListener,LayoutInflater.from(mContext).inflate(R.layout.item_chat_sent_message,parent,false));//ÕâÀïÊÇ·¢ËÍÎı¾ÊÊÅäÆ÷ } else if (viewType == TYPE_SEND_IMAGE) { return new SendImageHolder(parent.getContext(), parent,c,onRecyclerViewListener,LayoutInflater.from(mContext).inflate(R.layout.item_chat_sent_image,parent,false)); }else if (viewType == TYPE_SEND_VOICE) { return new SendVoiceHolder(parent.getContext(), parent,c,onRecyclerViewListener,LayoutInflater.from(mContext).inflate(R.layout.item_chat_sent_voice,parent,false)); } else if (viewType == TYPE_RECEIVER_TXT) { return new ReceiveTextHolder(parent.getContext(), parent,onRecyclerViewListener,LayoutInflater.from(mContext).inflate(R.layout.item_chat_received_message,parent,false)); } else if (viewType == TYPE_RECEIVER_IMAGE) { return new ReceiveImageHolder(parent.getContext(), parent,onRecyclerViewListener,LayoutInflater.from(mContext).inflate(R.layout.item_chat_received_image,parent,false)); } else if (viewType == TYPE_RECEIVER_VOICE) { return new ReceiveVoiceHolder(parent.getContext(), parent,onRecyclerViewListener,LayoutInflater.from(mContext).inflate(R.layout.item_chat_received_voice,parent,false)); } else if (viewType == TYPE_SEND_VIDEO) { return new SendVideoHolder(parent.getContext(), parent,c,onRecyclerViewListener,LayoutInflater.from(mContext).inflate(R.layout.item_chat_sent_video,parent,false)); } else if (viewType == TYPE_RECEIVER_VIDEO) { return new ReceiveVideoHolder(parent.getContext(), parent,onRecyclerViewListener,LayoutInflater.from(mContext).inflate(R.layout.item_chat_received_video,parent,false)); }else if(viewType ==TYPE_AGREE) { return new AgreeHolder(parent.getContext(),parent,onRecyclerViewListener,LayoutInflater.from(mContext).inflate(R.layout.item_chat_agree,parent,false)); }else{//¿ª·¢Õß×Ô¶¨ÒåµÄÆäËûÀàÐÍ£¬¿É×ÔÐд¦Àí return null; } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ((BaseViewHolder)holder).bindData(msgs.get(position)); if (holder instanceof ReceiveTextHolder) { ((ReceiveTextHolder)holder).showTime(shouldShowTime(position)); } else if (holder instanceof ReceiveImageHolder) { ((ReceiveImageHolder)holder).showTime(shouldShowTime(position)); }else if (holder instanceof ReceiveVoiceHolder) { ((ReceiveVoiceHolder)holder).showTime(shouldShowTime(position)); }else if (holder instanceof SendTextHolder) { ((SendTextHolder)holder).showTime(shouldShowTime(position)); }else if (holder instanceof SendImageHolder) { ((SendImageHolder)holder).showTime(shouldShowTime(position)); }else if (holder instanceof SendVoiceHolder) { ((SendVoiceHolder)holder).showTime(shouldShowTime(position)); }else if (holder instanceof SendVideoHolder) {//Ëæ±ãÄ£ÄâµÄÊÓÆµÀàÐÍ ((SendVideoHolder)holder).showTime(shouldShowTime(position)); }else if (holder instanceof ReceiveVideoHolder) { ((ReceiveVideoHolder)holder).showTime(shouldShowTime(position)); }else if (holder instanceof AgreeHolder) {//ͬÒâÌí¼ÓºÃÓѳɹ¦ºóµÄÏûÏ¢ ((AgreeHolder)holder).showTime(shouldShowTime(position)); } } @Override public int getItemViewType(int position) { BmobIMMessage message = msgs.get(position); if(message.getMsgType().equals(BmobIMMessageType.IMAGE.getType())){ return message.getFromId().equals(currentUid) ? TYPE_SEND_IMAGE: TYPE_RECEIVER_IMAGE; }else if(message.getMsgType().equals(BmobIMMessageType.LOCATION.getType())){ return message.getFromId().equals(currentUid) ? TYPE_SEND_LOCATION: TYPE_RECEIVER_LOCATION; }else if(message.getMsgType().equals(BmobIMMessageType.VOICE.getType())){ return message.getFromId().equals(currentUid) ? TYPE_SEND_VOICE: TYPE_RECEIVER_VOICE; }else if(message.getMsgType().equals(BmobIMMessageType.TEXT.getType())){ return message.getFromId().equals(currentUid) ? TYPE_SEND_TXT: TYPE_RECEIVER_TXT; }else if(message.getMsgType().equals(BmobIMMessageType.VIDEO.getType())){ return message.getFromId().equals(currentUid) ? TYPE_SEND_VIDEO: TYPE_RECEIVER_VIDEO; }else if(message.getMsgType().equals("agree")) {//ÏÔʾ»¶Ó­ return TYPE_AGREE; }else{ return -1; } } @Override public int getItemCount() { return msgs.size(); } private OnRecyclerViewListener onRecyclerViewListener; public void setOnRecyclerViewListener(OnRecyclerViewListener onRecyclerViewListener) { this.onRecyclerViewListener = onRecyclerViewListener; } private boolean shouldShowTime(int position) { if (position == 0) { return true; } long lastTime = msgs.get(position - 1).getCreateTime(); long curTime = msgs.get(position).getCreateTime(); return curTime - lastTime > TIME_INTERVAL; } }
apache-2.0
kapilupadhayay/Programs
Python/Chess/dp.nQueen.py
3429
#!/usr/bin/python import sys def get_queens_line_of_sight(Q, maxR, maxC): line_of_sight_list = [] # contains all the tuples that are in the line of sight # first we get the straight line of sights, both horizontal and vertical. for r in xrange(0,maxR): line_of_sight_list.append((r, Q[1])) for c in xrange(0,maxC): line_of_sight_list.append((Q[0], c)) # diagonals \ and / # # first \ diagonal if Q[0] == Q[1]: r,c = 0,0 # row column elif Q[0] < Q[1]: # upper triangle w.r.t middle (n,n) diagonal r = 0 # here the r value in tuple is < c value c = Q[1] - Q[0] else: r = Q[0] - Q[1] c = 0 while (r < maxR and c < maxC): line_of_sight_list.append((r,c)) r = r + 1 c = c + 1 # Now / diagonal, board must be square if (Q[0] + Q [1]) <= maxR - 1: r = Q[0] + Q[1] c = 0 else: rcSum = Q[0] + Q[1] r = maxR - 1 c = rcSum - r while (r >= 0 and c < maxC): line_of_sight_list.append((r,c)) r = r - 1 c = c + 1 # converting to set and back to list removes the # duplicates. But it also reshuffels the tupples # which makes it difficult to understand the sequence # of the tupples in the line of sight. #print "Q:", Q, "LoS:", line_of_sight_list return list(set(line_of_sight_list)) #c is column number starting with 0. Incidently, the Queen number too. #board : We use a list of tuples to represent the current state #of the board with nth tupple specifying the coordinate #of nth queen. #We start with placing the 0th queen on 0th column, successively #increasing n column wise. Obviously, each column #must have one and only one queen and no column must have #0 queens. # Now we add another list los i.e Line of sight. Instead of # every time calculating the los for any change in queens position # we calculate it at the time of queen's placement and add it to # the field of sight(fos). This fos is next passed to the subsequent # recusrsions as at n column all the queens < n are going to stay the # same only the n+1th and subsequent queens change their locations. # This yields in significant increase in the speed # Following are the results: # #Board Squares #sol bt dp # -------------------------------------------------- # 10 724 0m26.981s 0m1.545s # 11 2680 2m48.230s 0m6.468s # 12 14200 18m31.642s 0m37.687s # 13 73712 Not Executed 4m05.344s # 14 365596 Not Executed 30m15.249s def move_next_queen(c, b, R, C, los): # We will not change the state of board passed to us but # will take a copy of it and change that instead. Thus the # state of the board propagates under recursion keeping the # actual board intact. This will come in handy to start next # round of moves (backtracking) when forward path sees a dead end. # b_next = list(b) if c < C: for r in xrange(0, R): if not((r,c) in los) : #print "Q", c, "put on Board Position: (", r, ",", c,")" b_next = list(b) b_next = b_next + list(((r,c),)) if len(b_next) == R: print "Solution: ", b_next los_next = los + get_queens_line_of_sight((r,c), R,C) move_next_queen (c+1, b_next , R, C, los_next) #print "Backtrack to Queen:", c - 1 if len(sys.argv) == 2: #print "Board Size:", sys.argv[1] move_next_queen(0,[],int(sys.argv[1]), int(sys.argv[1]), []) else: print "Requires board size as a number"
apache-2.0
dcos/dcos-ui
plugins/services/src/js/reducers/serviceForm/MultiContainerScaling.ts
1138
import { SET } from "#SRC/js/constants/TransactionTypes"; import Transaction from "#SRC/js/structs/Transaction"; export function JSONReducer(state = null, { type, path, value }) { if (path == null) { return state; } const joinedPath = path.join("."); if (this.internalState == null) { this.internalState = { instances: 1, kind: "fixed", }; } if (type === SET && joinedPath === "instances") { this.internalState.instances = parseInt(value, 10) || 0; return this.internalState; } if (type === SET && joinedPath === "scaling.kind") { this.internalState.kind = value; if (this.internalState.instances == null) { return null; } return this.internalState; } return state; } export function JSONParser(state) { if (state.scaling == null) { return []; } const transactions = []; if (Number.isInteger(state.scaling.instances)) { transactions.push(new Transaction(["instances"], state.scaling.instances)); } if (state.scaling.kind) { transactions.push(new Transaction(["scaling", "kind"], state.scaling.kind)); } return transactions; }
apache-2.0
GrowMoi/moi-front-end
app/scripts/services/neuron-animate-service.js
2635
(function () { 'use strict'; angular .module('moi.services') .factory('NeuronAnimateService', NeuronAnimateService); function NeuronAnimateService($timeout) { var discoveredNeurons = []; var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend'; var counterAnimation = 4; var service = { setNeuronElement: setNeuronElement, callToAction: callToAction, stopCallToAction: false, neuronElementUnavailable: null, specialCallToAction: specialCallToAction }; return service; function setNeuronElement(element){ //add elements jquery of neurons with state DESCUBIERTA discoveredNeurons.push(element); } function callToAction(){ var limitGroup = 4; var totalNeuronsToAnimate = Math.floor(Math.random() * limitGroup); //animate a gropup neurons for (var i = 0; i <= totalNeuronsToAnimate; i ++) { var randomPosition = Math.floor(Math.random() * discoveredNeurons.length); var isTheLastItem = i === totalNeuronsToAnimate; addAnimateClass(randomPosition, isTheLastItem); } } function addAnimateClass(randomPosition, isTheLastItem) { var $neuronElement = discoveredNeurons[randomPosition]; var $neuronToAnimate = $neuronElement.find('img'); var cssClass = 'animated swing'; $neuronToAnimate.addClass(cssClass).one(animationEnd, function() { // Do somthing after animation $neuronToAnimate.removeClass(cssClass); if(isTheLastItem){ $timeout(function() { if(!service.stopCallToAction){ callToAction(); } }, 1500); } }); } function specialCallToAction(){ var $neuronElement = service.neuronElementUnavailable; var $neuronToAnimate = $neuronElement.find('img'); var $neuronTooltip = $neuronElement.find('tooltip'); var cssClass = 'animated tada'; $neuronTooltip.addClass('active'); $neuronToAnimate.addClass(cssClass).one(animationEnd, function() { $neuronToAnimate.removeClass(cssClass); $neuronTooltip.removeClass('active'); $timeout(function() { if(counterAnimation > 0){ specialCallToAction(); } }, 1000); counterAnimation --; }); if(counterAnimation === 1){ setNeuronElement($neuronToAnimate); service.callToAction(); } } } })();
apache-2.0
rlangbehn/rules
rules-components/rules-compiler-component/src/main/java/net/sourceforge/rules/compiler/RulesCompilerException.java
1837
/***************************************************************************** * $Id$ * * Copyright 2008, The Rules Framework Development Team, and individual * contributors as indicated by the @authors tag. See the copyright.txt * in the distribution for a full listing of individual contributors. * * 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 net.sourceforge.rules.compiler; /** * TODO * * @version $Revision$ $Date$ * @author <a href="mailto:rlangbehn@users.sourceforge.net">Rainer Langbehn</a> */ public class RulesCompilerException extends Exception { /** * Default serial version UID. */ private static final long serialVersionUID = 1L; /** * Constructs a new <code>RulesCompilerException</code> instance * with the specified detail message. * * @param message the detail message */ public RulesCompilerException(String message) { super(message); } /** * Constructs a new <code>RulesCompilerException</code> instance * with the specified detail message and cause. * * @param message the detail message * @param cause the cause */ public RulesCompilerException(String message, Throwable cause) { super(message, cause); } }
apache-2.0
GoogleCloudPlatform/bigquery-utils
tools/automatic_query_fixer/src/main/java/com/google/cloud/bigquery/utils/queryfixer/errors/TableNotFoundError.java
705
package com.google.cloud.bigquery.utils.queryfixer.errors; import com.google.cloud.bigquery.BigQueryException; import com.google.cloud.bigquery.utils.queryfixer.entity.Position; import lombok.Getter; /** * A class to represent the "Table Not Found" errors from BigQuery. The errors are presented in this * form: "Not found: Table [TableName] was not found", where [TableName] is the incorrect table * name. */ @Getter public class TableNotFoundError extends BigQuerySemanticError { private final String tableName; public TableNotFoundError(String tableName, Position errorPosition, BigQueryException errorSource) { super(errorPosition, errorSource); this.tableName = tableName; } }
apache-2.0
ronq/geomesa
geomesa-arrow/geomesa-arrow-jts/src/main/java/org/locationtech/geomesa/arrow/vector/PolygonFloatVector.java
2890
/*********************************************************************** * Copyright (c) 2013-2017 Commonwealth Computer Research, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at * http://www.opensource.org/licenses/apache2.0.php. ***********************************************************************/ package org.locationtech.geomesa.arrow.vector; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.vector.NullableFloat4Vector; import org.apache.arrow.vector.ValueVector.Accessor; import org.apache.arrow.vector.ValueVector.Mutator; import org.apache.arrow.vector.complex.AbstractContainerVector; import org.apache.arrow.vector.complex.ListVector; import org.apache.arrow.vector.types.pojo.Field; import org.locationtech.geomesa.arrow.vector.GeometryFields; import org.locationtech.geomesa.arrow.vector.impl.AbstractPolygonVector; import javax.annotation.Nullable; import java.util.List; import java.util.Map; public class PolygonFloatVector extends AbstractPolygonVector { // fields created by this vector public static final List<Field> fields = GeometryFields.XY_FLOAT_LIST_2; public PolygonFloatVector(String name, BufferAllocator allocator, @Nullable Map<String, String> metadata) { super(name, allocator, metadata); } public PolygonFloatVector(String name, AbstractContainerVector container, @Nullable Map<String, String> metadata) { super(name, container, metadata); } public PolygonFloatVector(ListVector vector) { super(vector); } @Override protected List<Field> getFields() { return fields; } @Override protected PolygonWriter createWriter(ListVector vector) { return new PolygonFloatWriter(vector); } @Override protected PolygonReader createReader(ListVector vector) { return new PolygonFloatReader(vector); } public static class PolygonFloatWriter extends PolygonWriter { private NullableFloat4Vector.Mutator mutator; public PolygonFloatWriter(ListVector vector) { super(vector); } @Override protected void setOrdinalMutator(Mutator mutator) { this.mutator = (NullableFloat4Vector.Mutator) mutator; } @Override protected void writeOrdinal(int index, double ordinal) { mutator.setSafe(index, (float) ordinal); } } public static class PolygonFloatReader extends PolygonReader { private NullableFloat4Vector.Accessor accessor; public PolygonFloatReader(ListVector vector) { super(vector); } @Override protected void setOrdinalAccessor(Accessor accessor) { this.accessor = (NullableFloat4Vector.Accessor) accessor; } @Override protected double readOrdinal(int index) { return accessor.get(index); } } }
apache-2.0
SoCe/SoCe
Server/thirdparty/hazelcast/hazelcast-3.3.3/code-samples/transactions/transaction-basics/src/main/java/TransactionalMember.java
1081
import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.TransactionalMap; import com.hazelcast.transaction.TransactionContext; import com.hazelcast.transaction.TransactionOptions; import java.util.concurrent.TimeUnit; public class TransactionalMember { public static void main(String[] args) throws Exception { HazelcastInstance hz = Hazelcast.newHazelcastInstance(); TransactionOptions txOptions = new TransactionOptions() .setTimeout(10, TimeUnit.SECONDS); TransactionContext txCxt = hz.newTransactionContext(txOptions); txCxt.beginTransaction(); TransactionalMap<String, String> map = txCxt.getMap("map"); try { map.put("1", "1"); Thread.sleep(TimeUnit.SECONDS.toMillis(20)); map.put("2", "2"); txCxt.commitTransaction(); } catch (RuntimeException t) { txCxt.rollbackTransaction(); throw t; } System.out.println("Finished"); System.exit(0); } }
apache-2.0
cruppstahl/SIMDCompressionAndIntersection
advancedbenchmarking/src/readflat.cpp
1361
#include <unistd.h> #include <fstream> #include <vector> #include "common.h" #include "util.h" #include "timer.h" #include "maropuparser.h" #include "codecfactory.h" using namespace SIMDCompressionLib; void printusage(char *prog) { cout << "Usage: " << prog << " <uncompressed postings in the flat format>" << endl; } int main(int argc, char **argv) { if (argc != 2) { printusage(argv[1]); return -1; } try { string postFileName = argv[1]; MaropuGapReader reader(postFileName); if (!reader.open()) { cout << " could not open " << postFileName << " for reading..." << endl; return -1; } off_t pos; uint32_t qty; uint32_t postId = 0; while (reader.readNextPosAndQty(pos, qty)) { cout << "id: " << postId << " qty: " << qty << "offset: " << pos << endl; postId++; if ((reader.getPos() - pos) != (qty + 1) * 4) { cerr << "Internal error: unpexected diff in offsets!" << endl; return -1; } } } catch (const exception &e) { cerr << "Run-time error: " << e.what() << endl; return -1; } catch (...) { cerr << "Unknown exception caught, terminating..." << endl; return -1; } return 0; }
apache-2.0
onyxbits/dummydroid
src/main/java/de/onyxbits/dummydroid/LoadForm.java
4191
package de.onyxbits.dummydroid; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileInputStream; import java.util.Arrays; import java.util.Properties; import javax.swing.JFileChooser; import javax.swing.JOptionPane; public class LoadForm extends AbstractForm implements ActionListener, DummyDroidProperties { /** * */ private static final long serialVersionUID = 1L; private JFileChooser fileChooser; private Properties properties; public LoadForm(NavigateAction forwardAction, NavigateAction backwardAction) { super(forwardAction, backwardAction); fileChooser = new JFileChooser(new File(System.getProperty("user.dir"))); fileChooser.setFileFilter(new BuildPropFilter()); properties = new Properties(); add(fileChooser); } @Override public void edit(FormData formData) { super.edit(formData); backwardAction.setEnabled(false); forwardAction.setEnabled(true); fileChooser.removeActionListener(this); fileChooser.addActionListener(this); } @Override public void commitForm() { String defWidth = "" + formData.getDeviceConfigurationProtoBuilder().getScreenWidth(); String defHeight = "" + formData.getDeviceConfigurationProtoBuilder().getScreenHeight(); String defDensity = "" + formData.getDeviceConfigurationProtoBuilder().getScreenDensity(); int sdkversion = Integer.parseInt(properties.getProperty("ro.build.version.sdk", "1")); int glesversion = Integer.parseInt(properties.getProperty("ro.opengles.version", "1")); int screendensity = Integer.parseInt(properties.getProperty("ro.sf.lcd_density", defDensity)); int width = Integer.parseInt(properties.getProperty(SCREENHEIGHT, defWidth)); int height = Integer.parseInt(properties.getProperty(SCREENWIDTH, defHeight)); formData.getAndroidBuildProtoBuilder() .setId(properties.getProperty("ro.build.fingerprint", "")) .setProduct(properties.getProperty("ro.product.board", "")) .setCarrier(properties.getProperty("ro.carrier", "")) .setBootloader(properties.getProperty("ro.bootloader", "")) .setClient(properties.getProperty("ro.com.google.clientidbase", "")) .setGoogleServices(sdkversion).setDevice(properties.getProperty("ro.product.device", "")) .setSdkVersion(sdkversion).setModel(properties.getProperty("ro.product.model", "")) .setManufacturer(properties.getProperty("ro.product.manufacturer", "")) .setBuildProduct(properties.getProperty("ro.product.name", "")) .setRadio(properties.getProperty("gsm.version.baseband", "")); formData.getDeviceConfigurationProtoBuilder().setGlEsVersion(glesversion) .setScreenDensity(screendensity).setScreenHeight(height).setScreenWidth(width); formData.getAndroidCheckinRequestBuilder().setLocale( properties.getProperty("ro.product.locale.language", "") + "_" + properties.getProperty("ro.product.locale.region", "")); if (properties.get(FEATURES) != null) { formData .getDeviceConfigurationProtoBuilder() .clearSystemAvailableFeature() .addAllSystemAvailableFeature( Arrays.asList(properties.getProperty(FEATURES, "").trim().split(", *"))); } if (properties.get(LIBRARIES) != null) { formData .getDeviceConfigurationProtoBuilder() .clearSystemSharedLibrary() .addAllSystemSharedLibrary( Arrays.asList(properties.getProperty(LIBRARIES, "").trim().split(", *"))); } if (properties.get(PLATFORMS) != null) { formData .getDeviceConfigurationProtoBuilder() .clearNativePlatform() .addAllNativePlatform( Arrays.asList(properties.getProperty(PLATFORMS, "").trim().split(", *"))); } } public void actionPerformed(ActionEvent action) { if (action.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) { try { properties.load(new FileInputStream(fileChooser.getSelectedFile())); forwardAction.actionPerformed(null); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error parsing file"); } } if (action.getActionCommand().equals(JFileChooser.CANCEL_SELECTION)) { properties = new Properties(); fileChooser.setSelectedFile(new File(System.getProperty("user.dir"))); } } }
apache-2.0
IharYakimush/EntLibLight
Blocks/SemanticLogging/Src/SemanticLogging/Sinks/TallyKeepingFileStreamWriter.cs
7153
#region license // ============================================================================== // Microsoft patterns & practices Enterprise Library // Semantic Logging Application Block // ============================================================================== // Copyright © Microsoft Corporation. All rights reserved. Modifications copyright © 2017 Ihar Yakimush // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. // ============================================================================== #endregion using System.IO; using System.Text; namespace EntLibExtensions.SemanticLogging.Sinks { /// <summary> /// Represents a file stream writer that keeps a tally of the length of the file. /// </summary> internal sealed class TallyKeepingFileStreamWriter : StreamWriter { private long tally; /// <summary> /// Initializes a new instance of the <see cref="TallyKeepingFileStreamWriter"/> class with a <see cref="FileStream"/>. /// </summary> /// <param name="stream">The <see cref="FileStream"/> to write to.</param> public TallyKeepingFileStreamWriter(FileStream stream) : base(stream) { this.tally = stream.Length; } /// <summary> /// Initializes a new instance of the <see cref="TallyKeepingFileStreamWriter"/> class with a <see cref="FileStream"/>. /// </summary> /// <param name="stream">The <see cref="FileStream"/> to write to.</param> /// <param name="encoding">The <see cref="Encoding"/> to use.</param> public TallyKeepingFileStreamWriter(FileStream stream, Encoding encoding) : base(stream, encoding) { this.tally = stream.Length; } /// <summary> /// Gets the tally of the length of the string. /// </summary> /// <value> /// The tally of the length of the string. /// </value> public long Tally { get { return this.tally; } } /// <summary> /// Writes a character to the stream. /// </summary> /// <param name="value">The character to write to the text stream. </param> /// <exception cref="T:System.ObjectDisposedException"><see cref="P:System.IO.StreamWriter.AutoFlush"></see> is true or the <see cref="T:System.IO.StreamWriter"></see> buffer is full, and current writer is closed. </exception> /// <exception cref="T:System.NotSupportedException"><see cref="P:System.IO.StreamWriter.AutoFlush"></see> is true or the <see cref="T:System.IO.StreamWriter"></see> buffer is full, and the contents of the buffer cannot be written to the underlying fixed size stream because the <see cref="T:System.IO.StreamWriter"></see> is at the end the stream. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception><filterpriority>1</filterpriority> public override void Write(char value) { base.Write(value); this.tally += Encoding.GetByteCount(new char[] { value }); } /// <summary> /// Writes a character array to the stream. /// </summary> /// <param name="buffer">A character array containing the data to write. If buffer is null, nothing is written. </param> /// <exception cref="T:System.ObjectDisposedException"><see cref="P:System.IO.StreamWriter.AutoFlush"></see> is true or the <see cref="T:System.IO.StreamWriter"></see> buffer is full, and current writer is closed. </exception> /// <exception cref="T:System.NotSupportedException"><see cref="P:System.IO.StreamWriter.AutoFlush"></see> is true or the <see cref="T:System.IO.StreamWriter"></see> buffer is full, and the contents of the buffer cannot be written to the underlying fixed size stream because the <see cref="T:System.IO.StreamWriter"></see> is at the end the stream. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception><filterpriority>1</filterpriority> public override void Write(char[] buffer) { base.Write(buffer); this.tally += Encoding.GetByteCount(buffer); } /// <summary> /// Writes the specified buffer to the stream. /// </summary> /// <param name="buffer">A character array containing the data to write.</param> /// <param name="index">The index into buffer at which to begin writing.</param> /// <param name="count">The number of characters to read from buffer.</param> /// <exception cref="T:System.IO.IOException">An I/O error occurs.</exception> /// <exception cref="T:System.ObjectDisposedException"><see cref="P:System.IO.StreamWriter.AutoFlush"></see> is true or the <see cref="T:System.IO.StreamWriter"></see> buffer is full, and current writer is closed. </exception> /// <exception cref="T:System.NotSupportedException"><see cref="P:System.IO.StreamWriter.AutoFlush"></see> is true or the <see cref="T:System.IO.StreamWriter"></see> buffer is full, and the contents of the buffer cannot be written to the underlying fixed size stream because the <see cref="T:System.IO.StreamWriter"></see> is at the end the stream. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException">index or count is negative. </exception> /// <exception cref="T:System.ArgumentException">The buffer length minus index is less than count. </exception> /// <exception cref="T:System.ArgumentNullException">buffer is null. </exception><filterpriority>1</filterpriority> public override void Write(char[] buffer, int index, int count) { base.Write(buffer, index, count); this.tally += Encoding.GetByteCount(buffer, index, count); } /// <summary> /// Writes a string to the stream. /// </summary> /// <param name="value">The string to write to the stream. If value is null, nothing is written. </param> /// <exception cref="T:System.ObjectDisposedException"><see cref="P:System.IO.StreamWriter.AutoFlush"></see> is true or the <see cref="T:System.IO.StreamWriter"></see> buffer is full, and current writer is closed. </exception> /// <exception cref="T:System.NotSupportedException"><see cref="P:System.IO.StreamWriter.AutoFlush"></see> is true or the <see cref="T:System.IO.StreamWriter"></see> buffer is full, and the contents of the buffer cannot be written to the underlying fixed size stream because the <see cref="T:System.IO.StreamWriter"></see> is at the end the stream. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception><filterpriority>1</filterpriority> public override void Write(string value) { base.Write(value); this.tally += Encoding.GetByteCount(value); } } }
apache-2.0
cloudiator/colosseum
app/dtos/HardwareDto.java
3643
/* * Copyright (c) 2014-2015 University of Ulm * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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 dtos; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.TypeLiteral; import java.util.List; import dtos.generic.RemoteDto; import dtos.validation.validators.IterableValidator; import dtos.validation.validators.ModelIdValidator; import dtos.validation.validators.NotNullOrEmptyValidator; import dtos.validation.validators.NotNullValidator; import models.Cloud; import models.CloudCredential; import models.HardwareOffer; import models.Location; import models.service.BaseModelService; import models.service.ModelService; public class HardwareDto extends RemoteDto { private String name; private Long cloud; private Long hardwareOffer; private Long location; private List<Long> cloudCredentials; public HardwareDto() { super(); } @Override public void validation() { super.validation(); validator(String.class).validate(name).withValidator(new NotNullOrEmptyValidator()); validator(Long.class).validate(cloud).withValidator(new NotNullValidator()) .withValidator(new ModelIdValidator<>(References.cloudService.get())); validator(Long.class).validate(hardwareOffer).withValidator(new NotNullValidator()) .withValidator(new ModelIdValidator<>(References.hardwareOfferService.get())); validator(Long.class).validate(location) .withValidator(new ModelIdValidator<>(References.locationService.get())); validator(new TypeLiteral<List<Long>>() { }).validate(cloudCredentials).withValidator(new IterableValidator<>( new ModelIdValidator<>(References.cloudCredentialService.get()))); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getCloud() { return cloud; } public void setCloud(Long cloud) { this.cloud = cloud; } public Long getHardwareOffer() { return hardwareOffer; } public void setHardwareOffer(Long hardwareOffer) { this.hardwareOffer = hardwareOffer; } public Long getLocation() { return location; } public void setLocation(Long location) { this.location = location; } public List<Long> getCloudCredentials() { return cloudCredentials; } public void setCloudCredentials(List<Long> cloudCredentials) { this.cloudCredentials = cloudCredentials; } public static class References { @Inject private static Provider<BaseModelService<Cloud>> cloudService; @Inject private static Provider<BaseModelService<HardwareOffer>> hardwareOfferService; @Inject private static Provider<ModelService<Location>> locationService; @Inject private static Provider<ModelService<CloudCredential>> cloudCredentialService; private References() { } } }
apache-2.0
Ehecatl-Software/erp-pyme
application/forms/Products.php
3162
<?php class Form_Products extends Zend_Dojo_Form { public $_selectOptions; public function init() { $this->_selectOptions=array( '1' => 'red', '2' => 'blue', '3' => 'gray' ); $this->setMethod('post'); $this->setAttribs(array( 'name' => 'masterform' )); $this->setDecorators(array( 'FormElements', array('TabContainer', array( 'id' => 'tabContainer', 'style' => 'width: 600px; height: 500px;', 'dijitParams' => array( 'tabPosition' => 'top' ), )), 'DijitForm', )); $toggleForm= new Zend_Dojo_Form_SubForm(); $toggleForm->setAttribs(array( 'name' => 'toggletab', 'legend' => 'Toggle Elements', )); $toggleForm->addElement( 'NumberSpinner', 'ns', array( 'value' => '7', 'label' => 'NumberSpinner', 'smallDelta' => 5, 'largeDelta' => 25, 'defaultTimeout' => 1000, 'timeoutChangeRate' => 100, 'min' => 9, 'max' => 1550, 'places' => 0, 'maxlength' => 20, ) ); $toggleForm->addElement( 'Button', 'dijitButton', array( 'label' => 'Button', ) ); $toggleForm->addElement( 'CheckBox', 'checkbox', array( 'label' => 'CheckBox', 'checkedValue' => 'foo', 'uncheckedValue' => 'bar', 'checked' => true, ) ); $selectForm= new Zend_Dojo_Form_SubForm(); $selectForm->setAttribs(array( 'name' => 'selecttab', 'legend' => 'Select Elements', )); $selectForm->addElement( 'FilteringSelect', 'filterselect', array( 'label' => 'FilteringSelect(select)', 'storeId' => 'productStore', 'storeType' => 'dojo.data.ItemFileReadStore', 'storeParams' => array('url' => 'getproducts'), 'dijitParams' => array('searchAttr' => 'descripcion'), ) ); $this->addSubForm($selectForm,'selectForm'); } /* public function init(){ $this->setMethod('post'); $form = new Zend_Dojo_Form_SubForm(); $form->setAttribs(array( 'name' => 'products', )); $form->addElement( 'FilteringSelect', 'filteringselectremote', array( 'label' => 'Producto: ', 'storeId' => 'productStore', 'storeType' => 'dojo.data.ItemFileReadStore', 'storeParams' => array('url' => '/compras/getproducts'), 'dijitParams' => array('searchAttr' => 'descripcion'), ) ); $this->addSubForm($form); }*/ }
apache-2.0
nesfit/NetfoxDetective
Misc/EntityFramework.MappingAPI/EntityFramework.MappingAPI.Test/CodeFirst/Domain/PageTranslations.cs
334
 namespace EntityFramework.MappingAPI.Test.CodeFirst.Domain { public class PageTranslations { public int PageId { get; set; } public virtual Page Page { get; set; } public string Language { get; set; } public string Title { get; set; } public string Content { get; set; } } }
apache-2.0
kameghamegha/harden_macos
test/integration/default/serverspec/hardening_spec.rb
1663
# # Cookbook Name:: harden_macos # Author:: Meg Cassidy (<meg@nuna.com>) # # Copyright:: 2016-2017, Nuna, 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. require 'spec_helper' describe 'harden_macos::default' do # Serverspec examples can be found at # http://serverspec.org/resource_types.html describe 'enable firewall' do describe command('defaults read /Library/Preferences/com.apple.alf globalstate') do its(:stdout) { should match /^1$/ } end describe 'enable firewall stealthmode' do describe command('/usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode') do its(:stdout) { should match /Stealth mode enabled/ } end end end describe 'Safari disable opening files after downloading' do describe command('defaults read /Users/vagrant/Library/Preferences/com.apple.Safari AutoOpenSafeDownloads') do its(:stdout) { should match /^0$/ } end end describe 'Disable Safari Spotlight Suggestions' do describe command('defaults read /Users/vagrant/Library/Preferences/com.apple.Safari UniversalSearchEnabled') do its(:stdout) { should match /^0$/ } end end end
apache-2.0
yyn1110/javaPlugin
pkg/project/core.go
21211
package project import ( "bufio" "fmt" "github.com/spf13/cobra" //"github.com/yyn1110/logs" "javaPlugin/pkg/db" "javaPlugin/pkg/logs" "os" "os/signal" "path/filepath" "runtime" "strings" "sync" "syscall" "time" ) const ( programName = "javaPlugin" version = "0.11" ) var ( dbNameTest string packageName string maxCore int outputPath string exclude string jdk string pomVersion string dbDriver string redisHost string redisPort string redisPassWord string useRedis bool ) type resources struct { daoConfigFile *os.File daoConfigWriter *bufio.Writer pomFile *os.File pomWriter *bufio.Writer } var ( g_resources *resources g_packageName string g_packageNamePath string g_modelPath string g_daoPath string g_dataSourcePath string g_myBatisPath string g_testPath string g_testExceptionPath string g_mainResourcesPath string g_testResourcesPath string g_upperDbName string g_excludeNames []string ) func InitConfig(cmd *cobra.Command) { cmd.Flags().BoolVarP(&useRedis, "useRedis", "r", false, "create redis config ") cmd.Flags().StringVar(&pomVersion, "version", "0.1", "pom version") cmd.Flags().StringVar(&dbDriver, "dbDriver", "c3p0", "c3p0 or druid") cmd.Flags().StringVar(&jdk, "jdk", "1.7", "jdk version") cmd.Flags().StringVar(&dbNameTest, "dbNameTest", "", "The empty DB name for unit test.") cmd.Flags().StringVar(&packageName, "packageName", "com.java.demo", "The package name of Java classes.") cmd.Flags().IntVar(&maxCore, "maxCore", 1, "The max core number. (0: Number of CPU - 1)") cmd.Flags().StringVar(&outputPath, "outputPath", "./", "The output file path.") cmd.Flags().StringVar(&exclude, "exclude", "open_app_log,health_report_stats_month,drug_question_stats_month,video_stats_month", "The exclude tables name.") cmd.Flags().StringVar(&redisHost, "redisHost", "127.0.0.1", "redis host") cmd.Flags().StringVar(&redisPort, "redisPort", "6379", "redis port") cmd.Flags().StringVar(&redisPassWord, "redisPassWord", "", "redis password") } type tableDefine struct { Field string Type string DBType string Null bool Key string Default string Extra string Comment string CharacterSetName string Schema string TableName string } type tableDefineString struct { DbFieldName string FieldName string MethodName string Type int TypeString string JDBCType string DbTypeString string Null string Key string Default string Extra string Comment string CharacterSetName string DBType string AutoIncrement bool TestValue string FieldLen int } type classDefine struct { HasPrefix bool ClassName string TableName string CamelCaseName string Fields map[string]*tableDefineString Names []string PrimaryKey *tableDefineString UnionKeys []*tableDefineString } func Run() { initEnviroment() var wg sync.WaitGroup go run(db.DbClient.Engine(), &wg) time.Sleep(time.Second) ch := make(chan os.Signal) signal.Notify(ch, syscall.SIGINT) finishChannel := make(chan bool) go wait(&wg, finishChannel) select { case <-ch: logs.Logger.Info("Canceled by user.") os.Exit(-1) case <-finishChannel: logs.Logger.Info("Convert finished successfully!") } } func initEnviroment() { logs.Logger.Info("%s version[%s]\r\nUsage: %s [OPTIONS]\r\n", programName, version, os.Args[0]) numcpu := runtime.NumCPU() currentcpu := runtime.GOMAXPROCS(0) cpu := 0 if maxCore > 0 && maxCore < numcpu-1 { cpu = maxCore } else { cpu = numcpu - 1 } if cpu > 1 && currentcpu != cpu { runtime.GOMAXPROCS(cpu) } g_upperDbName = strings.ToUpper(db.DbClient.DBName()) g_packageName = packageName + "." + db.DbClient.DBName() g_packageNamePath = strings.Replace(g_packageName, ".", string(filepath.Separator), -1) os.RemoveAll(filepath.Join(outputPath, "src")) var err error g_modelPath = filepath.Join(outputPath, "src", "main", "java", g_packageNamePath, "persistence", "model") if err = os.MkdirAll(g_modelPath, 0777); err != nil { logs.Logger.Error("Create folder", g_modelPath, "error:", err.Error()) os.Exit(-1) } g_daoPath = filepath.Join(outputPath, "src", "main", "java", g_packageNamePath, "persistence", "dao") if err = os.MkdirAll(g_daoPath, 0777); err != nil { logs.Logger.Error("Create folder", g_daoPath, "error:", err.Error()) os.Exit(-1) } g_dataSourcePath = filepath.Join(outputPath, "src", "main", "java", g_packageNamePath, "dataSource") if err = os.MkdirAll(g_dataSourcePath, 0777); err != nil { logs.Logger.Error("Create folder", g_dataSourcePath, "error:", err.Error()) os.Exit(-1) } g_myBatisPath = filepath.Join(outputPath, "src", "main", "resources", g_packageNamePath, "persistence", "sqlmap") if err = os.MkdirAll(g_myBatisPath, 0777); err != nil { logs.Logger.Error("Create folder", g_myBatisPath, "error:", err.Error()) os.Exit(-1) } //g_myBatisExtPath = filepath.Join(outputPath, "src", "main", "resources", g_packageNamePath, "persistence", "sqlmap", "ext") //if err = os.MkdirAll(g_myBatisExtPath, 0777); err != nil { // logger.Error("Create folder", g_myBatisExtPath, "error:", err.Error()) // os.Exit(-1) //} g_testPath = filepath.Join(outputPath, "src", "test", "java", g_packageNamePath) if err = os.MkdirAll(g_testPath, 0777); err != nil { logs.Logger.Error("Create folder", g_testPath, "error:", err.Error()) os.Exit(-1) } g_testExceptionPath = filepath.Join(outputPath, "src", "test", "java", g_packageNamePath, "exception") if err = os.MkdirAll(g_testExceptionPath, 0777); err != nil { logs.Logger.Error("Create folder", g_testExceptionPath, "error:", err.Error()) os.Exit(-1) } g_mainResourcesPath = filepath.Join(outputPath, "src", "main", "resources") if err = os.MkdirAll(g_mainResourcesPath, 0777); err != nil { logs.Logger.Error("Create folder", g_mainResourcesPath, "error:", err.Error()) os.Exit(-1) } g_testResourcesPath = filepath.Join(outputPath, "src", "test", "resources") if err = os.MkdirAll(g_testResourcesPath, 0777); err != nil { logs.Logger.Error("Create folder", g_testResourcesPath, "error:", err.Error()) os.Exit(-1) } excludeStrings := strings.Split(exclude, ",") for _, excludeString := range excludeStrings { g_excludeNames = append(g_excludeNames, excludeString) } } //////////////////////////////////////////////////// // Write files func writeFiles() { writeLog4j() writeConfigProperties() writeAbstractTest() writeConstants() if useRedis { writeRedisTest() } } func writeRedisTest() { var err error var file *os.File if file, err = os.Create(filepath.Join(g_testPath, "RedisTest.java")); err != nil { logs.Logger.Error("Create file", filepath.Join(g_testResourcesPath, "RedisTest.java"), ", error:", err.Error()) return } defer file.Close() bw := bufio.NewWriter(file) redis_content := strings.Replace(redis_test_class, "$(package)$", g_packageName, -1) bw.WriteString(redis_content) bw.Flush() } func writeLog4j() { var err error var file *os.File if file, err = os.Create(filepath.Join(g_testResourcesPath, "log4j.xml")); err != nil { logs.Logger.Error("Create file", filepath.Join(g_testResourcesPath, "log4j.xml"), ", error:", err.Error()) return } defer file.Close() bw := bufio.NewWriter(file) log4jxml := strings.Replace(log4jXML, "$(packageName)$", g_packageName, -1) bw.WriteString(log4jxml) bw.Flush() } func writeConfigProperties() { var err error var file *os.File if file, err = os.Create(filepath.Join(g_testResourcesPath, (db.DbClient.DBName())+"-db.properties")); err != nil { logs.Logger.Error("Create file", filepath.Join(g_testResourcesPath, (db.DbClient.DBName())+"-db.properties"), ", error:", err.Error()) return } defer file.Close() bw := bufio.NewWriter(file) mysql_properties := strings.Replace(ProPerties_Mysql, "$(dbAddr)$", db.DbClient.DBAddr(), -1) mysql_properties = strings.Replace(mysql_properties, "$(dbUser)$", db.DbClient.DBUser(), -1) mysql_properties = strings.Replace(mysql_properties, "$(dbPassword)$", db.DbClient.DBPassword(), -1) mysql_properties = strings.Replace(mysql_properties, "$(dbName)$", db.DbClient.DBName(), -1) bw.WriteString(mysql_properties) if useRedis { redis_properties := strings.Replace(Redis_Config, "$(redisHost)$", redisHost, -1) redis_properties = strings.Replace(redis_properties, "$(redisPort)$", redisPort, -1) redis_properties = strings.Replace(redis_properties, "$(redisPassWord)$", redisPassWord, -1) bw.WriteString(redis_properties) } bw.Flush() } func writeAbstractTest() { var err error var file *os.File if file, err = os.Create(filepath.Join(g_testPath, "AbstractTest.java")); err != nil { logs.Logger.Error("Create file", filepath.Join(g_testPath, "AbstractTest.java"), ", error:", err.Error()) return } defer file.Close() bw := bufio.NewWriter(file) bw.WriteString("package ") bw.WriteString(g_packageName) bw.WriteString(";\n") bw.WriteString(` import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * 描述:测试基类,所有的Dao测试类都必须继承此类 * @Transactional 引入事务控制 * @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true) 引入事务控制管理器 * AbstractTransactionalDataSourceSpringContextTests 继承事务测试基类,避免测试框架带来脏数据,取消事务控制时修改为false * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:`) bw.WriteString(db.DbClient.DBName()) bw.WriteString(`-daoConfig.xml"}) public abstract class AbstractTest { }`) bw.Flush() } func writeConstants() { var err error var file *os.File if file, err = os.Create(filepath.Join(g_daoPath, "DataSourceConstants.java")); err != nil { logs.Logger.Error("Create file", filepath.Join(g_daoPath, "DataSourceConstants.java"), ", error:", err.Error()) return } defer file.Close() bw := bufio.NewWriter(file) bw.WriteString(`package `) bw.WriteString(g_packageName) bw.WriteString(".persistence.dao;\n\n") bw.WriteString("public class DataSourceConstants {\n") bw.WriteString("\tpublic static final String DATASOURCE_R_") bw.WriteString(g_upperDbName) bw.WriteString(" = \"dataSource_R_") bw.WriteString(db.DbClient.DBName()) bw.WriteString("\";\n") bw.WriteString("\tpublic static final String DATASOURCE_W_") bw.WriteString(g_upperDbName) bw.WriteString(" = \"dataSource_W_") bw.WriteString(db.DbClient.DBName()) bw.WriteString("\";\n") bw.WriteString("}\n") bw.Flush() } //////////////////////////////////////////////////// // Resource files func (res *resources) init() { var err error if res.pomFile, err = os.Create(filepath.Join(outputPath, "pom.xml")); err != nil { logs.Logger.Error("Create pom file error %s", err.Error()) return } res.pomWriter = bufio.NewWriter(res.pomFile) pomxml := strings.Replace(POM_XML, "$(groupId)$", packageName, -1) pomxml = strings.Replace(pomxml, "$(artifactId)$", db.DbClient.DBName(), -1) pomxml = strings.Replace(pomxml, "$(name)$", db.DbClient.DBName()+"-persistence", -1) pomxml = strings.Replace(pomxml, "$(description)$", "description for this project", -1) pomxml = strings.Replace(pomxml, "$(jdk)$", jdk, -1) pomxml = strings.Replace(pomxml, "$(version)$", pomVersion, -1) jedis := ` <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.3</version> </dependency> ` if useRedis { pomxml = strings.Replace(pomxml, "$(redisDependency)$", jedis, -1) } else { pomxml = strings.Replace(pomxml, "$(redisDependency)$", "", -1) } res.pomWriter.WriteString(pomxml) if res.daoConfigFile, err = os.Create(filepath.Join(g_testResourcesPath, (db.DbClient.DBName())+"-daoConfig.xml")); err != nil { logs.Logger.Error("Create file", filepath.Join(g_testResourcesPath, (db.DbClient.DBName())+"-daoConfig.xml"), ", error:", err.Error()) return } res.daoConfigWriter = bufio.NewWriter(res.daoConfigFile) daoConfigXml := strings.Replace(daoConfigXML, "$(packageName)$", g_packageName, -1) daoConfigXml = strings.Replace(daoConfigXml, "$(classPath)$", strings.Replace(g_packageName, ".", "/", -1)+"/persistence/sqlmap/*.xml", -1) daoConfigXml = strings.Replace(daoConfigXml, "$(classPathExt)$", strings.Replace(g_packageName, ".", "/", -1)+"/persistence/sqlmap/ext/*.xml", -1) switch dbDriver { case "c3p0": daoConfigXml = strings.Replace(daoConfigXml, "$(driverExtR)$", c3p0_r, -1) daoConfigXml = strings.Replace(daoConfigXml, "$(driverExtW)$", c3p0_w, -1) daoConfigXml = strings.Replace(daoConfigXml, "$(init)$", "", -1) daoConfigXml = strings.Replace(daoConfigXml, "$(driver)$", "com.mchange.v2.c3p0.ComboPooledDataSource", -1) case "druid": daoConfigXml = strings.Replace(daoConfigXml, "$(driverExtR)$", druid_r, -1) daoConfigXml = strings.Replace(daoConfigXml, "$(driverExtW)$", druid_w, -1) daoConfigXml = strings.Replace(daoConfigXml, "$(init)$", `init-method="init"`, -1) daoConfigXml = strings.Replace(daoConfigXml, "$(driver)$", "com.alibaba.druid.pool.DruidDataSource", -1) } daoConfigXml = strings.Replace(daoConfigXml, "$(properties)$", db.DbClient.DBName()+"-db.properties", -1) daoConfigXml = strings.Replace(daoConfigXml, "$(dbName)$", db.DbClient.DBName(), -1) if useRedis { daoConfigXml = strings.Replace(daoConfigXml, "$(redisConfig)$", redis_config, -1) } else { daoConfigXml = strings.Replace(daoConfigXml, "$(redisConfig)$", "", -1) } res.daoConfigWriter.WriteString(daoConfigXml) } func (res *resources) writeLine(class *classDefine) { } func (res *resources) close() { //res.daoConfigWriter.WriteString("\n</beans>") res.daoConfigWriter.Flush() res.daoConfigFile.Close() res.pomWriter.Flush() res.pomFile.Close() } //////////////////////////////// // Test file func writeTestHeader(bw *bufio.Writer, class *classDefine) { bw.WriteString(`package ` + g_packageName + ";\n\n") bw.WriteString("import " + g_packageName + ".persistence.model." + class.ClassName + ";\n") bw.WriteString("import " + g_packageName + ".persistence.dao." + class.ClassName + "Dao;\n") header := packageName + "." + db.DbClient.DBName() + ".exception" bw.WriteString("import " + header + ".UnitTestException;\n") bw.WriteString("import org.slf4j.Logger;\n") bw.WriteString("import org.slf4j.LoggerFactory;\n") bw.WriteString("import org.junit.Test;\n") bw.WriteString("import javax.annotation.Resource;\n") bw.WriteString("import org.springframework.transaction.annotation.Transactional;\n\n") bw.WriteString("public class " + class.ClassName + "Test extends AbstractTest {\n") bw.WriteString("\tprivate static final Logger logger = LoggerFactory.getLogger(" + class.ClassName + ".class);\n") } func writeTestBody(bw *bufio.Writer, class *classDefine) { bw.WriteString("\t@Resource\n") bw.WriteString("\tprivate " + class.ClassName + "Dao dao;\n") // setObjVal function bw.WriteString("\n\tprivate void setObjVal(" + class.ClassName + " sObj) {\n") index := 0 keyType := "Integer" keyValue := "" var unionKeys []string for _, fieldName := range class.Names { field := class.Fields[fieldName] if field == class.PrimaryKey { if field.AutoIncrement { continue } keyType = field.TypeString } if field == class.PrimaryKey { keyValue = field.TestValue } bw.WriteString("\t\tsObj.set" + field.MethodName + "(" + field.TestValue + ");\n") index++ } for _, field := range class.UnionKeys { unionKeys = append(unionKeys, field.TestValue) } bw.WriteString("\t}\n\n") //add bw.WriteString("\t@Test\n\t@Transactional(rollbackFor=Exception.class)\n") // Test case bw.WriteString("\tpublic void testCase() throws UnitTestException {\n") new := fmt.Sprintf("\t\t%s objInsert = new %s();\n", class.ClassName, class.ClassName) //bw.WriteString(class.ClassName+" objInsert = new "+class.ClassName+"") //bw.WriteString(" objInsert = new ") bw.WriteString(new) bw.WriteString("\t\tsetObjVal(objInsert);\n\n") bw.WriteString("\t\tlogger.info(\"insert [") bw.WriteString(class.ClassName) bw.WriteString("]\");\n") bw.WriteString("\t\tdao.insert(objInsert);\n") if class.PrimaryKey != nil { if class.PrimaryKey.AutoIncrement { bw.WriteString("\t\tInteger key = objInsert.get") bw.WriteString(class.PrimaryKey.MethodName) bw.WriteString("();\n") bw.WriteString("\t\tif (key == null || key == 0) {\n") bw.WriteString("\t\t\tthrow new UnitTestException(\"") bw.WriteString(class.ClassName) bw.WriteString("Test\", \"test of insert is failed\");\n") bw.WriteString("\t\t}\n") bw.WriteString("\t\tlogger.info(\"\tinsert OK\");\n\n") bw.WriteString("\t\t") bw.WriteString(class.ClassName) bw.WriteString(" objSelect = dao.get") bw.WriteString(class.ClassName) bw.WriteString("ByKey(key);\n") bw.WriteString("\t\tif (objSelect == null) {\n") bw.WriteString("\t\t\tthrow new UnitTestException(\"") bw.WriteString(class.ClassName) bw.WriteString("Test\", \"test of select is failed\");\n") bw.WriteString("\t\t}\n") bw.WriteString("\t\tlogger.info(\"\tselect OK \"+objSelect.toString());\n\n") } else { bw.WriteString("\t\t") bw.WriteString(keyType) bw.WriteString(" key = ") bw.WriteString(keyValue) bw.WriteString(";\n") bw.WriteString("\t\t") bw.WriteString(class.ClassName) bw.WriteString(" objSelect = dao.get") bw.WriteString(class.ClassName) bw.WriteString("ByKey(key);\n") bw.WriteString("\t\tif (objSelect == null) {\n") bw.WriteString("\t\t\tdao.insert(objInsert);\n") bw.WriteString("\t\t\tlogger.info(\"\tinsert OK\");\n\n") bw.WriteString("\t\t\tobjSelect = dao.get") bw.WriteString(class.ClassName) bw.WriteString("ByKey(key);\n") bw.WriteString("\t\t\tif (objSelect == null) {\n") bw.WriteString("\t\t\tthrow new UnitTestException(\"") bw.WriteString(class.ClassName) bw.WriteString("Test\", \"test of select is failed\");\n") bw.WriteString("\t\t\t}\n") bw.WriteString("\t\t\tlogger.info(\"\tselect OK \"+objSelect.toString());\n\n") bw.WriteString("\t\t}\n") } bw.WriteString("\t\tjava.util.List<" + class.ClassName + "> list = dao.get" + class.ClassName + "s(objSelect);\n") bw.WriteString("\t\t") bw.WriteString(`if (list !=null){ logger.info(" selectAll OK "+list.toString()); }else{ throw new UnitTestException("EcuserWxUserinfoTest", "test of selectAll is failed"); }` + "\n\n") bw.WriteString("\t\tInteger res = dao.update(objSelect);\n") bw.WriteString("\t\tif (res == null || res == 0) {\n") bw.WriteString("\t\t\tthrow new UnitTestException(\"") bw.WriteString(class.ClassName) bw.WriteString("Test\", \"test of update is failed\");\n") bw.WriteString("\t\t}\n") bw.WriteString("\t\tlogger.info(\"\tupdate OK\");\n\n") bw.WriteString("\t\tInteger del = dao.delete(key);\n") bw.WriteString("\t\tif (del == null || del == 0) {\n") bw.WriteString("\t\t\tthrow new UnitTestException(\"") bw.WriteString(class.ClassName) bw.WriteString("Test\", \"test of delete is failed\");\n") bw.WriteString("\t\t}\n") bw.WriteString("\t\tlogger.info(\"\tdelete OK\");\n\n") } else if len(class.UnionKeys) > 0 { unionKeysString := strings.Join(unionKeys, ", ") bw.WriteString("\t\tlogger.info(\"\tinsert OK\");\n\n") bw.WriteString("\t\t") bw.WriteString(class.ClassName) bw.WriteString(" objSelect = dao.get") bw.WriteString(class.ClassName) bw.WriteString("ByKey(") bw.WriteString(unionKeysString) bw.WriteString(");\n") bw.WriteString("\t\tif (objSelect == null) {\n") bw.WriteString("\t\t\tthrow new UnitTestException(\"") bw.WriteString(class.ClassName) bw.WriteString("Test\", \"test of select is failed\");\n") bw.WriteString("\t\t}\n") bw.WriteString("\t\tlogger.info(\"\tselect OK \"+objSelect.toString());\n\n") bw.WriteString("\t\tInteger res = dao.update(objSelect);\n") bw.WriteString("\t\tif (res == null || res == 0) {\n") bw.WriteString("\t\t\tthrow new UnitTestException(\"") bw.WriteString(class.ClassName) bw.WriteString("Test\", \"test of update is failed\");\n") bw.WriteString("\t\t}\n") bw.WriteString("\t\tlogger.info(\"\tupdate OK\");\n\n") bw.WriteString("\t\tInteger del = dao.delete(") bw.WriteString(unionKeysString) bw.WriteString(");\n") bw.WriteString("\t\tif (del == null || del == 0) {\n") bw.WriteString("\t\t\tthrow new UnitTestException(\"") bw.WriteString(class.ClassName) bw.WriteString("Test\", \"test of delete is failed\");\n") bw.WriteString("\t\t}\n") bw.WriteString("\t\tlogger.info(\"\tdelete OK\");\n\n") } else { bw.WriteString("\t\tdao.insert(objInsert);\n") bw.WriteString("\t\tlogger.info(\"\tinsert OK\");\n\n") } bw.WriteString("\t}\n\n") } func writeTestTailer(bw *bufio.Writer) { bw.WriteString("}\n") }
apache-2.0
att-comdev/drydock
drydock_provisioner/objects/__init__.py
5170
# Copyright 2017 AT&T Intellectual Property. All other 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. """Object models for Drydock design and task data.""" import importlib from copy import deepcopy def register_all(): # NOTE(sh8121att) - Import all versioned objects so # they are available via RPC. Any new object definitions # need to be added here. importlib.import_module('drydock_provisioner.objects.network') importlib.import_module('drydock_provisioner.objects.node') importlib.import_module('drydock_provisioner.objects.hostprofile') importlib.import_module('drydock_provisioner.objects.hwprofile') importlib.import_module('drydock_provisioner.objects.site') importlib.import_module('drydock_provisioner.objects.promenade') importlib.import_module('drydock_provisioner.objects.rack') importlib.import_module('drydock_provisioner.objects.bootaction') importlib.import_module('drydock_provisioner.objects.task') importlib.import_module('drydock_provisioner.objects.builddata') importlib.import_module('drydock_provisioner.objects.validation') # Utility class for calculating inheritance class Utils(object): """ apply_field_inheritance - apply inheritance rules to a single field value param child_field - value of the child field, or the field receiving the inheritance param parent_field - value of the parent field, or the field supplying the inheritance return the correct value for child_field based on the inheritance algorithm Inheritance algorithm 1. If child_field is not None, '!' for string vals or -1 for numeric vals retain the value of child_field 2. If child_field is '!' return None to unset the field value 3. If child_field is -1 return None to unset the field value 4. If child_field is None return parent_field """ @staticmethod def apply_field_inheritance(child_field, parent_field): if child_field is not None: if child_field != '!' and child_field != -1: return child_field else: return None else: return parent_field """ merge_lists - apply inheritance rules to a list of simple values param child_list - list of values from the child param parent_list - list of values from the parent return a merged list with child values taking prority 1. All members in the child list not starting with '!' 2. If a member in the parent list has a corresponding member in the chid list prefixed with '!' it is removed 3. All remaining members of the parent list """ @staticmethod def merge_lists(child_list, parent_list): if child_list is None: return parent_list if parent_list is None: return child_list effective_list = [] try: # Probably should handle non-string values effective_list.extend( filter(lambda x: not x.startswith("!"), child_list)) effective_list.extend( filter(lambda x: ("!" + x) not in child_list, filter(lambda x: x not in effective_list, parent_list))) except TypeError: raise TypeError("Error iterating list argument") return effective_list """ merge_dicts - apply inheritance rules to a dict param child_dict - dict of k:v from child param parent_dict - dict of k:v from the parent return a merged dict with child values taking prority 1. All members in the child dict with a key not starting with '!' 2. If a member in the parent dict has a corresponding member in the chid dict where the key is prefixed with '!' it is removed 3. All remaining members of the parent dict """ @staticmethod def merge_dicts(child_dict, parent_dict): if child_dict is None: return parent_dict if parent_dict is None: return child_dict effective_dict = {} try: # Probably should handle non-string keys use_keys = filter(lambda x: ("!" + x) not in child_dict.keys(), parent_dict) for k in use_keys: effective_dict[k] = deepcopy(parent_dict[k]) use_keys = filter(lambda x: not x.startswith("!"), child_dict) for k in use_keys: effective_dict[k] = deepcopy(child_dict[k]) except TypeError: raise TypeError("Error iterating dict argument") return effective_dict
apache-2.0
TonnyL/Espresso
app/src/main/java/io/github/marktony/espresso/mvp/companydetails/CompanyDetailContract.java
1158
/* * Copyright(c) 2017 lizhaotailang * * 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 io.github.marktony.espresso.mvp.companydetails; import java.util.List; import io.github.marktony.espresso.mvp.BasePresenter; import io.github.marktony.espresso.mvp.BaseView; /** * Created by lizhaotailang on 2017/2/10. */ public interface CompanyDetailContract { interface View extends BaseView<Presenter> { void setCompanyName(String name); void setCompanyTel(String tel); void setCompanyWebsite(String website); void showErrorMsg(); } interface Presenter extends BasePresenter { } }
apache-2.0
levymoreira/griffon
subprojects/griffon-core/src/main/java/org/codehaus/griffon/runtime/core/controller/ActionDecorator.java
2391
/* * Copyright 2008-2015 the original author or 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. */ package org.codehaus.griffon.runtime.core.controller; import griffon.core.artifact.GriffonController; import griffon.core.controller.Action; import griffon.core.controller.ActionManager; import javax.annotation.Nonnull; import javax.annotation.Nullable; import static java.util.Objects.requireNonNull; /** * @author Andres Almiray * @since 2.2.0 */ public class ActionDecorator implements Action { private final Action delegate; public ActionDecorator(@Nonnull Action delegate) { this.delegate = requireNonNull(delegate, "Argument 'delegate' must not be null"); } @Nonnull @Override public String getActionName() { return delegate.getActionName(); } @Nonnull @Override public String getFullyQualifiedName() { return delegate.getFullyQualifiedName(); } @Nullable @Override public String getName() { return delegate.getName(); } @Override public void setName(@Nullable String name) { delegate.setName(name); } @Override public boolean isEnabled() { return delegate.isEnabled(); } @Override public void setEnabled(boolean enabled) { delegate.setEnabled(enabled); } @Nonnull @Override public ActionManager getActionManager() { return delegate.getActionManager(); } @Nonnull @Override public GriffonController getController() { return delegate.getController(); } @Nonnull @Override public Object getToolkitAction() { return delegate.getToolkitAction(); } @Override public void execute(Object... args) { delegate.execute(args); } @Override public void initialize() { delegate.initialize(); } }
apache-2.0
triniwiz/nativescript-youtubeplayer
demo-ng/app/main.ts
178
import { platformNativeScriptDynamic } from 'nativescript-angular/platform'; import { AppModule } from './app.module'; platformNativeScriptDynamic().bootstrapModule(AppModule);
apache-2.0
imAArtist/simIr
Data/singleFile/code_605.cpp
850
public int longestConsecutive(int[] num) { int res = 0; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int n : num) { if (!map.containsKey(n)) { int left = (map.containsKey(n - 1)) ? map.get(n - 1) : 0; int right = (map.containsKey(n + 1)) ? map.get(n + 1) : 0; // sum: length of the sequence n is in int sum = left + right + 1; map.put(n, sum); // keep track of the max length res = Math.max(res, sum); // extend the length to the boundary(s) // of the sequence // will do nothing if n has no neighbors map.put(n - left, sum); map.put(n + right, sum); } else { // duplicates continue; } } return res; }
artistic-2.0
tcolar/javaontracks
src/net/jot/web/widget/builtin/JOTTextBoxWidget.java
592
/* * JavaOnTrack/Jotwiki * Thibaut Colar. * tcolar-jot AT colar DOT net */ package net.jot.web.widget.builtin; import net.jot.web.widget.JOTWidgetBaseProperties; import net.jot.web.widget.JOTWidgetNoAjaxBase; /** * Smple text widget * @author thibautc */ public abstract class JOTTextBoxWidget extends JOTWidgetNoAjaxBase { // can ovveride in subclass: either: hidden, scroll, auto, visible public String overflow="hidden"; public void customizeProperties() { properties.updatePropertyDefaultValue(JOTWidgetBaseProperties.PROP_BG_COLOR, ""); } }
artistic-2.0
jpahle/jCell
src/jCell/Modulo5StateTable.java
1411
package jCell; import jCell.*; import java.awt.*; import java.io.*; /** * Diese StateTable beschreibt die Zustaende des Zellularautomaten Modulo5. * * @version 0.9, 6/29/1999 * @author Juergen Pahle */ public class Modulo5StateTable implements StateTable, Serializable { /** * Diese Methode gibt Farben fuer die graph. Ausgabe zurueck, die Zustaenden * zugeordnet sind. */ public Color getColor(int i) { if (i == 0) { return (Color.black); } else if (i == 1) { return (Color.yellow); } else if (i == 2) { return (Color.green); } else if (i == 3) { return (Color.blue); } else if (i == 4) { return (Color.red); } else return null; } /** * Diese Methode gibt Namen fuer das Popup-Menu zurueck, die den Zustaenden * zugeordnet sind. */ public String getName(int i) { if (i == 0) { return ("schwarz"); } else if (i == 1) { return ("gelb"); } else if (i == 2) { return ("gruen"); } else if (i == 3) { return ("blau"); } else if (i == 4) { return ("rot"); } else return null; } /** * Diese Methode gibt die Anzahl der Zustaende zurueck. */ public int getNumberStates () { return 5; } /** * Diese Methode setzt ein Element der Relation zwischen Zustaenden, Namen und Farben. */ public void setState(int i, String name, Color color) {} }
artistic-2.0
lsilbers/codepathTwitterFragments
app/src/main/java/com/lsilbers/apps/twitternator/models/User.java
3736
package com.lsilbers.apps.twitternator.models; import android.os.Parcel; import android.os.Parcelable; import com.activeandroid.Model; import com.activeandroid.annotation.Column; import com.activeandroid.annotation.Table; import com.activeandroid.query.Delete; import org.json.JSONException; import org.json.JSONObject; @Table(name = "Users") public class User extends Model implements Parcelable { // "name": "OAuth Dancer", @Column(name = "name") private String name; // "profile_image_url": "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg", @Column(name = "profile_image_url") private String profileImageUrl; // "id_str": "119476949", @Column(name = "id_str") private String idStr; // "followers_count": 28, @Column(name = "followers_count") private int followersCount; // "description": "", @Column(name = "tagline") private String tagline; // "friends_count": 14, @Column(name = "followings_count") private int followingsCount; // "screen_name": "oauth_dancer" @Column(name = "screen_name") private String screenName; public String getName() { return name; } public String getProfileImageUrl() { return profileImageUrl; } public String getIdStr() { return idStr; } public String getScreenName() { return screenName; } public int getFollowersCount() { return followersCount; } public String getTagline() { return tagline; } public int getFollowingsCount() { return followingsCount; } public User(){ super(); } @Override public String toString() { return "user:{"+name+","+screenName+","+idStr+","+profileImageUrl+", "+followersCount+", "+tagline+", "+ followingsCount +"}"; } public static User fromJSON(JSONObject jsonObject) { User user = new User(); try { user.name = jsonObject.getString("name"); user.idStr = jsonObject.getString("id_str"); user.profileImageUrl = jsonObject.getString("profile_image_url"); user.screenName = jsonObject.getString("screen_name"); user.followingsCount = jsonObject.getInt("friends_count"); user.followersCount = jsonObject.getInt("followers_count"); user.tagline = jsonObject.getString("description"); } catch (JSONException e) { e.printStackTrace(); } user.save(); return user; } public static void clearSavedUsers(){ new Delete().from(User.class).execute(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.name); dest.writeString(this.profileImageUrl); dest.writeString(this.idStr); dest.writeInt(this.followersCount); dest.writeString(this.tagline); dest.writeInt(this.followingsCount); dest.writeString(this.screenName); } protected User(Parcel in) { this.name = in.readString(); this.profileImageUrl = in.readString(); this.idStr = in.readString(); this.followersCount = in.readInt(); this.tagline = in.readString(); this.followingsCount = in.readInt(); this.screenName = in.readString(); } public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { public User createFromParcel(Parcel source) { return new User(source); } public User[] newArray(int size) { return new User[size]; } }; }
artistic-2.0
bcl-io/hmDNA
gatk-tools-java/src/main/java/com/google/cloud/genomics/gatk/htsjdk/GA4GHSamRecordIterator.java
6055
/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.google.cloud.genomics.gatk.htsjdk; import com.google.cloud.genomics.gatk.common.GenomicsApiDataSource; import com.google.cloud.genomics.gatk.common.ReadIteratorResource; import com.google.common.base.Stopwatch; import htsjdk.samtools.SAMFileHeader; import htsjdk.samtools.SAMFileHeader.SortOrder; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SAMRecordIterator; import java.util.concurrent.TimeUnit; import java.util.Iterator; import java.util.logging.Logger; /** * Wraps iterators provided from Genomics API and implements * HTSJDK's SAMRecordIterator. * Iterates over data returned from the API and when needed * re-queries the API for more data. * Since the API always return *overlapping* reads and SAMRecordIterator * supports contained and start-at queries, this class filters reads * returned from the API to make sure they conform to the requested intervals. */ public class GA4GHSamRecordIterator implements SAMRecordIterator{ private static final Logger LOG = Logger.getLogger(GA4GHSamRecordIterator.class.getName()); private static final long STATS_DUMP_INTERVAL_READS = 100000; Iterator<SAMRecord> iterator; GenomicsApiDataSource dataSource; GA4GHQueryInterval[] intervals; String readSetId; int intervalIndex = -1; boolean hasNext; SAMRecord nextRead; SAMFileHeader header; long processedReads; Stopwatch timer; public GA4GHSamRecordIterator(GenomicsApiDataSource dataSource, String readSetId, GA4GHQueryInterval[] intervals) { this.dataSource = dataSource; this.readSetId = readSetId; this.intervals = intervals; this.timer = Stopwatch.createUnstarted(); seekMatchingRead(); } /** Returns true when we truly reached the end of all requested data */ boolean isAtEnd() { return intervals == null || intervals.length == 0 || intervalIndex >= intervals.length; } /** Returns the current interval being processed or null if we have reached the end */ GA4GHQueryInterval currentInterval() { if (isAtEnd()) { return null; } return intervals[intervalIndex]; } /** Re-queries the API for the next interval */ ReadIteratorResource queryNextInterval() { Stopwatch w = Stopwatch.createStarted(); if (!isAtEnd()) { intervalIndex++; } if (isAtEnd()) { return null; } ReadIteratorResource result = queryForInterval(currentInterval()); LOG.info("Interval query took: " + w); startTiming(); return result; } /** Queries the API for an interval and returns the iterator resource, or null if failed */ ReadIteratorResource queryForInterval(GA4GHQueryInterval interval) { try { return dataSource.getReadsFromGenomicsApi(readSetId, interval.getSequence(), interval.getStart(), interval.getEnd()); } catch (Exception ex) { LOG.warning("Error getting data for interval " + ex.toString()); } return null; } /** * Ensures next returned read will match the currently requested interval. * Since the API always returns overlapping reads we might need to skip some * reads if the interval asks for "included" or "starts at" types. * Also deals with the case of iterator being at an end and needing to query * for the next interval. */ void seekMatchingRead() { while (!isAtEnd()) { if (iterator == null || !iterator.hasNext()) { LOG.info("Getting " + (iterator == null ? "first" : "next") + "interval from the API"); // We have hit an end (or this is first time) so we need to go fish // to the API. ReadIteratorResource resource = queryNextInterval(); if (resource != null) { LOG.info("Got next interval from the API"); header = resource.getSAMFileHeader(); iterator = resource.getSAMRecordIterable().iterator(); } else { LOG.info("Failed to get next interval from the API"); header = null; iterator = null; } } else { nextRead = iterator.next(); if (currentInterval().matches(nextRead)) { return; // Happy case, otherwise we keep spinning in the loop. } else { LOG.info("Skipping non matching read"); } } } } @Override public void close() { this.iterator = null; this.dataSource = null; this.intervalIndex = intervals.length; } @Override public boolean hasNext() { return !isAtEnd(); } @Override public SAMRecord next() { SAMRecord retVal = nextRead; seekMatchingRead(); updateTiming(); return retVal; } @Override public void remove() { // Not implemented } @Override public SAMRecordIterator assertSorted(SortOrder sortOrder) { // TODO(iliat): implement this properly. This code never checks anything. return this; } public SAMFileHeader getFileHeader() { return header; } void startTiming() { processedReads = 0; timer.start(); } void updateTiming() { processedReads++; if ((processedReads % STATS_DUMP_INTERVAL_READS) == 0) { dumpTiming(); } } void stopTiming() { timer.stop(); } void dumpTiming() { if (processedReads == 0) { return; } LOG.info("Processed " + processedReads + " reads in " + timer + ". Speed: " + (processedReads*1000)/timer.elapsed(TimeUnit.MILLISECONDS) + " reads/sec"); } }
artistic-2.0
abuzarhamza/PostAScholarship
admin/_top.php
5961
<?php if( CheckAdminLogedIn() ) {?> <!--navigation panel--> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> </div> <!--close row--> </div> <!--close row--> <div row> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <div class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.php?page=home">PostAScholarship Admin Panel</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="./index.php?page=dashboard"><span class="glyphicon glyphicon-book"></span> Dashboard </a></li> <li><a href="./index.php?page=settings"><span class="glyphicon glyphicon-wrench"></span> Settings </a></li> <li><a href="./index.php?page=profile"><span class="glyphicon glyphicon-user"></span> Profile </a></li> </ul> <form class="navbar-form navbar-right" role="form" method="post" action="./admin_login.php?action=logout" name ="adminlogout" id="adminlogout"> <button type="submit" class="btn btn-primary" >Log out</button> </form> </div> <!--</div>--> </div> </div> </div> <?php if (array_key_exists('page', $_GET)) { $page = $_GET['page']; if ( $page == "settings" ) { ?> <!--Banner--> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-10 col-lg-10 col-md-offset-1 col-lg-offset-1"> <h1>Settings</h1> </div> </div> <!--Breadcrum--> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-10 col-lg-10 col-md-offset-1 col-lg-offset-1" > <ol class="breadcrumb"> <li><a href="./index.php?page=home">Home</a></li> <li class="active">Settings</li> </ol> </div> </div> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-4 col-lg-4 col-md-offset-1 col-lg-offset-1"> <div class="span2"> <p><a href="./manage_admin_details.php"><button class="btn btn-default btn-lg btn-block"><span class="glyphicon glyphicon-file"> </span> Manage admin detail</button></p> <p><a href="./change_admin_password.php"><button class="btn btn-default btn-lg btn-block"><span class="fa fa-key"></span> Change Password</button></a></p> </div> </div> </div> <? } elseif ( $page == "profile" ) { ?> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-10 col-lg-10 col-md-offset-1 col-lg-offset-1" > <h1>Profile</h1> </div> </div> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-10 col-lg-10 col-md-offset-1 col-lg-offset-1" > <ol class="breadcrumb"> <li><a href="./index.php?page=home">Home</a></li> <li class="active">Profile</li> </ol> </div> </div> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-4 col-lg-4 col-md-offset-1 col-lg-offset-1"> <div class="span2"> <p><a href="./profile_manager.php"><button class="btn btn-default btn-lg btn-block"><span class="glyphicon glyphicon-file"> </span> Update admin detail</button></p> </div> </div> </div> <? } elseif ( $page == "dashboard" ) { ?> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-10 col-lg-10 col-md-offset-1 col-lg-offset-1" > <h1>Dashboard</h1> </div> </div> <!--Breadcrum--> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-10 col-lg-10 col-md-offset-1 col-lg-offset-1" > <ol class="breadcrumb"> <li><a href="./index.php?page=home">Home</a></li> <li class="active">Dashboard</li> </ol> </div> </div> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-4 col-lg-4 col-md-offset-1 col-lg-offset-1"> <div class="span2"> <p><a href="./post.php"><button class="btn btn-default btn-lg btn-block"><span class="glyphicon glyphicon-file"> </span> Manage Post</button></p> <p><a href="./change_admin_password.php"><button class="btn btn-default btn-lg btn-block"><span class="glyphicon glyphicon-tags"></span> Manage Tags</button></a></p> <p><a href="./change_admin_password.php"><button class="btn btn-default btn-lg btn-block"><span class="glyphicon glyphicon-star-empty"></span> Manage Badge</button></a></p> <p><a href="./change_admin_password.php"><button class="btn btn-default btn-lg btn-block"><span class="glyphicon glyphicon-pushpin"></span> Manage SocialBookmarks</button></a></p> <p><a href="./change_admin_password.php"><button class="btn btn-default btn-lg btn-block"><span class="fa fa-users"></span> Manage User</button></a></p> <p><a href="./change_admin_password.php"><button class="btn btn-default btn-lg btn-block"><span class="fa fa-lock"></span> Manage admin</button></a></p> </div> </div> </div> <?php } elseif ( $page == "home" ) { ?> <div class="jumbotron"> <h1>Hello, Admin!</h1> <p>Check navigation button on the right top corner.To learn about the navigation panel check the learn more buttons </p> <p><a class="btn btn-primary btn-lg" role="button">Learn more</a></p> </div> <?php } } } ?>
artistic-2.0
smansooroutlook/MigrationTestv1
src/MVC/Models/AccountViewModels/SendCodeViewModel.cs
447
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; namespace MVC.Models.AccountViewModels { public class SendCodeViewModel { public string SelectedProvider { get; set; } public ICollection<SelectListItem> Providers { get; set; } public string ReturnUrl { get; set; } public bool RememberMe { get; set; } } }
artistic-2.0
BrainComputationLab/ncs
plugins/input/linear/include/Linear.hpp
3274
#include <ncs/sim/AtomicWriter.h> #include <ncs/sim/Memory.h> template<ncs::sim::DeviceType::Type MType, InputType IType> bool LinearSimulator<MType, IType>:: BatchStartsLater::operator()(const Batch* a, const Batch* b) const { return a->start_time > b->start_time; } template<ncs::sim::DeviceType::Type MType, InputType IType> bool LinearSimulator<MType, IType>:: addInputs(const std::vector<ncs::sim::Input*>& inputs, void* instantiator, float start_time, float end_time) { Instantiator* i = (Instantiator*)instantiator; auto starting_amplitude_generator = i->starting_amplitude; auto ending_amplitude_generator = i->ending_amplitude; std::vector<float> starting_amplitudes; std::vector<float> slopes; std::vector<unsigned int> device_neuron_ids; float duration = end_time - start_time; float one_over_duration = 1.0f / duration; for (auto input : inputs) { device_neuron_ids.push_back(input->neuron_device_id); ncs::spec::RNG rng(input->seed); float starting_amplitude = starting_amplitude_generator->generateDouble(&rng); starting_amplitudes.push_back(starting_amplitude); float ending_amplitude = ending_amplitude_generator->generateDouble(&rng); float slope = (ending_amplitude - starting_amplitude) * one_over_duration; slopes.push_back(slope); } Batch* batch = new Batch(); batch->count = starting_amplitudes.size(); batch->start_time = start_time; batch->end_time = end_time; bool result = true; result &= ncs::sim::mem::clone<MType>(batch->starting_amplitude, starting_amplitudes); result &= ncs::sim::mem::clone<MType>(batch->slope, slopes); result &= ncs::sim::mem::clone<MType>(batch->device_neuron_id, device_neuron_ids); if (!result) { delete batch; std::cerr << "Failed to allocate memory for input." << std::endl; return false; } future_batches_.push(batch); return true; } template<ncs::sim::DeviceType::Type MType, InputType IType> bool LinearSimulator<MType, IType>:: initialize(const ncs::spec::SimulationParameters* simulation_parameters) { return true; } template<ncs::sim::DeviceType::Type MType, InputType IType> bool LinearSimulator<MType, IType>:: update(ncs::sim::InputUpdateParameters* parameters) { const auto simulation_time = parameters->simulation_time; auto BatchIsDone = [simulation_time](Batch* b) { return b->end_time < simulation_time; }; for (auto batch : active_batches_) { if (BatchIsDone(batch)) { delete batch; } } active_batches_.remove_if(BatchIsDone); while (!future_batches_.empty() && future_batches_.top()->start_time <= simulation_time) { Batch* batch = future_batches_.top(); future_batches_.pop(); active_batches_.push_back(batch); } return update_(parameters); } template<ncs::sim::DeviceType::Type MType, InputType IType> LinearSimulator<MType, IType>::Batch::~Batch() { if (starting_amplitude) { ncs::sim::Memory<MType>::free(starting_amplitude); } if (slope) { ncs::sim::Memory<MType>::free(slope); } if (device_neuron_id) { ncs::sim::Memory<MType>::free(device_neuron_id); } }
bsd-2-clause
jwg4/gtools
tikumo/App.xaml.cs
552
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; using log4net; using System.Reflection; [assembly: log4net.Config.XmlConfigurator(Watch = true)] namespace tikumo { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); } }
bsd-2-clause
RealTimeGenomics/rtg-tools
test/com/rtg/variant/sv/bndeval/BndEvalCliTest.java
5511
/* * Copyright (c) 2018. Real Time Genomics Limited. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.rtg.variant.sv.bndeval; import java.io.File; import java.io.IOException; import com.rtg.tabix.TabixIndexer; import com.rtg.tabix.UnindexableDataException; import com.rtg.util.TestUtils; import com.rtg.util.io.TestDirectory; import com.rtg.util.test.FileHelper; import com.rtg.vcf.header.VcfHeader; import junit.framework.TestCase; public class BndEvalCliTest extends AbstractBndEvalTest { public void testInitParams() { checkHelp("bndeval [OPTION]... -b FILE -c FILE -o DIR" , "Evaluate" , "called variants" , "baseline variants" , "directory for output" , "-f,", "--vcf-score-field", "the name of the VCF FORMAT field to use as the ROC score" , "-O,", "--sort-order", "the order in which to sort the ROC scores" , "--no-gzip", "-Z,", "do not gzip the output" ); } public void testValidator() throws IOException, UnindexableDataException { try (TestDirectory dir = new TestDirectory("bndevalcli")) { final File out = new File(dir, "out"); final File calls = new File(dir, "calls"); final File mutations = new File(dir, "mutations"); final String[] flagStrings = { "-o", out.getPath() , "-c", calls.getPath() , "-b", mutations.getPath() }; TestUtils.containsAllUnwrapped(checkHandleFlagsErr(flagStrings), "--baseline file", "does not exist"); TestCase.assertTrue(mutations.createNewFile()); FileHelper.stringToGzFile(VcfHeader.MINIMAL_HEADER + "\tSAMPLE\n", mutations); new TabixIndexer(mutations).saveVcfIndex(); TestUtils.containsAllUnwrapped(checkHandleFlagsErr(flagStrings), "--calls file", "does not exist"); FileHelper.stringToGzFile(VcfHeader.MINIMAL_HEADER + "\tSAMPLE\n", calls); new TabixIndexer(calls).saveVcfIndex(); checkHandleFlags(flagStrings); TestCase.assertTrue(out.mkdir()); checkHandleFlagsErr(flagStrings); } } public void testNanoSmallDefault() throws IOException, UnindexableDataException { endToEnd("bndeval_small", "bndeval_small_default", new String[] {"summary.txt", "tp.vcf", "tp-baseline.vcf", "fp.vcf", "fn.vcf"}, false); } public void testNanoSmallTol() throws IOException, UnindexableDataException { endToEnd("bndeval_small_tol", "bndeval_small_tol", new String[] {"summary.txt", "tp.vcf", "tp-baseline.vcf", "fp.vcf", "fn.vcf"}, false, "--tolerance", "4"); } public void testNanoSmallAnnotate() throws IOException, UnindexableDataException { endToEnd("bndeval_small", "bndeval_small_annotate", new String[] {"summary.txt", "baseline.vcf", "calls.vcf"}, false, "--no-roc", "--output-mode", "annotate"); } public void testNanoSmallAll() throws IOException, UnindexableDataException { endToEnd("bndeval_small", "bndeval_small_all", new String[] {"summary.txt", "tp.vcf", "tp-baseline.vcf", "fp.vcf", "fn.vcf"}, false, "--vcf-score-field", "QUAL", "--all-records"); } public void testNanoSmallBidirectional() throws IOException, UnindexableDataException { endToEnd("bndeval_small_bidirectional", new String[] {"summary.txt", "tp.vcf", "tp-baseline.vcf", "fp.vcf", "fn.vcf"}, false, "--vcf-score-field", "QUAL", "--bidirectional"); } public void testNanoSmallBidirectionalAnnotate() throws IOException, UnindexableDataException { endToEnd("bndeval_small_bidirectional", "bndeval_small_bidirectional_annotate", new String[] {"summary.txt", "baseline.vcf", "calls.vcf"}, false, "--vcf-score-field", "QUAL", "--bidirectional", "--output-mode", "annotate"); } public void testNanoSmallBidirectional2() throws IOException, UnindexableDataException { endToEnd("bndeval_small_bidirectional2", new String[] {"summary.txt", "tp.vcf", "tp-baseline.vcf", "fp.vcf", "fn.vcf"}, false, "--vcf-score-field", "QUAL", "--bidirectional"); } public void testNanoSmallBidirectional3() throws IOException, UnindexableDataException { endToEnd("bndeval_small", "bndeval_small_bidirectional3", new String[] {"summary.txt", "tp.vcf", "tp-baseline.vcf", "fp.vcf", "fn.vcf"}, false, "--vcf-score-field", "QUAL", "--bidirectional"); } }
bsd-2-clause
frew/simpleproto
scons-local-1.1.0/SCons/Tool/wix.py
3462
"""SCons.Tool.wix Tool-specific initialization for wix, the Windows Installer XML Tool. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation # # 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. # __revision__ = "src/engine/SCons/Tool/wix.py 3603 2008/10/10 05:46:45 scons" import SCons.Builder import SCons.Action import os import string def generate(env): """Add Builders and construction variables for WiX to an Environment.""" if not exists(env): return env['WIXCANDLEFLAGS'] = ['-nologo'] env['WIXCANDLEINCLUDE'] = [] env['WIXCANDLECOM'] = '$WIXCANDLE $WIXCANDLEFLAGS -I $WIXCANDLEINCLUDE -o ${TARGET} ${SOURCE}' env['WIXLIGHTFLAGS'].append( '-nologo' ) env['WIXLIGHTCOM'] = "$WIXLIGHT $WIXLIGHTFLAGS -out ${TARGET} ${SOURCES}" object_builder = SCons.Builder.Builder( action = '$WIXCANDLECOM', suffix = '.wxiobj', src_suffix = '.wxs') linker_builder = SCons.Builder.Builder( action = '$WIXLIGHTCOM', src_suffix = '.wxiobj', src_builder = object_builder) env['BUILDERS']['WiX'] = linker_builder def exists(env): env['WIXCANDLE'] = 'candle.exe' env['WIXLIGHT'] = 'light.exe' # try to find the candle.exe and light.exe tools and # add the install directory to light libpath. #for path in os.environ['PATH'].split(os.pathsep): for path in string.split(os.environ['PATH'], os.pathsep): if not path: continue # workaround for some weird python win32 bug. if path[0] == '"' and path[-1:]=='"': path = path[1:-1] # normalize the path path = os.path.normpath(path) # search for the tools in the PATH environment variable try: if env['WIXCANDLE'] in os.listdir(path) and\ env['WIXLIGHT'] in os.listdir(path): env.PrependENVPath('PATH', path) env['WIXLIGHTFLAGS'] = [ os.path.join( path, 'wixui.wixlib' ), '-loc', os.path.join( path, 'WixUI_en-us.wxl' ) ] return 1 except OSError: pass # ignore this, could be a stale PATH entry. return None
bsd-2-clause
mrtryhard/mytryhard
src/MyTryHard/Bll/BaseContext.cs
1071
using Npgsql; using System.Data.Common; namespace MyTryHard.Bll { /// <summary> /// BaseContext is required for all additionnal context. /// Each context group features under a category; /// i.e. ArticlesContext regroups each operations appliable to Articles. /// </summary> public abstract class BaseContext { private readonly string _connStr; /// <summary> /// /// </summary> /// <param name="connStr">Connection string.</param> public BaseContext(string connStr) { _connStr = connStr; } /// <summary> /// Opens a new connection. /// Must be used within a using statement. /// /// Garantees same type of connection is used (here, NpgsqlConnection). /// </summary> /// <returns>DbConnection handle.</returns> protected DbConnection OpenConnection() { DbConnection conn = new NpgsqlConnection(_connStr); conn.Open(); return conn; } } }
bsd-2-clause
biokit/biokit
test/sequence/test_sequence.py
957
from biokit import Sequence, DNA def test(): s1 = Sequence('ACGT') s2 = Sequence('AAAA') s1 + s2 s2 + s1 s1+= s2 "aa" + s1 try: s1 += 2 assert False except: assert True s1.histogram() s1.pie() d1 = Sequence('GAGCCTACTAACGGGAT') d2 = Sequence('CATCGTAATGACGGCCT') #d1 = Sequence(d2) assert d1.hamming_distance(d2) == 7 d1.lower() assert d1.sequence == 'gagcctactaacgggat' d2.upper() d1._check_sequence() # __repr__ and __str__ print(d1) d1.__repr__() d1 = Sequence('AAAAa') # length greater than 10 print(d1) d1.__repr__() d1 = Sequence('ACGT') dna = DNA('ACGT') try: d1 += rna assert False except: assert True try: dna += d1 assert False except: assert True s = Sequence(DNA('ACGT')) assert s == 'ACGT' assert s == dna
bsd-2-clause
ggobbe/vivre-uo
Server/Persistence/StandardSaveStrategy.cs
7150
/*************************************************************************** * StandardSaveStrategy.cs * ------------------- * begin : May 1, 2002 * copyright : (C) The RunUO Software Team * email : info@runuo.com * * $Id: StandardSaveStrategy.cs 828 2012-02-11 04:36:54Z asayre $ * ***************************************************************************/ /*************************************************************************** * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * ***************************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Threading; using System.Diagnostics; using Server; using Server.Guilds; namespace Server { public class StandardSaveStrategy : SaveStrategy { public enum SaveOption { Normal, Threaded } public static SaveOption SaveType = SaveOption.Normal; public override string Name { get { return "Standard"; } } private Queue<Item> _decayQueue; private bool _permitBackgroundWrite; public StandardSaveStrategy() { _decayQueue = new Queue<Item>(); } protected bool PermitBackgroundWrite { get { return _permitBackgroundWrite; } set { _permitBackgroundWrite = value; } } protected bool UseSequentialWriters { get { return (StandardSaveStrategy.SaveType == SaveOption.Normal || !_permitBackgroundWrite); } } public override void Save(SaveMetrics metrics, bool permitBackgroundWrite) { _permitBackgroundWrite = permitBackgroundWrite; SaveMobiles(metrics); SaveItems(metrics); SaveGuilds(metrics); if (permitBackgroundWrite && UseSequentialWriters) //If we're permitted to write in the background, but we don't anyways, then notify. World.NotifyDiskWriteComplete(); } protected void SaveMobiles(SaveMetrics metrics) { Dictionary<Serial, Mobile> mobiles = World.Mobiles; GenericWriter idx; GenericWriter tdb; GenericWriter bin; if (UseSequentialWriters) { idx = new BinaryFileWriter(World.MobileIndexPath, false); tdb = new BinaryFileWriter(World.MobileTypesPath, false); bin = new BinaryFileWriter(World.MobileDataPath, true); } else { idx = new AsyncWriter(World.MobileIndexPath, false); tdb = new AsyncWriter(World.MobileTypesPath, false); bin = new AsyncWriter(World.MobileDataPath, true); } idx.Write((int)mobiles.Count); foreach (Mobile m in mobiles.Values) { long start = bin.Position; idx.Write((int)m.m_TypeRef); idx.Write((int)m.Serial); idx.Write((long)start); m.Serialize(bin); if (metrics != null) { metrics.OnMobileSaved((int)(bin.Position - start)); } idx.Write((int)(bin.Position - start)); m.FreeCache(); } tdb.Write((int)World.m_MobileTypes.Count); for (int i = 0; i < World.m_MobileTypes.Count; ++i) tdb.Write(World.m_MobileTypes[i].FullName); idx.Close(); tdb.Close(); bin.Close(); } protected void SaveItems(SaveMetrics metrics) { Dictionary<Serial, Item> items = World.Items; GenericWriter idx; GenericWriter tdb; GenericWriter bin; if (UseSequentialWriters) { idx = new BinaryFileWriter(World.ItemIndexPath, false); tdb = new BinaryFileWriter(World.ItemTypesPath, false); bin = new BinaryFileWriter(World.ItemDataPath, true); } else { idx = new AsyncWriter(World.ItemIndexPath, false); tdb = new AsyncWriter(World.ItemTypesPath, false); bin = new AsyncWriter(World.ItemDataPath, true); } idx.Write((int)items.Count); foreach (Item item in items.Values) { if (item.Decays && item.Parent == null && item.Map != Map.Internal && (item.LastMoved + item.DecayTime) <= DateTime.Now) { _decayQueue.Enqueue(item); } long start = bin.Position; idx.Write((int)item.m_TypeRef); idx.Write((int)item.Serial); idx.Write((long)start); item.Serialize(bin); if (metrics != null) { metrics.OnItemSaved((int)(bin.Position - start)); } idx.Write((int)(bin.Position - start)); item.FreeCache(); } tdb.Write((int)World.m_ItemTypes.Count); for (int i = 0; i < World.m_ItemTypes.Count; ++i) tdb.Write(World.m_ItemTypes[i].FullName); idx.Close(); tdb.Close(); bin.Close(); } protected void SaveGuilds(SaveMetrics metrics) { GenericWriter idx; GenericWriter bin; if (UseSequentialWriters) { idx = new BinaryFileWriter(World.GuildIndexPath, false); bin = new BinaryFileWriter(World.GuildDataPath, true); } else { idx = new AsyncWriter(World.GuildIndexPath, false); bin = new AsyncWriter(World.GuildDataPath, true); } idx.Write((int)BaseGuild.List.Count); foreach (BaseGuild guild in BaseGuild.List.Values) { long start = bin.Position; idx.Write((int)0);//guilds have no typeid idx.Write((int)guild.Id); idx.Write((long)start); guild.Serialize(bin); if (metrics != null) { metrics.OnGuildSaved((int)(bin.Position - start)); } idx.Write((int)(bin.Position - start)); } idx.Close(); bin.Close(); } public override void ProcessDecay() { while (_decayQueue.Count > 0) { Item item = _decayQueue.Dequeue(); if (item.OnDecay()) { item.Delete(); } } } } }
bsd-2-clause
UCSFMemoryAndAging/lava
lava-core/src/edu/ucsf/lava/core/action/model/Action.java
3113
package edu.ucsf.lava.core.action.model; import java.util.List; import java.util.Map; import edu.ucsf.lava.core.webflow.builder.FlowTypeBuilder; public interface Action { public boolean equals(Object action); public boolean equalsId(Object action); public Object clone(); public String getDescription(); public void setDescription(String description); public String getId(); public void setId(String id); public String getIdParamName(); public void setIdParamName(String idParamName); public String getModule(); public void setModule(String module); public String getInstance(); public void setInstance(String instance); public String getScope(); public void setScope(String scope); public String getSection(); public void setSection(String section); public String getTarget(); public void setTarget(String target); public Object getParam(Object key); public void setParam(Object key, Object value); public Map getParams(); public void setParams(Map params); public boolean recordInActionHistory(); public String getActionUrl(); public String getActionUrlWithIdParam(); public String getActionUrlWithModeParam(); public String getActionUrlWithParams(); public void setActionUrl(String actionUrl); public Long getPrecedenceLevel(); public void setPrecedenceLevel(Long precedenceLevel); public boolean getHomeDefault(); public void setHomeDefault(boolean homeDefault); public boolean getModuleDefault(); public void setModuleDefault(boolean moduleDefault); public boolean getSectionDefault(); public void setSectionDefault(boolean sectionDefault); public FlowTypeBuilder getFlowTypeBuilder(); public void setFlowTypeBuilder(FlowTypeBuilder flowTypeBuilder); public String getFlowType(); public String getDefaultFlowMode(); public void setParentFlow(String parentFlow); public void clearParentFlow(String parentFlow); public void clearParentFlows(); public List<String> getParentFlows(); public void setParentFlows(List<String> parentFlows); public void setSubFlow(String subFlow); public void clearSubFlow(String subFlow); public void clearSubFlows(); public List<String> getSubFlows(); public void setSubFlows(List<String> subFlows); public List<String> getCustomizingFlows(); public void setCustomizingFlows(List<String> customizingFlows); public void clearCustomizingFlow(String customizingFlow); public void clearCustomizingFlows(); public void setCustomizingFlow(String customizingFlow); public void setCustomizedFlow(String customizedFlow); public void clearCustomizedFlow(); public String getCustomizedFlow(); public void setViewBasePath(String viewBasePath); public String getViewBasePath(); public void setCustomizedViewBasePath(String customizedViewBasePath); public String getCustomizedViewBasePath(); public String getActionView(); public boolean isCustomizedInstanceAction(); public String makeCacheKey(String mode); public String makeCacheKey(); }
bsd-2-clause
renemilk/gitnotifs
src/gitnotifs/test/test_control.py
788
# -*- coding: utf-8 -*- """ Created on Tue Oct 2 14:49:16 2012 @author: r_milk01 """ import unittest import os from dune import supermodule from dune.control import ModuleMissing, Dunecontrol class TestControl(unittest.TestCase): def setUp(self): self.repo = supermodule.get_dune_stuff() def test_control(self): self.assertTrue(os.path.isdir(self.repo)) ctrl = Dunecontrol.from_basedir(self.repo) self.assertIn('dune-common', ctrl.dependencies('dune-stuff')['required']) with self.assertRaises(ModuleMissing): ctrl.dependencies('NONEXISTENT') ctrl.autogen('dune-common') ctrl.configure('dune-common') ctrl.make('dune-common') if __name__ == '__main__': unittest.main()
bsd-2-clause
okket/homebrew-cask
Casks/surge-synthesizer.rb
733
cask "surge-synthesizer" do version "1.8.0" sha256 "ceca8ad00bc41bbec9f379881e2b0ec3707f4a0fbeebc581d4202f6c1bb589a0" url "https://github.com/surge-synthesizer/releases/releases/download/#{version}/Surge-#{version}-Setup.dmg", verified: "github.com/surge-synthesizer/releases/" appcast "https://github.com/surge-synthesizer/releases/releases.atom" name "Surge" desc "Hybrid synthesizer" homepage "https://surge-synthesizer.github.io/" pkg "Surge-#{version}-Setup.pkg" uninstall pkgutil: [ "com.vemberaudio.vst2.pkg", "com.vemberaudio.vst3.pkg", "com.vemberaudio.au.pkg", "com.vemberaudio.resources.pkg", "org.surge-synthesizer.fxau.pkg", "org.surge-synthesizer.fxvst3.pkg", ] end
bsd-2-clause
m6w6/seekat
tests/bootstrap.php
6582
<?php require_once __DIR__."/../vendor/autoload.php"; function headers() : array { static $headers; if (!isset($headers)) { if (($token = getenv("GITHUB_TOKEN"))) { $headers["Authorization"] = "token $token"; } elseif (function_exists("posix_isatty") && defined("STDIN") && posix_isatty(STDIN)) { fprintf(STDOUT, "GITHUB_TOKEN is not set in the environment, enter Y to continue without: "); fflush(STDOUT); if (strncasecmp(fgets(STDIN), "Y", 1)) { exit; } $headers = []; } else { throw new Exception("GITHUB_TOKEN is not set in the environment"); } } return $headers; } function logger() : \Monolog\Logger { static $logger; if (!isset($logger)) { $logger = new \Monolog\Logger( "test", [ new \Monolog\Handler\FingersCrossedHandler( new \Monolog\Handler\StreamHandler(STDERR), \Monolog\Logger::EMERGENCY ) ] ); } return $logger; } class BaseTest extends \PHPUnit\Framework\TestCase { function provideAPI() { $auth = \seekat\API\auth("token", getenv("GITHUB_TOKEN")); $headers = headers(); $url = null; $client = null; $logger = logger(); return [ "using ReactPHP" => [new \seekat\API(\seekat\API\Future\react(), $headers, $url, $client, $logger)], "using AmPHP" => [new \seekat\API(\seekat\API\Future\amp(), $headers, $url, $client, $logger)], ]; } } trait ConsumePromise { function consumePromise($p, &$errors, &$results) { if (method_exists($p, "done")) { $p->then(function($result) use(&$results) { if (isset($result)) { $results[] = $result; } }, function($error) use (&$errors) { if (isset($error)) { $errors[] = $error; } }); } else { $p->onResolve(function($error, $result) use(&$errors, &$results) { if (isset($error)) { $errors[] = $error; } if (isset($result)) { $results[] = $result; } }); } } } trait AssertSuccess { function assertAllSuccess(array $apis, ...$args) { foreach ($apis as $api) { $this->consumePromise($api->get(...$args), $errors, $results); } $api->send(); $this->assertEmpty($errors, "errors"); $this->assertNotEmpty($results, "results"); return $results; } function assertSuccess(seekat\API $api, ...$args) { $this->consumePromise($api->get(...$args), $errors, $results); $api->send(); $this->assertEmpty($errors, "errors"); $this->assertNotEmpty($results, "results"); return $results[0]; } } trait AssertCancelled { function assertCancelled($promise) { $this->consumePromise($promise, $errors, $results); $this->assertEmpty($results); $this->assertStringMatchesFormat("%SCancelled%S", \seekat\Exception\message($errors[0])); } } trait AssertFailure { function assertFailure(seekat\API $api, ...$args) { $this->consumePromise($api->get(...$args), $errors, $results); $api->send(); $this->assertNotEmpty($errors, "errors"); $this->assertEmpty($results, "results"); return $errors[0]; } } class CombinedTestdoxPrinter extends PHPUnit\TextUI\DefaultResultPrinter { function isTestClass(PHPUnit\Framework\TestSuite $suite) { $suiteName = $suite->getName(); return false === strpos($suiteName, "::") && substr($suiteName, -4) === "Test"; } function startTestSuite(PHPUnit\Framework\TestSuite $suite) : void { if ($this->isTestClass($suite)) { $this->column = 0; } parent::startTestSuite($suite); } function endTestSuite(PHPUnit\Framework\TestSuite $suite) : void { /* print % progress */ if ($this->isTestClass($suite)) { if ($this->numTestsRun != $this->numTests) { $colWidth = $this->maxColumn - $this->column; $this->column = $this->maxColumn - 1; --$this->numTestsRun; $this->writeProgress(str_repeat(" ", $colWidth)); } else { $this->writeNewLine(); } } parent::endTestSuite($suite); } } class TestdoxListener implements PHPUnit\Framework\TestListener { private $groups; private $testdox; function __construct() { $this->testdox = new PHPUnit\Util\TestDox\TextResultPrinter("php://stdout", ["testdox"]); $this->groups = new ReflectionProperty("\PHPUnit\Util\TestDox\ResultPrinter", "groups"); $this->groups->setAccessible(true); } function startTest(PHPUnit\Framework\Test $test) : void { /* always show test class, even if no testdox test */ if ($test instanceof \PHPUnit\Framework\TestCase) { if ($test->getGroups() == ["default"]) { $this->groups->setValue($this->testdox, ["default"]); } } $this->testdox->startTest($test); $this->groups->setValue($this->testdox, ["testdox"]); } public function addError(\PHPUnit\Framework\Test $test, Throwable $t, float $time): void { $this->testdox->addError($test, $t, $time); } public function addWarning(\PHPUnit\Framework\Test $test, \PHPUnit\Framework\Warning $e, float $time): void { $this->testdox->addWarning($test, $e, $time); } public function addFailure(\PHPUnit\Framework\Test $test, \PHPUnit\Framework\AssertionFailedError $e, float $time): void { $this->testdox->addFailure($test, $e, $time); } public function addIncompleteTest(\PHPUnit\Framework\Test $test, Throwable $t, float $time): void { $this->testdox->addIncompleteTest($test, $t, $time); } public function addRiskyTest(\PHPUnit\Framework\Test $test, Throwable $t, float $time): void { $this->testdox->addRiskyTest($test, $t, $time); } public function addSkippedTest(\PHPUnit\Framework\Test $test, Throwable $t, float $time): void { $this->testdox->addSkippedTest($test, $t, $time); } public function startTestSuite(\PHPUnit\Framework\TestSuite $suite): void { $this->testdox->startTestSuite($suite); } public function endTestSuite(\PHPUnit\Framework\TestSuite $suite): void { $this->testdox->endTestSuite($suite); } public function endTest(\PHPUnit\Framework\Test $test, float $time): void { $this->testdox->endTest($test, $time); } } class DebugLogListener implements \PHPUnit\Framework\TestListener { use \PHPUnit\Framework\TestListenerDefaultImplementation; private $printLog = false; function endTest(PHPUnit\Framework\Test $test, float $time) : void { /* @var $handler \Monolog\Handler\FingersCrossedHandler */ $handler = logger()->getHandlers()[0]; if ($this->printLog) { $this->printLog = false; $handler->activate(); } else { $handler->clear(); } } function addError(PHPUnit\Framework\Test $test, \Throwable $e, float $time) : void { $this->printLog = true; } function addFailure(PHPUnit\Framework\Test $test, PHPUnit\Framework\AssertionFailedError $e, float $time) : void { $this->printLog = true; } }
bsd-2-clause
Pengcheng-Wang/IntelliMediaCore
Source/Unity/Utilities/UnityListBox.cs
3502
//--------------------------------------------------------------------------------------- // Copyright 2014 North Carolina State University // // Center for Educational Informatics // http://www.cei.ncsu.edu/ // // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //--------------------------------------------------------------------------------------- using UnityEngine; using System.Collections; using System.Collections.Generic; namespace IntelliMedia.Utilities { /// <summary> /// The purpose of this button is to wrap the Unity 3D button and properly handle mouse presses /// for buttons that overlap. /// http://forum.unity3d.com/threads/96563-corrected-GUI.Button-code-%28works-properly-with-layered-controls%29?p=629284#post629284 /// </summary> public class UnityListBox<T> { public Texture2D background; public GUIStyle titleStyle; public GUIStyle buttonStyle; public string Title { get; set; } public IEnumerable<T> Items { get; set; } public T SelectedValue { get; set; } private Vector2 scrollPos = new Vector2(0, 0); public void Draw(UnityEngine.Rect bounds) { if (background != null) { GUI.DrawTexture(bounds, background); } GUILayout.BeginArea(bounds); scrollPos = GUILayout.BeginScrollView(scrollPos); GUILayout.BeginVertical(); if (!string.IsNullOrEmpty(Title)) { GUILayout.Label(Title, titleStyle); GUILayout.Space(20); } foreach (T item in Items) { if (item != null) { if (GUILayout.Toggle((item.Equals(SelectedValue)), item.ToString(), buttonStyle, GUILayout.Height(buttonStyle.fontSize), GUILayout.Width(bounds.width))) { SelectedValue = item; } } } GUILayout.EndScrollView(); GUILayout.EndVertical(); GUILayout.EndArea(); } } }
bsd-2-clause
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Array/prototype/every/15.4.4.16-7-b-4.js
831
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-array.prototype.every es5id: 15.4.4.16-7-b-4 description: > Array.prototype.every - properties added into own object after current position are visited on an Array-like object ---*/ function callbackfn(val, idx, obj) { if (idx === 1 && val === 1) { return false; } else { return true; } } var arr = { length: 2 }; Object.defineProperty(arr, "0", { get: function() { Object.defineProperty(arr, "1", { get: function() { return 1; }, configurable: true }); return 0; }, configurable: true }); assert.sameValue(Array.prototype.every.call(arr, callbackfn), false, 'Array.prototype.every.call(arr, callbackfn)');
bsd-2-clause
jdubois/homebrew-core
Formula/points2grid.rb
1092
class Points2grid < Formula desc "Generate digital elevation models using local griding" homepage "https://github.com/CRREL/points2grid" url "https://github.com/CRREL/points2grid/archive/1.3.1.tar.gz" sha256 "6e2f2d3bbfd6f0f5c2d0c7d263cbd5453745a6fbe3113a3a2a630a997f4a1807" revision 3 bottle do cellar :any sha256 "03d183ed5be6f1ecffdd3439b0ef4287ed2bcdda29bfcd3d6305f2f2e93eb244" => :high_sierra sha256 "cb58d67da29769bf2481f60eb4668697699babb90ed18340a6fac217c6d3bd75" => :sierra sha256 "498339350edde2ace1538bf8f361ae8a81afb5e7563859687f6309326525db1b" => :el_capitan end depends_on "cmake" => :build depends_on "boost" depends_on "gdal" def install args = std_cmake_args + ["-DWITH_GDAL=ON"] libexec.install "test/data/example.las" system "cmake", ".", *args system "make", "install" end test do system bin/"points2grid", "-i", libexec/"example.las", "-o", "example", "--max", "--output_format", "grid" assert_equal 13, File.read("example.max.grid").scan("423.820000").size end end
bsd-2-clause
hubwub/homebrew-versions
Casks/android-studio-canary.rb
925
cask 'android-studio-canary' do version '2.2.0.5,145.3070098' sha256 'eb4e69345f0b2a103d085fe22b13df654748f04be5fe1fa93f017ad553639a1d' url "https://dl.google.com/dl/android/studio/ide-zips/#{version.before_comma}/android-studio-ide-#{version.after_comma}-mac.zip" name 'Android Studio Canary' homepage 'https://sites.google.com/a/android.com/tools/download/studio/canary' license :apache app 'Android Studio.app' zap delete: [ "~/Library/Preferences/AndroidStudio#{version.major_minor}", '~/Library/Preferences/com.google.android.studio.plist', "~/Library/Application Support/AndroidStudio#{version.major_minor}", "~/Library/Logs/AndroidStudio#{version.major_minor}", "~/Library/Caches/AndroidStudio#{version.major_minor}", ], rmdir: '~/AndroidStudioProjects' caveats do depends_on_java end end
bsd-2-clause
mgrimes/brew
Library/Homebrew/vendor/macho/macho.rb
1497
require "#{File.dirname(__FILE__)}/macho/structure" require "#{File.dirname(__FILE__)}/macho/view" require "#{File.dirname(__FILE__)}/macho/headers" require "#{File.dirname(__FILE__)}/macho/load_commands" require "#{File.dirname(__FILE__)}/macho/sections" require "#{File.dirname(__FILE__)}/macho/macho_file" require "#{File.dirname(__FILE__)}/macho/fat_file" require "#{File.dirname(__FILE__)}/macho/exceptions" require "#{File.dirname(__FILE__)}/macho/utils" require "#{File.dirname(__FILE__)}/macho/tools" # The primary namespace for ruby-macho. module MachO # release version VERSION = "1.2.0".freeze # Opens the given filename as a MachOFile or FatFile, depending on its magic. # @param filename [String] the file being opened # @return [MachOFile] if the file is a Mach-O # @return [FatFile] if the file is a Fat file # @raise [ArgumentError] if the given file does not exist # @raise [TruncatedFileError] if the file is too small to have a valid header # @raise [MagicError] if the file's magic is not valid Mach-O magic def self.open(filename) raise ArgumentError, "#{filename}: no such file" unless File.file?(filename) raise TruncatedFileError unless File.stat(filename).size >= 4 magic = File.open(filename, "rb") { |f| f.read(4) }.unpack("N").first if Utils.fat_magic?(magic) file = FatFile.new(filename) elsif Utils.magic?(magic) file = MachOFile.new(filename) else raise MagicError, magic end file end end
bsd-2-clause
passerbyid/homebrew-core
Formula/app-engine-go-64.rb
953
class AppEngineGo64 < Formula desc "Google App Engine SDK for Go (AMD64)" homepage "https://cloud.google.com/appengine/docs/go/" url "https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_darwin_amd64-1.9.54.zip" sha256 "5f15b985fa2de5d2b64cf34cabc08992eaf731ebf4f06a67c875f5c2a2b0c78a" bottle :unneeded conflicts_with "app-engine-go-32", :because => "both install the same binaries" conflicts_with "app-engine-python", :because => "both install the same binaries" def install pkgshare.install Dir["*"] %w[ api_server.py appcfg.py bulkloader.py bulkload_client.py dev_appserver.py download_appstats.py goapp ].each do |fn| bin.install_symlink pkgshare/fn end (pkgshare/"goroot/pkg").install_symlink pkgshare/"goroot/pkg/darwin_amd64_appengine" => "darwin_amd64" end test do assert_match(/^usage: goapp serve/, shell_output("#{bin}/goapp help serve").strip) end end
bsd-2-clause
ofavre/ReTouchPad
www/touchpad.js
3789
Touchpad = { Touch: function(touch) { this.id = touch.identifier; this.x = touch.screenX; this.y = touch.screenY; }, GestureManager: { restartEvents: true, gestures: [], registerGesture: function(gesture) { this.gestures.push(gesture); }, notify: function(dispatcher) { if (this.restartEvents) for (var i = 0 ; i < this.gestures.length ; i++) if (this.gestures[i].currentState == null) this.gestures[i].start(); for (var i = 0 ; i < this.gestures.length ; i++) this.gestures[i].notify(dispatcher); this.restartEvents = dispatcher.touches.count == 0; }, }, Gesture: function(name, setupCb) { this.name = name; this.states = {}; this.startState = null; this.currentState = null; this.fromState = null; this.toState = null; this.firedEvent = null; this.notify = function(dispatcher) { if (this.currentState) { var s = this.states[this.currentState]; var transitioned = false; for (var i = 0 ; i < s.links.length ; i++) { var e = s.links[i]; if (e.event.notify(dispatcher)) { console.log(this.name+" "+this.currentState+" -> "+e.toState); transitioned = true; this.transitionTo(e.toState, e.event); break; } } if (!transitioned) { console.log(this.name+" "+this.currentState+" -> (stopped)"); this.stop(); } } }; this.transitionTo = function(name, event) { event = event || Touchpad.TouchEventTypes.NULL; this.fromState = this.currentState; this.toState = (name && name in this.states) ? name : null; this.firedEvent = event; if (this.currentState) this.states[this.currentState].leave(); this.currentState = this.toState; if (this.currentState) this.states[this.currentState].enter(); }; this.start = function() { if (this.currentState != null) return; this.transitionTo(this.startState); }; this.stop = function() { if (this.currentState == null) return; this.transitionTo(null); }; this.reset = function() { this.stop(); this.start(); }; var setup = new (function(gesture) { function State(gesture,name) { this.gesture = gesture; this.name = name; this.links = []; this.forbidEvents = function(touchEvents) { for (var i = 0 ; i < touchEvents.length ; i++) this.links.push({event: touchEvents[i], toState: null}); }; this.addLink = function(touchEvent, toStateName) { this.links.push({event: touchEvent, toState: toStateName}); }; this.onEnter = undefined; this.onLeave = undefined; this.enter = function() { for (var i = 0 ; i < this.links.length ; i++) this.links[i].event.onStateEnter(); if (this.onEnter) this.onEnter(); }; this.leave = function() { if (this.onLeave) this.onLeave(); for (var i = 0 ; i < this.links.length ; i++) this.links[i].event.onStateLeave(); }; }; this.gesture = gesture; this.setStartState = function(name) { this.gesture.startState = name; }; this.addState = function(name) { if (this.gesture.states[name] != undefined) throw "State already defined!"; return this.gesture.states[name] = new State(this.gesture,name); }; this.setup = function(setupCb) { setupCb.call(this); Touchpad.GestureManager.registerGesture(this.gesture); }; })(this); setup.setup(setupCb); }, };
bsd-2-clause
HunanTV/fw
src/main/java/com/hunantv/fw/tests/FakeBrowser.java
1673
package com.hunantv.fw.tests; import java.util.HashMap; import java.util.Map; import com.hunantv.fw.exceptions.HttpException; import com.hunantv.fw.net.URLParser; import com.hunantv.fw.route.Routes; import com.hunantv.fw.view.View; /** * @TODO: 需要考虑put, delete */ public class FakeBrowser { FakeDispatcher dis = null; public FakeBrowser(Routes routes) { dis = new FakeDispatcher(); dis.setRoutes(routes); } public View get(String url) throws HttpException { return this.get(url, new HashMap<>(), null); } public View get(String url, Map<String, Object> params) throws HttpException { return this.get(url, params, null); } public View get(String url, Map<String, Object> params, Map<String, String> headers) throws HttpException { URLParser urlParser = new URLParser(url); urlParser.addQuery(params); FakeRequest req = new FakeRequest(); req.setURLParser(urlParser); req.setMethod("GET"); req.setParameter(urlParser.getQueryPair()); req.setHeaders(headers); return dis.doIt(url, req, null); } public View post(String url) throws HttpException { return this.post(url, new HashMap<>(), null); } public View post(String url, Map<String, Object> params) throws HttpException { return this.post(url, params, null); } public View post(String url, Map<String, Object> params, Map<String, String> headers) throws HttpException { URLParser urlParser = new URLParser(url); urlParser.addQuery(params); FakeRequest req = new FakeRequest(); req.setURLParser(urlParser); req.setMethod("POST"); req.setParameter(urlParser.getQueryPair()); req.setHeaders(headers); return dis.doIt(url, req, null); } }
bsd-2-clause
UCSFMemoryAndAging/lava
lava-core/src/edu/ucsf/lava/core/list/model/NumericRangeListConfig.java
4084
package edu.ucsf.lava.core.list.model; import java.util.ArrayList; import java.util.List; import edu.ucsf.lava.core.dao.LavaDaoFilter; import edu.ucsf.lava.core.dao.LavaDaoNamedParam; import edu.ucsf.lava.core.dao.LavaDaoParam; /** * This class supports numeric ranges based on a large numeric range list in the database. * This could be refactored to generate the list at runtime in java faster. * * @author jhesse * */ public class NumericRangeListConfig extends DefaultListConfig { public static String MIN_PARAM_NAME="min"; public static String MAX_PARAM_NAME="max"; private Long defaultMinValue = new Long(0); //if we end up not specifying any defaults we will get and empty list private Long defaultMaxValue = new Long(-1); public NumericRangeListConfig() { super(); this.defaultSort = SORT_VALUE_NUMERIC; } public Long getDefaultMaxValue() { return defaultMaxValue; } public void setDefaultMaxValue(Long defaultMaxValue) { this.defaultMaxValue = defaultMaxValue; } public Long getDefaultMinValue() { return defaultMinValue; } public void setDefaultMinValue(Long defaultMinValue) { this.defaultMinValue = defaultMinValue; } protected ListRequest onGetList(ListRequest request) { request = super.onGetList(request); List<LavaDaoParam> params = request.getParams(); LavaDaoFilter filter = LavaList.newFilterInstance(); //for new params boolean minFound = false; boolean maxFound = false; if(params != null){ //make sure min and max params are specified as Long for(LavaDaoParam param : params){ if(param.getType().equals(LavaDaoParam.TYPE_NAMED)){ LavaDaoNamedParam namedParam = (LavaDaoNamedParam)param; if(namedParam.getParamName().equalsIgnoreCase(MIN_PARAM_NAME)){ if(namedParam.getParamValue() instanceof String){ try{ minFound = true; namedParam.setParamValue(Long.valueOf((String)namedParam.getParamValue())); }catch(NumberFormatException nfe){ namedParam.setParamValue(defaultMinValue); //this should make the list blow up... } } }else if(namedParam.getParamName().equalsIgnoreCase(MAX_PARAM_NAME)){ if(namedParam.getParamValue() instanceof String){ try{ maxFound = true; namedParam.setParamValue(Long.valueOf((String)namedParam.getParamValue())); }catch(NumberFormatException nfe){ namedParam.setParamValue(defaultMaxValue); } } } } } } //use defaults if min and/or max not found if(!minFound){ request.addParam(filter.daoNamedParam(MIN_PARAM_NAME, defaultMinValue)); } if(!maxFound){ request.addParam(filter.daoNamedParam(MAX_PARAM_NAME, defaultMaxValue)); } return request; } /** * override the base class to generate the list in code rather than query the list table for a numeric series */ protected List<LabelValueBean> loadPrimaryQueryList(LavaDaoFilter filter) { Long minValue = null; Long maxValue = null; //get range for(LavaDaoParam param : filter.getDaoParams()){ if(param.getType().equals(LavaDaoParam.TYPE_NAMED)){ LavaDaoNamedParam namedParam = (LavaDaoNamedParam)param; if(namedParam.getParamName().equalsIgnoreCase(MIN_PARAM_NAME)){ minValue = (Long)namedParam.getParamValue(); }else if(namedParam.getParamName().equalsIgnoreCase(MAX_PARAM_NAME)){ maxValue = (Long)namedParam.getParamValue(); } } } //use defaults if min and/or max not found if(minValue==null){minValue=defaultMinValue;} if(maxValue==null){maxValue=defaultMaxValue;} int resultSize = maxValue.intValue() - minValue.intValue() + 1; List<LabelValueBean> results = new ArrayList<LabelValueBean>(resultSize < 0 ? 0 : resultSize); for(int i = minValue.intValue(); i <= maxValue.intValue();i++){ String value = Integer.toString(i); results.add(new LabelValueBean(value,value,Integer.valueOf(i))); } return results; } }
bsd-2-clause
makinacorpus/formhub
odk_viewer/tests/test_pandas_mongo_bridge.py
28658
import os import csv from django.utils.dateparse import parse_datetime from django.core.urlresolvers import reverse from tempfile import NamedTemporaryFile from odk_logger.models.xform import XForm from main.tests.test_base import MainTestCase from odk_logger.xform_instance_parser import xform_instance_to_dict from odk_viewer.pandas_mongo_bridge import * from common_tags import NA_REP def xls_filepath_from_fixture_name(fixture_name): """ Return an xls file path at tests/fixtures/[fixture]/fixture.xls """ #TODO: currently this only works for fixtures in this app because of __file__ return os.path.join( os.path.dirname(os.path.abspath(__file__)), "fixtures", fixture_name, fixture_name + ".xls" ) def xml_inst_filepath_from_fixture_name(fixture_name, instance_name): return os.path.join( os.path.dirname(os.path.abspath(__file__)), "fixtures", fixture_name, "instances", fixture_name + "_" + instance_name + ".xml" ) class TestPandasMongoBridge(MainTestCase): def setUp(self): self._create_user_and_login() self._submission_time=parse_datetime('2013-02-18 15:54:01Z') def _publish_xls_fixture_set_xform(self, fixture): """ Publish an xls file at tests/fixtures/[fixture]/fixture.xls """ xls_file_path = xls_filepath_from_fixture_name(fixture) count = XForm.objects.count() response = self._publish_xls_file(xls_file_path) self.assertEqual(XForm.objects.count(), count + 1) self.xform = XForm.objects.all().reverse()[0] def _submit_fixture_instance( self, fixture, instance, submission_time=None): """ Submit an instance at tests/fixtures/[fixture]/instances/[fixture]_[instance].xml """ xml_submission_file_path = xml_inst_filepath_from_fixture_name(fixture, instance) self._make_submission( xml_submission_file_path, forced_submission_time=submission_time) self.assertEqual(self.response.status_code, 201) def _publish_single_level_repeat_form(self): self._publish_xls_fixture_set_xform("new_repeats") self.survey_name = u"new_repeats" def _publish_nested_repeats_form(self): self._publish_xls_fixture_set_xform("nested_repeats") self.survey_name = u"nested_repeats" def _publish_grouped_gps_form(self): self._publish_xls_fixture_set_xform("grouped_gps") self.survey_name = u"grouped_gps" def _xls_data_for_dataframe(self): xls_df_builder = XLSDataFrameBuilder(self.user.username, self.xform.id_string) cursor = xls_df_builder._query_mongo() return xls_df_builder._format_for_dataframe(cursor) def _csv_data_for_dataframe(self): csv_df_builder = CSVDataFrameBuilder(self.user.username, self.xform.id_string) cursor = csv_df_builder._query_mongo() return csv_df_builder._format_for_dataframe(cursor) def test_generated_sections(self): self._publish_single_level_repeat_form() self._submit_fixture_instance("new_repeats", "01") xls_df_builder = XLSDataFrameBuilder(self.user.username, self.xform.id_string) expected_section_keys = [self.survey_name, u"kids_details"] section_keys = xls_df_builder.sections.keys() self.assertEqual(sorted(expected_section_keys), sorted(section_keys)) def test_row_counts(self): """ Test the number of rows in each sheet We expect a single row in the main new_repeats sheet and 2 rows in the kids details sheet one for each repeat """ self._publish_single_level_repeat_form() self._submit_fixture_instance("new_repeats", "01") data = self._xls_data_for_dataframe() self.assertEqual(len(data[self.survey_name]), 1) self.assertEqual(len(data[u"kids_details"]), 2) def test_xls_columns(self): """ Test that our expected columns are in the data """ self._publish_single_level_repeat_form() self._submit_fixture_instance("new_repeats", "01") data = self._xls_data_for_dataframe() # columns in the default sheet expected_default_columns = [ u"gps", u"_gps_latitude", u"_gps_longitude", u"_gps_altitude", u"_gps_precision", u"web_browsers/firefox", u"web_browsers/safari", u"web_browsers/ie", u"info/age", u"web_browsers/chrome", u"kids/has_kids", u"info/name", u"meta/instanceID" ] + AbstractDataFrameBuilder.ADDITIONAL_COLUMNS +\ XLSDataFrameBuilder.EXTRA_COLUMNS # get the header default_columns = [k for k in data[self.survey_name][0]] self.assertEqual(sorted(expected_default_columns), sorted(default_columns)) # columns in the kids_details sheet expected_kids_details_columns = [ u"kids/kids_details/kids_name", u"kids/kids_details/kids_age" ] + AbstractDataFrameBuilder.ADDITIONAL_COLUMNS +\ XLSDataFrameBuilder.EXTRA_COLUMNS kids_details_columns = [k for k in data[u"kids_details"][0]] self.assertEqual(sorted(expected_kids_details_columns), sorted(kids_details_columns)) def test_xls_columns_for_gps_within_groups(self): """ Test that a valid xpath is generated for extra gps fields that are NOT top level """ self._publish_grouped_gps_form() self._submit_fixture_instance("grouped_gps", "01") data = self._xls_data_for_dataframe() # columns in the default sheet expected_default_columns = [ u"gps_group/gps", u"gps_group/_gps_latitude", u"gps_group/_gps_longitude", u"gps_group/_gps_altitude", u"gps_group/_gps_precision", u"web_browsers/firefox", u"web_browsers/safari", u"web_browsers/ie", u"web_browsers/chrome", u"meta/instanceID" ] + AbstractDataFrameBuilder.ADDITIONAL_COLUMNS +\ XLSDataFrameBuilder.EXTRA_COLUMNS default_columns = [k for k in data[self.survey_name][0]] self.assertEqual(sorted(expected_default_columns), sorted(default_columns)) def test_xlsx_output_when_data_exceeds_limits(self): self._publish_xls_fixture_set_xform("xlsx_output") self._submit_fixture_instance("xlsx_output", "01") xls_builder = XLSDataFrameBuilder(username=self.user.username, id_string=self.xform.id_string) self.assertEqual(xls_builder.exceeds_xls_limits, True) # test that the view returns an xlsx file instead url = reverse('xls_export', kwargs={ 'username': self.user.username, 'id_string': self.xform.id_string }) self.response = self.client.get(url) self.assertEqual(self.response.status_code, 200) self.assertEqual(self.response["content-type"],\ 'application/vnd.openxmlformats') def test_xlsx_export_for_repeats(self): """ Make sure exports run fine when the xlsx file has multiple sheets """ self._publish_xls_fixture_set_xform("new_repeats") self._submit_fixture_instance("new_repeats", "01") xls_builder = XLSDataFrameBuilder(username=self.user.username, id_string=self.xform.id_string) # test that the view returns an xlsx file instead url = reverse('xls_export', kwargs={ 'username': self.user.username, 'id_string': self.xform.id_string } ) params = { 'xlsx': 'true' # force xlsx } self.response = self.client.get(url, params) self.assertEqual(self.response.status_code, 200) self.assertEqual(self.response["content-type"],\ 'application/vnd.openxmlformats') def test_csv_dataframe_export_to(self): self._publish_nested_repeats_form() self._submit_fixture_instance( "nested_repeats", "01", submission_time=self._submission_time) self._submit_fixture_instance( "nested_repeats", "02", submission_time=self._submission_time) csv_df_builder = CSVDataFrameBuilder(self.user.username, self.xform.id_string) temp_file = NamedTemporaryFile(suffix=".csv", delete=False) csv_df_builder.export_to(temp_file.name) csv_fixture_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "fixtures", "nested_repeats", "nested_repeats.csv" ) temp_file.close() fixture, output = '', '' with open(csv_fixture_path) as f: fixture = f.read() with open(temp_file.name) as f: output = f.read() os.unlink(temp_file.name) self.assertEqual(fixture, output) def test_csv_columns_for_gps_within_groups(self): self._publish_grouped_gps_form() self._submit_fixture_instance("grouped_gps", "01") data = self._csv_data_for_dataframe() columns = data[0].keys() expected_columns = [ u'gps_group/gps', u'gps_group/_gps_latitude', u'gps_group/_gps_longitude', u'gps_group/_gps_altitude', u'gps_group/_gps_precision', u'web_browsers/firefox', u'web_browsers/chrome', u'web_browsers/ie', u'web_browsers/safari', ] + AbstractDataFrameBuilder.ADDITIONAL_COLUMNS +\ AbstractDataFrameBuilder.IGNORED_COLUMNS self.maxDiff = None self.assertEqual(sorted(expected_columns), sorted(columns)) def test_format_mongo_data_for_csv(self): self.maxDiff = None self._publish_single_level_repeat_form() self._submit_fixture_instance("new_repeats", "01") dd = self.xform.data_dictionary() columns = dd.get_keys() data_0 = self._csv_data_for_dataframe()[0] # remove AbstractDataFrameBuilder.INTERNAL_FIELDS for key in AbstractDataFrameBuilder.IGNORED_COLUMNS: data_0.pop(key) for key in AbstractDataFrameBuilder.ADDITIONAL_COLUMNS: data_0.pop(key) expected_data_0 = { u'gps': u'-1.2627557 36.7926442 0.0 30.0', u'_gps_latitude': u'-1.2627557', u'_gps_longitude': u'36.7926442', u'_gps_altitude': u'0.0', u'_gps_precision': u'30.0', u'kids/has_kids': u'1', u'info/age': u'80', u'kids/kids_details[1]/kids_name': u'Abel', u'kids/kids_details[1]/kids_age': u'50', u'kids/kids_details[2]/kids_name': u'Cain', u'kids/kids_details[2]/kids_age': u'76', u'web_browsers/chrome': True, u'web_browsers/ie': True, u'web_browsers/safari': False, u'web_browsers/firefox': False, u'info/name': u'Adam', } self.assertEqual(expected_data_0, data_0) def test_split_select_multiples(self): self._publish_nested_repeats_form() dd = self.xform.data_dictionary() self._submit_fixture_instance("nested_repeats", "01") csv_df_builder = CSVDataFrameBuilder(self.user.username, self.xform.id_string) cursor = csv_df_builder._query_mongo() record = cursor[0] select_multiples = CSVDataFrameBuilder._collect_select_multiples(dd) result = CSVDataFrameBuilder._split_select_multiples(record, select_multiples) expected_result = { u'web_browsers/ie': True, u'web_browsers/safari': True, u'web_browsers/firefox': False, u'web_browsers/chrome': False } # build a new dictionary only composed of the keys we want to use in # the comparison result = dict([(key, result[key]) for key in result.keys() if key in \ expected_result.keys()]) self.assertEqual(expected_result, result) def test_split_select_multiples_within_repeats(self): self.maxDiff = None record = { 'name': 'Tom', 'age': 23, 'browser_use': [ { 'browser_use/year': '2010', 'browser_use/browsers': 'firefox safari' }, { 'browser_use/year': '2011', 'browser_use/browsers': 'firefox chrome' } ] } expected_result = { 'name': 'Tom', 'age': 23, 'browser_use': [ { 'browser_use/year': '2010', 'browser_use/browsers/firefox': True, 'browser_use/browsers/safari': True, 'browser_use/browsers/ie': False, 'browser_use/browsers/chrome': False }, { 'browser_use/year': '2011', 'browser_use/browsers/firefox': True, 'browser_use/browsers/safari': False, 'browser_use/browsers/ie': False, 'browser_use/browsers/chrome': True } ] } select_multiples = { 'browser_use/browsers': [ 'browser_use/browsers/firefox', 'browser_use/browsers/safari', 'browser_use/browsers/ie', 'browser_use/browsers/chrome' ] } result = CSVDataFrameBuilder._split_select_multiples(record, select_multiples) self.assertEqual(expected_result, result) def test_split_gps_fields(self): record = { 'gps': '5 6 7 8' } gps_fields = ['gps'] expected_result = { 'gps': '5 6 7 8', '_gps_latitude': '5', '_gps_longitude': '6', '_gps_altitude': '7', '_gps_precision': '8', } AbstractDataFrameBuilder._split_gps_fields(record, gps_fields) self.assertEqual(expected_result, record) def test_split_gps_fields_within_repeats(self): record = \ { 'a_repeat': [ { 'a_repeat/gps': '1 2 3 4' }, { 'a_repeat/gps': '5 6 7 8' } ] } gps_fields = ['a_repeat/gps'] expected_result = \ { 'a_repeat': [ { 'a_repeat/gps': '1 2 3 4', 'a_repeat/_gps_latitude': '1', 'a_repeat/_gps_longitude': '2', 'a_repeat/_gps_altitude': '3', 'a_repeat/_gps_precision': '4', }, { 'a_repeat/gps': '5 6 7 8', 'a_repeat/_gps_latitude': '5', 'a_repeat/_gps_longitude': '6', 'a_repeat/_gps_altitude': '7', 'a_repeat/_gps_precision': '8', } ] } AbstractDataFrameBuilder._split_gps_fields(record, gps_fields) self.assertEqual(expected_result, record) def test_unicode_export(self): unicode_char = unichr(40960) # fake data data = [{"key": unicode_char}] columns = ["key"] # test xls xls_df_writer = XLSDataFrameWriter(data, columns) temp_file = NamedTemporaryFile(suffix=".xls") excel_writer = ExcelWriter(temp_file.name) passed = False try: xls_df_writer.write_to_excel(excel_writer, "default") passed = True except UnicodeEncodeError: pass finally: temp_file.close() self.assertTrue(passed) # test csv passed = False csv_df_writer = CSVDataFrameWriter(data, columns) temp_file = NamedTemporaryFile(suffix=".csv") try: csv_df_writer.write_to_csv(temp_file) passed = True except UnicodeEncodeError: pass finally: temp_file.close() temp_file.close() self.assertTrue(passed) def test_repeat_child_name_matches_repeat(self): """ ParsedInstance.to_dict creates a list within a repeat if a child has the same name as the repeat This test makes sure that doesnt happen """ self.maxDiff = None fixture = "repeat_child_name_matches_repeat" # publish form so we have a dd to pass to xform inst. parser self._publish_xls_fixture_set_xform(fixture) submission_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "fixtures", fixture, fixture + ".xml" ) # get submission xml str with open(submission_path, "r") as f: xml_str = f.read() dict = xform_instance_to_dict(xml_str, self.xform.data_dictionary()) expected_dict = { u'test_item_name_matches_repeat': { u'formhub': { u'uuid': u'c911d71ce1ac48478e5f8bac99addc4e' }, u'gps': [ { u'info': u'Yo', u'gps': u'-1.2625149 36.7924478 0.0 30.0' }, { u'info': u'What', u'gps': u'-1.2625072 36.7924328 0.0 30.0' } ] } } self.assertEqual(dict, expected_dict) def test_remove_dups_from_list_maintain_order(self): l = ["a", "z", "b", "y", "c", "b", "x"] result = remove_dups_from_list_maintain_order(l) expected_result = ["a", "z", "b", "y", "c", "x"] self.assertEqual(result, expected_result) def test_valid_sheet_name(self): sheet_names = ["sheet_1", "sheet_2"] desired_sheet_name = "sheet_3" expected_sheet_name = "sheet_3" generated_sheet_name = get_valid_sheet_name(desired_sheet_name, sheet_names) self.assertEqual(generated_sheet_name, expected_sheet_name) def test_invalid_sheet_name(self): sheet_names = ["sheet_1", "sheet_2"] desired_sheet_name = "sheet_3_with_more_than_max_expected_length" expected_sheet_name = "sheet_3_with_more_than_max_exp" generated_sheet_name = get_valid_sheet_name(desired_sheet_name, sheet_names) self.assertEqual(generated_sheet_name, expected_sheet_name) def test_duplicate_sheet_name(self): sheet_names = ["sheet_2_with_duplicate_sheet_n", "sheet_2_with_duplicate_sheet_1"] duplicate_sheet_name = "sheet_2_with_duplicate_sheet_n" expected_sheet_name = "sheet_2_with_duplicate_sheet_2" generated_sheet_name = get_valid_sheet_name(duplicate_sheet_name, sheet_names) self.assertEqual(generated_sheet_name, expected_sheet_name) def test_query_mongo(self): """ Test querying for record count and records using AbstractDataFrameBuilder._query_mongo """ self._publish_single_level_repeat_form() # submit 3 instances for i in range(3): self._submit_fixture_instance("new_repeats", "01") df_builder = XLSDataFrameBuilder(self.user.username, self.xform.id_string) record_count = df_builder._query_mongo(count=True) self.assertEqual(record_count, 3) cursor = df_builder._query_mongo() records = [record for record in cursor] self.assertTrue(len(records), 3) # test querying using limits cursor = df_builder._query_mongo(start=2, limit=2) records = [record for record in cursor] self.assertTrue(len(records), 1) def test_prefix_from_xpath(self): xpath = "parent/child/grandhild" prefix = get_prefix_from_xpath(xpath) self.assertEqual(prefix, 'parent/child/') xpath = "parent/child" prefix = get_prefix_from_xpath(xpath) self.assertEqual(prefix, 'parent/') xpath = "parent" prefix = get_prefix_from_xpath(xpath) self.assertTrue(prefix is None) def test_csv_export_with_df_size_limit(self): """ To fix pandas limitation of 30k rows on csv export, we specify a max number of records in a dataframe on export - lets test it """ self._publish_single_level_repeat_form() # submit 7 instances for i in range(4): self._submit_fixture_instance("new_repeats", "01") self._submit_fixture_instance("new_repeats", "02") for i in range(2): self._submit_fixture_instance("new_repeats", "01") csv_df_builder = CSVDataFrameBuilder(self.user.username, self.xform.id_string) record_count = csv_df_builder._query_mongo(count=True) self.assertEqual(record_count, 7) temp_file = NamedTemporaryFile(suffix=".csv", delete=False) csv_df_builder.export_to(temp_file.name, data_frame_max_size=3) csv_file = open(temp_file.name) csv_reader = csv.reader(csv_file) header = csv_reader.next() self.assertEqual( len(header), 17 + len(AbstractDataFrameBuilder.ADDITIONAL_COLUMNS)) rows = [] for row in csv_reader: rows.append(row) self.assertEqual(len(rows), 7) self.assertEqual(rows[4][5], NA_REP) # close and delete file csv_file.close() os.unlink(temp_file.name) def test_csv_column_indices_in_groups_within_repeats(self): self._publish_xls_fixture_set_xform("groups_in_repeats") self._submit_fixture_instance("groups_in_repeats", "01") dd = self.xform.data_dictionary() columns = dd.get_keys() data_0 = self._csv_data_for_dataframe()[0] # remove dynamic fields ignore_list = [ '_uuid', 'meta/instanceID', 'formhub/uuid', '_submission_time', '_id', '_bamboo_dataset_id'] for item in ignore_list: data_0.pop(item) expected_data_0 = { # u'_id': 1, # u'_uuid': u'ba6bc9d7-b46a-4d25-955e-99ec94e7b2f6', u'_deleted_at': None, u'_xform_id_string': u'groups_in_repeats', u'_status': u'submitted_via_web', # u'_bamboo_dataset_id': u'', # u'_submission_time': u'2013-03-20T10:50:08', u'name': u'Abe', u'age': u'88', u'has_children': u'1', # u'meta/instanceID': u'uuid:ba6bc9d7-b46a-4d25-955e-99ec94e7b2f6', # u'formhub/uuid': u'1c491d705d514354acd4a9e34fe7526d', u'_attachments': [], u'children[1]/childs_info/name': u'Cain', u'children[2]/childs_info/name': u'Abel', u'children[1]/childs_info/age': u'56', u'children[2]/childs_info/age': u'48', u'children[1]/immunization/immunization_received/polio_1': True, u'children[1]/immunization/immunization_received/polio_2': False, u'children[2]/immunization/immunization_received/polio_1': True, u'children[2]/immunization/immunization_received/polio_2': True, u'web_browsers/chrome': True, u'web_browsers/firefox': False, u'web_browsers/ie': False, u'web_browsers/safari': False, u'gps': u'-1.2626156 36.7923571 0.0 30.0', u'_geolocation': [u'-1.2626156', u'36.7923571'], u'_gps_latitude': u'-1.2626156', u'_gps_longitude': u'36.7923571', u'_gps_altitude': u'0.0', u'_gps_precision': u'30.0', } self.maxDiff = None self.assertEqual(data_0, expected_data_0) # todo: test nested repeats as well on xls def test_xls_groups_within_repeats(self): self._publish_xls_fixture_set_xform("groups_in_repeats") self._submit_fixture_instance("groups_in_repeats", "01") dd = self.xform.data_dictionary() columns = dd.get_keys() data = self._xls_data_for_dataframe() # remove dynamic fields ignore_list = [ '_uuid', 'meta/instanceID', 'formhub/uuid', '_submission_time', '_id', '_bamboo_dataset_id'] for item in ignore_list: # pop unwanted keys from main section for d in data["groups_in_repeats"]: if d.has_key(item): d.pop(item) # pop unwanted keys from children's section for d in data["children"]: if d.has_key(item): d.pop(item) # todo: add _id to xls export expected_data = { u"groups_in_repeats": [ { # u'_submission_time': u'2013-03-21T02:57:37', u'picture': None, u'has_children': u'1', u'name': u'Abe', u'age': u'88', u'web_browsers/chrome': True, u'web_browsers/safari': False, u'web_browsers/ie': False, u'web_browsers/firefox': False, u'gps': u'-1.2626156 36.7923571 0.0 30.0', u'_gps_latitude': u'-1.2626156', u'_gps_longitude': u'36.7923571', u'_gps_altitude': u'0.0', u'_gps_precision': u'30.0', # u'meta/instanceID': u'uuid:ba6bc9d7-b46a-4d25-955e-99ec94e7b2f6', # u'_uuid': u'ba6bc9d7-b46a-4d25-955e-99ec94e7b2f6', u'_index': 1, u'_parent_table_name': None, u'_parent_index': -1 } ] , u"children": [ { u'children/childs_info/name': u'Cain', u'children/childs_info/age': u'56', u'children/immunization/immunization_received/polio_1': True, u'children/immunization/immunization_received/polio_2': False, u'_index': 1, u'_parent_table_name': u'groups_in_repeats', u'_parent_index': 1, # u'_submission_time': None, # u'_uuid': None, }, { u'children/childs_info/name': u'Able', u'children/childs_info/age': u'48', u'children/immunization/immunization_received/polio_1': True, u'children/immunization/immunization_received/polio_2': True, u'_index': 2, u'_parent_table_name': u'groups_in_repeats', u'_parent_index': 1, # u'_submission_time': None, # u'_uuid': None, } ] } self.maxDiff = None self.assertEqual( data["groups_in_repeats"][0], expected_data["groups_in_repeats"][0]) # each of the children should have children/... keys, we can guratnee the order so we cant check the values, just make sure they are not none self.assertEqual(len(data["children"]), 2) for child in data["children"]: self.assertTrue(child.has_key("children/childs_info/name")) self.assertIsNotNone(child["children/childs_info/name"]) self.assertTrue(child.has_key("children/childs_info/age")) self.assertIsNotNone(child["children/childs_info/name"]) self.assertTrue(child.has_key("children/immunization/immunization_received/polio_1")) self.assertEqual(type(child["children/immunization/immunization_received/polio_1"]), bool) self.assertTrue(child.has_key("children/immunization/immunization_received/polio_2")) self.assertEqual(type(child["children/immunization/immunization_received/polio_2"]), bool)
bsd-2-clause
cventeic/venteicher-org
src/app/app.component.ts
6969
import { Component } from '@angular/core'; import { Card } from './card'; import { Header } from './header'; import { Hyperlink } from './hyperlink'; import imgUri from './images/ChrisProfilePicture.jpg'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; cards: Array<Card>; constructor (){ console.log("app.component.ts constructor"); this.cards = [ new Card({ images: [imgUri], hyperlinks: [ new Hyperlink({ href:"https://github.com/cventeic", icons:["github-circle"], texts:["GitHub- All Repos"] }), new Hyperlink({ href:"https://linkedin.com/in/chris-venteicher", icons:["linkedin-box"], texts:["LinkedIn- Chris V"] }), new Hyperlink({ href: "tel:262 607 2040", icons:["phone"], texts:["Phone: 262 607 2040"] }), new Hyperlink({ href: "email:chris@venteicher.org", icons:["email"], texts:["Email: chris@venteicher.org"] }), ], headers: [ new Header({ tags: [], avatarUrls: [ imgUri ], titles: [ `Chris Venteicher`, `Software Engineer, Developer of Venteicher.org`, ], }), ], contents: [ ` <p> I am a Computer Engineer who is bothered when he doesn't know how something works, enjoys building things, enjoys programming and runs Linux on all his computers. </p> I have the most interest and experience in: <ul> <li> C, C++, Ruby </li> <li> Machine Learning (Genetic Algorithms, Neural Nets, Markov Models, Agent Systems) </li> <li> Web Technologies (d3.js, Rails, Angular4, Kubernetes) </li> <li> Cellular (Android, Modems 3GPP, 4G/LTE)</li> <li> Networking (IPv4, IPv6, Proxy Mobile IP, PPP, DHCP, VPN, WiFi, VoIP/SIP)</li> <li> Linux (Ubuntu, Kernel, Network Drivers, Performance Tools)</li> <li> Video Compression, 3D Graphics / OpenGL </li> </ul> ` ], tags: [ 'person' ] }), new Card({ images: [], headers: [ new Header({ tags: [], avatarUrls: [ imgUri ], titles: [ "Venteicher.org Web Site", "WebSite Construction and Cloud Deployment", ], }), ], contents: [ ` This web site is constructed using: <ul> <li> Angular 4 </li> <li> Angular Material 2 </li> <li> Angular Universal (Server Side rendering to speed up initial page loading)</li> </ul> This web site hosted and served using: <ul> <li> Phusion Passenger + Nginx + Node.js to serve content. </li> <li> Google Container Engine + Kubernetes for Hosting / Compute. </li> </ul> <p> Rails 5 was originally used to serve content. However I did not succeed in supporting Angular Universal with Rails 5 + Webpacker. In the future I plan to re-integrate Rails 5 to provide backend database services. </p> ` ], tags: [ 'project', 'site' ], hyperlinks: [ new Hyperlink({ href:"https://github.com/cventeic", icons:["github-circle"], texts:["GitHub- Site Content"] }), new Hyperlink({ href:"https://github.com/cventeic", icons:["github-circle"], texts:["GitHub- Google Container / Kubernetes Deployment Scripts"] }), new Hyperlink({ href: "https://angular.io", icons:["angular"], texts:["Angular.io (v4)"] }), new Hyperlink({ href: "https://material.angular.io", icons:["angular-material"], texts:["Angular Material"] }), new Hyperlink({ href: "https://kubernetes.io", icons:["kubernetes"], texts:["Kubernetes"] }), new Hyperlink({ href: "https://cloud.google.com/container-engine", icons:["google-container-engine"], texts:["Google Container Engine"] }), new Hyperlink({ href: "https://www.phusionpassenger.com", icons:["passenger"], texts:["Passenger"] }), new Hyperlink({ href: "https://www.docker.com", icons:["docker"], texts:["Docker"] }), new Hyperlink({ href: "https://lwn.net/Kernel", icons:["linux"], texts:["Linux"] }), ], }), new Card({ headers: [ new Header({ tags: [], avatarUrls: [ imgUri ], titles: [ "3D Printer", "Custom Designed and Built 3D Printer", ], }), ], contents: [ ` The 3D printer was built using: <ul> <li> v-slot linear rails from openbuilds (20mm x 20mm and 20mm x 80mm rails) </li> <li> Ramps 1.4 (arduino) electronics </li> <li> Marlin software on the Ramps </li> </ul> The Printing process uses: <ul> <li> Octoprint for remote control </li> <li> Cura for slicing </li> </ul> ` ], tags: [ 'project'], videos: [ "https://www.youtube.com/embed/zzwA_C7NFoI" ], hyperlinks: [ ], }), new Card({ headers: [ new Header({ tags: [], avatarUrls: [ imgUri ], titles: [ "Interactive 3D Graphics via Ruby", "OpenGL 3D Graphics in Ruby Language" ], }), ], contents: [ ` OpenGL 3D graphics written in Ruby <ul> <li> Programatic shaders with diffuse and specular lighting. </li> <li> Arcball and Quaterion implemented in Ruby code. </li> <li> Basic shape rendering in Ruby code. </li> <li> Buffer management in Ruby. </li> </ul> ` ], tags: [ 'project' ], hyperlinks: [ new Hyperlink({ href:"https://github.com/cventeic/opengl-ruby", icons:["github-circle"], texts:["GitHub- opengl-ruby code "] }), ], videos: [ "https://www.youtube.com/embed/_8pJCWOsiIo" ], }), ] } }
bsd-2-clause
ibudiselic/contest-problem-solutions
tc 160+/Stick.cpp
1805
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> #include <numeric> using namespace std; class Stick { public: int pieces(int x) { vector<int> v; v.push_back(64); while (1) { int t = accumulate(v.begin(), v.end(), 0); if (t == x) { return (int)v.size(); } v[0] = v[0]/2; if (t - v[0] < x) { v.insert(v.begin(), v[0]); } } return -1; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 32; int Arg1 = 1; verify_case(0, Arg1, pieces(Arg0)); } void test_case_1() { int Arg0 = 48; int Arg1 = 2; verify_case(1, Arg1, pieces(Arg0)); } void test_case_2() { int Arg0 = 23; int Arg1 = 4; verify_case(2, Arg1, pieces(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { Stick ___test; ___test.run_test(-1); } // END CUT HERE
bsd-2-clause
homiak/pims-lims
src/servlet/org/pimslims/servlet/AjaxExists.java
4184
/** * pims-web org.pimslims.servlet AjaxUnique.java * * @author Marc Savitsky * @date 25 Oct 2007 * * Protein Information Management System * @version: 1.3 * * Copyright (c) 2007 Marc Savitsky * * * */ package org.pimslims.servlet; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jdom.Document; import org.jdom.Element; import org.jdom.output.XMLOutputter; import org.pimslims.dao.ReadableVersion; import org.pimslims.metamodel.MetaClass; import org.pimslims.metamodel.ModelObject; /** * AjaxUnique * */ public class AjaxExists extends PIMSServlet { @Override public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override public String getServletInfo() { return "Create a PiMS record and send an XML reply"; } @Override //TODO no, only GET required public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final java.io.PrintWriter writer = response.getWriter(); final String metaClassName = request.getPathInfo().substring(1); //System.out.println("AjaxExists [" + metaClassName + "]"); MetaClass metaClass = null; try { metaClass = this.getModel().getMetaClass(metaClassName); } catch (final java.lang.AssertionError e) { //can't find metaclass by name } if (null == metaClass) { // TODO provide AJAX error reporter PIMSServlet.sendHttpHeaders(response, HttpServletResponse.SC_BAD_REQUEST); writer.print("Unknown type: " + metaClassName); return; } final ReadableVersion version = this.getReadableVersion(request, response); if (version == null) { return; } try { final java.util.Map parms = request.getParameterMap(); final java.util.Map<String, Object> params = new HashMap<String, Object>(); //Map params = parseValues(version, parms, pmeta, errorMessages); for (final Iterator iter = parms.entrySet().iterator(); iter.hasNext();) { final Map.Entry entry = (Map.Entry) iter.next(); final String key = (String) entry.getKey(); final String[] values = (String[]) entry.getValue(); for (int i = 0; i < values.length; i++) { //System.out.println("AjaxExists Parameter [" + key + "," + values[i] + "]"); params.put(key, values[i]); } } final ModelObject mObj = version.findFirst(metaClass.getJavaClass(), params); /*if (null != mObj) { //System.out.println("AjaxExists FALSE [" + mObj.get_Name() + ":" + mObj.get_Hook() + "]"); }*/ AjaxExists.sendXMLResponse(request, response, mObj); } finally { if (!version.isCompleted()) { version.abort(); } } } public static void sendXMLResponse(final HttpServletRequest request, final HttpServletResponse response, final ModelObject createdObject) throws IOException { final Element rootElement = new Element("unique"); final Element elem = new Element("modelobject"); if (null != createdObject) { elem.setAttribute("hook", createdObject.get_Hook()); } rootElement.addContent(elem); // TODO for all roles, for all associates, add an <object> element final Document xml = new Document(rootElement); response.setContentType("text/xml"); final XMLOutputter xo = new XMLOutputter(); xo.output(xml, response.getWriter()); } }
bsd-2-clause
DanielArenas/mezcalaria-backend
spec/factories/events.rb
145
FactoryGirl.define do factory :event do name "MyString" place "MyString" date_event "2017-05-03" baner "MyString" is_free false end end
bsd-2-clause
wzman/werkkzeug4CE
altona/main/gui/gui.hpp
1493
/****************************************************************************/ /*** ***/ /*** (C) 2005 Dierk Ohlerich, all rights reserved ***/ /*** ***/ /****************************************************************************/ #ifndef FILE_GUI_GUI_HPP #define FILE_GUI_GUI_HPP #ifndef __GNUC__ #pragma once #endif // base #include "base/types.hpp" #include "base/windows.hpp" #include "base/types2.hpp" // window system #include "gui/window.hpp" #include "gui/manager.hpp" #include "gui/wire.hpp" // general windows #include "gui/frames.hpp" #include "gui/controls.hpp" #include "gui/borders.hpp" #include "gui/dialog.hpp" // special windows: not included by default #if 0 #include "gui/textwindow.hpp" #include "gui/listwindow.hpp" #include "gui/3dwindow.hpp" #include "gui/overlapped.hpp" #endif /****************************************************************************/ /* example for a good starting point: #include "base/system.hpp" #include "gui/gui.hpp" class MyWindow : public sWindow { public: void OnPaint2D() { sRect2D(Client,sGC_BACK); sLine2D(Client.x0,Client.y0,Client.x1-1,Client.y1-1,sGC_DRAW); sLine2D(Client.x0,Client.y1-1,Client.x1-1,Client.y0,sGC_DRAW); } }; void sMain() { sInit(sISF_2D,800,600); sInitGui(); sGui->AddBackWindow(new MyWindow); } */ #endif
bsd-2-clause
finvernizzi/mplane_http_transport
ssl_files.js
1660
/** * This module manages external CA or keys * It is simply a wrapper of basic FS functions for simpler HTTPS options * * @type {readCaChain} */ var fs = require('fs'); module.exports.readCaChain = readCaChain; module.exports.readFileContent = readFileContent; /** * Given an array of file name (complete path) or a single file (complete path), return an array of ca for use in https options * @param caChain can be a file full path or an array of files (full path) if you are using a CA chain. * @returns {*} the CA cahin to be used as options in https requests */ function readCaChain(caChain){ var ret = []; if (caChain instanceof Array){ caChain.forEach(function(fileName){ try{ ret.push(fs.readFileSync(fileName , "utf-8")) }catch(e){ console.log("---readCaChain--- Error reading CA chain file"); console.log(e); return null; } }); } // IF it is a string, it should be directly a file name and not a chain if (caChain instanceof String){ try{ ret.push(fs.readFileSync(caChain) , "utf-8"); }catch(e){ console.log("---readCaChain--- Error reading CA chain file"); console.log(e); return null; } } return ret; } /** * Reads cert and keys * @param fileName (full path) * @returns {*} */ function readFileContent(fileName){ try{ return(fs.readFileSync(fileName , "utf-8")); }catch(e){ console.log("---readFileContent-- Error reading file "+fileName); console.log(e); return null; } }
bsd-2-clause
forkch/scrabble_ar
examples/book_eclipse/Chapter4/SensorFusionJME/src/com/ar4android/sensorFusionJME/SensorFusionJME.java
7934
/* SensorFusionJME - SensorFusionJME Example * * Example Chapter 4 * accompanying the book * "Augmented Reality for Android Application Development", Packt Publishing, 2013. * * Copyright © 2013 Jens Grubert, Raphael Grasset / Packt Publishing. * * This example use the sensor fusion code from * //http://www.thousand-thoughts.com/2012/03/android-sensor-fusion-tutorial/ */ package com.ar4android.sensorFusionJME; import com.jme3.animation.AnimChannel; import com.jme3.animation.AnimControl; import com.jme3.animation.AnimEventListener; import com.jme3.animation.LoopMode; import com.jme3.app.SimpleApplication; import com.jme3.light.DirectionalLight; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.FastMath; import com.jme3.math.Quaternion; import com.jme3.math.Vector3f; import com.jme3.renderer.Camera; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Geometry; import com.jme3.scene.Spatial; import com.jme3.scene.shape.Box; import com.jme3.scene.shape.Quad; import com.jme3.texture.Image; import com.jme3.texture.Texture2D; public class SensorFusionJME extends SimpleApplication implements AnimEventListener { private static final String TAG = "SensorFusionJME"; // The geometry which will represent the video background private Geometry mVideoBGGeom; // The material which will be applied to the video background geometry. private Material mvideoBGMat; // The texture displaying the Android camera preview frames. private Texture2D mCameraTexture; // the JME image which serves as intermediate storage place for the Android // camera frame before the pixels get uploaded into the texture. private Image mCameraImage; // A flag indicating if the scene has been already initialized. private boolean mSceneInitialized = false; // A flag indicating if a new Android camera image is available. boolean mNewCameraFrameAvailable = false; private Quaternion mInitialCamRotation; private Quaternion mRotXQ; private Quaternion mRotYQ; private Quaternion mRotZQ; private Quaternion mRotXYZQ; //the User rotation which serves as intermediate storage place for the Android //Sensor listener motion update private Quaternion mCurrentCamRotationFused; private Quaternion mCurrentCamRotation; //A flag indicating if a new Rotation is available private boolean mNewUserRotationFusedAvailable =false; private float mForegroundCamFOVY = 50; // for a Samsung Galaxy SII Camera fgCam; // for animation // The controller allows access to the animation sequences of the model private AnimControl mAniControl; // the channel is used to run one animation sequence at a time private AnimChannel mAniChannel; static int counterTime=1000; public static void main(String[] args) { SensorFusionJME app = new SensorFusionJME(); app.start(); } @Override public void simpleInitApp() { // Do not display statistics setDisplayStatView(false); setDisplayFps(false); // we use our custom viewports - so the main viewport does not need the rootNode viewPort.detachScene(rootNode); initVideoBackground(settings.getWidth(), settings.getHeight()); initForegroundScene(); initBackgroundCamera(); initForegroundCamera(mForegroundCamFOVY); mSceneInitialized = true; } // This function creates the geometry, the viewport and the virtual camera // needed for rendering the incoming Android camera frames in the scene // graph public void initVideoBackground(int screenWidth, int screenHeight) { // Create a Quad shape. Quad videoBGQuad = new Quad(1, 1, true); // Create a Geometry with the Quad shape mVideoBGGeom = new Geometry("quad", videoBGQuad); float newWidth = 1.f * screenWidth / screenHeight; // Center the Geometry in the middle of the screen. mVideoBGGeom.setLocalTranslation(-0.5f * newWidth, -0.5f, 0.f);// // Scale (stretch) the width of the Geometry to cover the whole screen // width. mVideoBGGeom.setLocalScale(1.f * newWidth, 1.f, 1); // Apply a unshaded material which we will use for texturing. mvideoBGMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); mVideoBGGeom.setMaterial(mvideoBGMat); // Create a new texture which will hold the Android camera preview frame // pixels. mCameraTexture = new Texture2D(); mCurrentCamRotationFused=new Quaternion(0.f,0.f,0.f,1.f); mCurrentCamRotation = new Quaternion(0.f,0.f,0.f,1.f); } public void initBackgroundCamera() { // Create a custom virtual camera with orthographic projection Camera videoBGCam = cam.clone(); videoBGCam.setParallelProjection(true); // Also create a custom viewport. ViewPort videoBGVP = renderManager.createMainView("VideoBGView", videoBGCam); // Attach the geometry representing the video background to the // viewport. videoBGVP.attachScene(mVideoBGGeom); } public void initForegroundScene() { // Load a model from test_data (OgreXML + material + texture) Spatial ninja = assetManager.loadModel("Models/Ninja/Ninja.mesh.xml"); ninja.scale(0.025f, 0.025f, 0.025f); ninja.rotate(0.0f, -3.0f, 0.0f); ninja.setLocalTranslation(0.0f, -2.5f, -10.0f); rootNode.attachChild(ninja); // You must add a light to make the model visible DirectionalLight sun = new DirectionalLight(); sun.setDirection(new Vector3f(-0.1f, -0.7f, -1.0f)); rootNode.addLight(sun); mAniControl = ninja.getControl(AnimControl.class); mAniControl.addListener(this); mAniChannel = mAniControl.createChannel(); // show animation from beginning mAniChannel.setAnim("Walk"); mAniChannel.setLoopMode(LoopMode.Loop); mAniChannel.setSpeed(1f); } public void initForegroundCamera(float fovY) { fgCam = new Camera(settings.getWidth(), settings.getHeight()); fgCam.setLocation(new Vector3f(0f, 0f, 0f)); fgCam.setAxes(new Vector3f(-1f,0f,0f), new Vector3f(0f,1f,0f), new Vector3f(0f,0f,-1f)); mInitialCamRotation = new Quaternion(); mInitialCamRotation.fromAxes(new Vector3f(-1f,0f,0f), new Vector3f(0f,1f,0f), new Vector3f(0f,0f,-1f)); mRotXQ = new Quaternion(); mRotYQ = new Quaternion(); mRotZQ = new Quaternion(); mRotXYZQ = new Quaternion(); fgCam.setFrustumPerspective(fovY, settings.getWidth()/settings.getHeight(), 1, 50000); ViewPort fgVP = renderManager.createMainView("ForegroundView", fgCam); fgVP.attachScene(rootNode); fgVP.setClearFlags(false, true, false); fgVP.setBackgroundColor(ColorRGBA.Blue); } public void onAnimCycleDone(AnimControl control, AnimChannel channel, String animName) { // unused } public void onAnimChange(AnimControl control, AnimChannel channel, String animName) { // unused } // This method retrieves the preview images from the Android world and puts // them into a JME image. public void setVideoBGTexture(final Image image) { if (!mSceneInitialized) { return; } mCameraImage = image; mNewCameraFrameAvailable = true; } public void setRotationFused(float pitch, float roll, float heading) { if (!mSceneInitialized) { return; } // pitch: cams x axis roll: cams y axisheading: cams z axis mRotXYZQ.fromAngles(pitch + FastMath.HALF_PI , roll - FastMath.HALF_PI, 0); mCurrentCamRotationFused = mInitialCamRotation.mult(mRotXYZQ); mNewUserRotationFusedAvailable =true; } @Override public void simpleUpdate(float tpf) { if (mNewCameraFrameAvailable) { mCameraTexture.setImage(mCameraImage); mvideoBGMat.setTexture("ColorMap", mCameraTexture); } if (mNewUserRotationFusedAvailable) { fgCam.setAxes(mCurrentCamRotationFused); mNewUserRotationFusedAvailable=false; } mVideoBGGeom.updateLogicalState(tpf); mVideoBGGeom.updateGeometricState(); } @Override public void simpleRender(RenderManager rm) { // unused } }
bsd-2-clause
KostaVlev/Wilson
Web/Wilson.Web/Seed/CompaniesDbSeeder.cs
5190
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.DependencyInjection; using Wilson.Accounting.Data; using Wilson.Companies.Core.Entities; using Wilson.Companies.Core.Enumerations; using Wilson.Companies.Data; using Wilson.Web.Events; using Wilson.Web.Events.Interfaces; namespace Wilson.Web.Seed { /// <summary> /// Contains the data which will be seeded for the Company module. Before seeding the Company module seed /// first Accounting Module. /// </summary> public static class CompaniesDbSeeder { private static IEnumerable<Employee> employees; private static IEnumerable<Inquiry> inquiries; private static IEnumerable<Offer> offers; /// <summary> /// Seeds the data for the Company module. /// </summary> /// <param name="services">The service factory.</param> public static void Seed(IServiceScopeFactory services, IEventsFactory eventsFactory) { using (var scope = services.CreateScope()) { var companyDb = scope.ServiceProvider.GetRequiredService<CompanyDbContext>(); var accountingDb = scope.ServiceProvider.GetRequiredService<AccountingDbContext>(); // Keep the following methods in this exact order. SeedEmployees(companyDb, out employees); SeedInquiries(companyDb, out inquiries); SeedOffers(companyDb, out offers); companyDb.SaveChanges(); eventsFactory.Raise(new EmployeeCreated(employees)); } } private static void SeedEmployees(CompanyDbContext companyDb, out IEnumerable<Employee> employees) { var company = companyDb.Companies.FirstOrDefault(); if (company == null) { throw new ArgumentNullException( "company", "Accounting module must be seeded first. Make sure the even CompaniesCreated is triggered."); } var ivan = Employee.Create( "Ivan", "Petrov", "0125669874", "0135698552", "j.smith@mail.com", EmployeePosition.OfficeSaff, Address.Create("Bulgaria", "1000", "Sofia", "Vasil Levski", "11"), company.Id); var maria = Employee.Create( "Maria", "Popinska", "0526668822", "0329555645", "m.popinska@mail.com", EmployeePosition.OfficeSaff, Address.Create("Bulgaria", "1000", "Sofia", "Ivan Vazov", "2B"), company.Id); employees = new List<Employee> { ivan, maria }; companyDb.Employees.AddRange(employees); } private static void SeedInquiries(CompanyDbContext companyDb, out IEnumerable<Inquiry> inquiries) { var company = companyDb.Companies.Skip(1).FirstOrDefault(); if (company == null) { throw new ArgumentNullException( "company", "Accounting module must be seeded first. Make sure the even CompaniesCreated is triggered and at least two companies are seeded."); } if (employees == null || employees.Count() < 2) { throw new ArgumentNullException( "employees", "Run SeedCompanyEmployees() first and make sure at least two Employees are seeded."); } var ivan = employees.First(); var maria = employees.Skip(1).First(); var inquiry = Inquiry.Create("Offer for part Electrical - Apartment Complex", ivan.Id, company.Id); inquiry.AddAssignee(maria.Id); inquiry.AddInfoRequest("We need the electrical plans to make offer.", maria.Id); inquiries = new List<Inquiry>() { inquiry }; companyDb.Inquiries.AddRange(inquiries); } private static void SeedOffers(CompanyDbContext companyDb, out IEnumerable<Offer> offers) { if (employees == null || employees.Count() < 2) { throw new ArgumentNullException( "employees", "Run SeedCompanyEmployees() first and make sure at least two Employees are seeded."); } if (inquiries == null || inquiries.Count() == 0) { throw new ArgumentNullException( "offers", "Run SeedInquiries() first and make sure at least one Offer is seeded."); } var maria = employees.Skip(1).First(); var inquiry = inquiries.First(); var offer = Offer.Create("No html yet.", inquiry.Id, maria.Id); offer.Send(maria.Id); offers = new List<Offer>() { offer }; companyDb.Set<Offer>().AddRange(offers); } } }
bsd-2-clause
fluffynuts/traymonkey
source/TrayMonkey.Tests/TestVolume.cs
3118
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using CoreAudioApi; using NUnit.Framework; namespace TrayMonkey.Tests { public class TestVolume { [Test] [Ignore("Run manually")] public void SimpleTest() { //---------------Set up test pack------------------- //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var enumerator = new MMDeviceEnumerator(); var defaultDeviceEndpoint = enumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia).AudioEndpointVolume; var leftChannel = defaultDeviceEndpoint.Channels[0]; var rightChannel = defaultDeviceEndpoint.Channels[1]; var startedWith = leftChannel.VolumeLevelScalar; Debug.WriteLine(startedWith); leftChannel.VolumeLevelScalar = 0.5f; rightChannel.VolumeLevelScalar = 0.5f; //---------------Test Result ----------------------- } [Test] [Ignore("Run manually")] public void GNARLY() { //---------------Set up test pack------------------- //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var enumerator = new MMDeviceEnumerator(); var defaultDeviceEndpoint = enumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia).AudioEndpointVolume; var leftChannel = defaultDeviceEndpoint.Channels[0]; var rightChannel = defaultDeviceEndpoint.Channels[1]; var startedWith = leftChannel.VolumeLevelScalar; Debug.WriteLine(startedWith); Action<float, float> setVolTo = (l, r) => { leftChannel.VolumeLevelScalar = l; rightChannel.VolumeLevelScalar = r; }; setVolTo(0, 1); try { var left = 0f; var right = 1f; var delta = 0.1f; var interval = 50; var totalTime = 10000; for (var i = 0; i < (totalTime/interval); i++) { Debug.WriteLine("left/right/delta: {0} / {1} / {2}", left, right, delta); left += delta; if (left < 0.05 || left > 0.95) { delta = -1*delta; left += 2 * delta; } right -= delta; setVolTo(left, right); Thread.Sleep(interval); } } catch (Exception) { setVolTo(0.6f, 0.6f); throw; } //---------------Test Result ----------------------- } } }
bsd-2-clause
sreal/bounce
LegacyBounce.Framework/BounceFactory.cs
322
namespace LegacyBounce.Framework { public class BounceFactory : IBounceFactory { public ITargetBuilderBounce GetBounce() { return new Bounce(); } public ITargetBuilderBounce GetBounce(LogOptions logOptions) { return new Bounce(logOptions); } } }
bsd-2-clause
jython234/nectar-server
src/main/java/io/github/jython234/nectar/server/EventLog.java
2976
package io.github.jython234.nectar.server; import lombok.AccessLevel; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.LocalDateTime; import java.util.ArrayDeque; import java.util.Deque; /** * Represents the server's internal event log that records * all actions performed by management sessions and clients. * * @author jython234 */ public class EventLog { @Getter private final int maxEntryCount; private int nextEntryId = 0; @Getter private final Deque<Entry> entries = new ArrayDeque<>(); @Getter private final Logger eventLogLogger; public EventLog(int maxEntryCount) { this.maxEntryCount = maxEntryCount; this.eventLogLogger = LoggerFactory.getLogger("Nectar-EventLog"); } public void addEntry(Entry entry) { synchronized (entries) { if(entries.size() >= maxEntryCount) { // If we reach the max size, remove the furthest entry entries.removeFirst(); } entry.setEntryId(nextEntryId++); this.entries.addLast(entry); // Add the entry to the end of the Deque } } public void addEntry(EntryLevel level, String message) { addEntry(new Entry(LocalDateTime.now(), level, message)); } public void logEntry(EntryLevel level, String message) { switch (level) { case DEBUG: this.eventLogLogger.debug("!|! " + message); break; case INFO: this.eventLogLogger.info("!|! " + message); break; case NOTICE: this.eventLogLogger.info("!|! (NOTICE): " + message); break; case WARNING: this.eventLogLogger.warn("!|! " + message); break; case ERROR: this.eventLogLogger.error("!|! " + message); break; } this.addEntry(new Entry(LocalDateTime.now(), level, message)); } /** * Represents an Entry inside the event log. * An entry contains a time, date, level, and message. * * @author jython234 */ @RequiredArgsConstructor public static class Entry { @Getter private final LocalDateTime datetime; @Getter private final EntryLevel level; @Getter private final String message; @Getter @Setter(AccessLevel.PROTECTED) private int entryId; } /** * Represents the level of an Entry * * @author jython234 */ public enum EntryLevel { DEBUG("DEBUG"), INFO("INFO"), NOTICE("NOTICE"), WARNING("WARNING"), ERROR("ERROR"); private String level; EntryLevel(String level) { this.level = level; } @Override public String toString() { return this.level; } } }
bsd-2-clause
WimpyAnalytics/django-andablog
andablog/migrations/0005_auto_20151017_1747.py
583
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('andablog', '0004_shorten_entry_title'), ] operations = [ migrations.AlterField( model_name='entry', name='slug', field=models.SlugField(unique=True, editable=False, max_length=255), ), migrations.AlterField( model_name='entry', name='title', field=models.CharField(max_length=255), ), ]
bsd-2-clause
cblecker/homebrew-core
Formula/ponyc.rb
1255
class Ponyc < Formula desc "Object-oriented, actor-model, capabilities-secure programming language" homepage "https://www.ponylang.org/" url "https://github.com/ponylang/ponyc.git", tag: "0.39.1", revision: "330b4bca5f53a9a87782166afbf7971e92bf37c2" license "BSD-2-Clause" bottle do sha256 cellar: :any_skip_relocation, big_sur: "592d31d1803e8a58534b842466e2bbf5235894b4c02c3ca83c9bea3b55cbce95" sha256 cellar: :any_skip_relocation, catalina: "497cc7a15b5856a879f734ec4b5cb0979e2c5d47f995c34597a18480a2d84081" sha256 cellar: :any_skip_relocation, mojave: "8a4daff68af70d89ef1cebca9e3116baec9dfaca31cd4abfa74926ce538f515a" end depends_on "cmake" => :build def install ENV.cxx11 ENV["MAKEFLAGS"] = "build_flags=-j#{ENV.make_jobs}" system "make", "libs" system "make", "configure" system "make", "build" system "make", "install", "DESTDIR=#{prefix}" end test do system "#{bin}/ponyc", "-rexpr", "#{prefix}/packages/stdlib" (testpath/"test/main.pony").write <<~EOS actor Main new create(env: Env) => env.out.print("Hello World!") EOS system "#{bin}/ponyc", "test" assert_equal "Hello World!", shell_output("./test1").strip end end
bsd-2-clause
wzman/werkkzeug4CE
altona/tools/wz4ops/doc.hpp
7186
/*+**************************************************************************/ /*** ***/ /*** This file is distributed under a BSD license. ***/ /*** See LICENSE.txt for details. ***/ /*** ***/ /**************************************************************************+*/ #ifndef FILE_WZ4OPS_DOC_HPP #define FILE_WZ4OPS_DOC_HPP #include "base/types2.hpp" #include "util/scanner.hpp" /****************************************************************************/ enum DocTypes { TYPE_LABEL = 1, TYPE_INT, TYPE_FLOAT, TYPE_COLOR, TYPE_FLAGS, TYPE_RADIO, TYPE_STRING, TYPE_FILEIN, TYPE_FILEOUT, TYPE_LINK, TYPE_GROUP, TYPE_STROBE, TYPE_ACTION, // trigger a code during editing that was defined with the op, that has access to the operator itself TYPE_CUSTOM, // Add a custom control TYPE_BITMASK, TYPE_CHARARRAY, }; enum CustomTokens { TOK_ANDAND = 0x100, TOK_OROR, TOK_IF, TOK_ELSE, TOK_ARRAY, }; class CodeBlock { public: CodeBlock(sPoolString code,sInt line); void Output(sTextBuffer &,const sChar *file,sBool semi=0); sPoolString Code; sInt Line; }; class External { public: External(); ~External(); sInt Line; sPoolString Type; sPoolString PureType; sPoolString Name; sPoolString Para; CodeBlock *Code; }; class Importer { public: Importer(); sPoolString Name; sPoolString Extension; sPoolString Code; }; class Type { public: Type(); ~Type(); sPoolString Parent; sPoolString Symbol; sPoolString Label; sU32 Color; sInt Flags; sInt GuiSets; sBool Virtual; CodeBlock *Code; CodeBlock *Header; sPoolString ColumnHeaders[31]; sArray<External *> Externals; }; enum ExprOp { EOP_NOP, // binary EOP_GT, EOP_LT, EOP_GE, EOP_LE, EOP_EQ, EOP_NE, EOP_AND, EOP_OR, EOP_BITAND, EOP_BITOR, // unary EOP_NOT, EOP_BITNOT, // special EOP_INT, EOP_SYMBOL, EOP_INPUT, }; struct ExprNode { sInt Op; ExprNode *Left; ExprNode *Right; sInt Value; sPoolString Symbol; }; enum ParaFlag { PF_Anim = 0x00000001, PF_LineNumber = 0x00000002, PF_Narrow = 0x00000004, PF_OverLabel = 0x00000008, PF_OverBox = 0x00000010, PF_Static = 0x00000020, }; class Parameter { public: Parameter(); sInt Type; sInt Offset; sPoolString Label; sPoolString Symbol; sPoolString CType; sPoolString Format; sF32 Min,Max,Step,RStep; sInt Count; sBool XYZW; sInt LinkMethod; union { sS32 DefaultS[16]; sU32 DefaultU[16]; sF32 DefaultF[16]; }; sBool DefaultStringRandom; sPoolString DefaultString; sPoolString Options; ExprNode *Condition; sInt LayoutFlag; // use LayoutMsg, not ChangeMsg, only for Flags sInt ContinueFlag; // do not create new variable, just new gui. for continuing Flags sInt FilterMode; sPoolString CustomName; // name of custom control class sInt GridLines; // lines in grid (for text edit thingies sInt Flags; /* sInt OverBoxFlag; // width in grid sInt OverLabelFlag; // width in grid sBool AnimFlag; // this parameter is animatable sBool LineNumberFlag; // line numbers in printf's sBool NarrowFlag; */ sPoolString ScriptName(); }; enum InputLinkMethod { IE_INPUT, IE_LINK, IE_BOTH, IE_CHOOSE, IE_ANIM, }; enum InputFlagsEnum { IF_OPTIONAL = 0x0001, IF_WEAK = 0x0002, }; class Input { public: Input(); sPoolString Type; sPoolString DefaultOpName,DefaultOpType; sBool InputFlags; sInt Method; sPoolString GuiSymbol; }; struct StructMember { sPoolString CType; sPoolString Name; sInt PointerCount; sInt ArrayCount; sInt Line; }; struct Struct { sArray<StructMember> Members; }; struct AnimInfo { sPoolString Name; sInt Flags; AnimInfo() { Flags = 0; } }; struct ActionInfo { sPoolString Name; sInt Id; void Init(sPoolString n,sInt i) { Name=n; Id=i; } }; struct Tie { sArray<sPoolString> Paras; }; class Op { public: Op(); ~Op(); sPoolString Name; sPoolString OutputType; // wz4 class name of output sPoolString TabType; sPoolString OutputClass; // c class name of output wObject derived class sPoolString Label; // screen name of the op sInt ArrayNumbers; // add number labeling sArray<Parameter *> Parameters; sArray<Parameter *> ArrayParam; sArray<AnimInfo> AnimInfos; sArray<ActionInfo> ActionInfos; sArray<Input *> Inputs; sArray<Tie *> Ties; sArray<Tie *> ArrayTies; CodeBlock *Code; sInt Shortcut; sInt Column; sInt MaxOffset; sInt MaxStrings; sInt MaxArrayOffset; sU32 FileInMask; sU32 FileOutMask; sPoolString FileInFilter; sInt Flags; sInt HideArray; sInt GroupArray; sInt GridColumns; sInt DefaultArrayMode; sPoolString Extract; sPoolString CustomEd; CodeBlock *Handles; CodeBlock *SetDefaultsArray; CodeBlock *Actions; CodeBlock *SpecialDrag; CodeBlock *Description; Struct *Helper; }; class Document { // parser sMemoryPool Pool; ExprNode *NewExpr(sInt op,ExprNode *left,ExprNode *right); ExprNode *NewExprInt(sInt value); sBool FindFlag(sPoolString para,const sChar *choice,sInt &mask,sInt &value); void _Global(); void _Include(sArray<CodeBlock *> &codes); CodeBlock *_CodeBlock(); void _Type(); sInt _Choice(const sChar *match); sInt _Flag(const sChar *match); void _Operator(); void _Parameter(Op *op,ExprNode *cond,sInt &offset,sInt &stringoffset,sInt inarray,sInt &linkoffset); void _Parameters(Op *op,ExprNode *cond,sInt &offset,sInt &stringoffset,sInt inarray,sInt &linkoffset); void _External(sArray<External *> &list); Struct *_Struct(); ExprNode *_Literal(); ExprNode *_Value(); ExprNode *_Expr(sInt level=6); void HPPLine(sInt line=-1); void CPPLine(sInt line=-1); void OutputCodeblocks(); void OutputExt(External *ext,const sChar *classname); void OutputTypes1(); void OutputTypes2(); void OutputParaStruct(const sChar *label,sArray<Parameter *> &pa,Op *op); void OutputIf(ExprNode *cond,ExprNode **condref,sInt indent); void OutputPara(sArray<Parameter *> &para,Op *op,sBool inarray); void OutputTies(sArray<Tie *> &ties); void OutputOps(); void OutputMain(); void OutputExpr(ExprNode *); void OutputStruct(sTextBuffer &tb,Struct *,const sChar *name); void OutputAnim(); sArray<CodeBlock *> HCodes; sArray<CodeBlock *> HEndCodes; sArray<CodeBlock *> CCodes; sArray<Type *> Types; sArray<Op *> Ops; Op *CurrentOp; public: Document(); ~Document(); sScanner Scan; sBool Parse(const sChar *filename); sBool Output(); sTextBuffer CPP; sTextBuffer HPP; sInt Priority; void SetNames(const sChar *name); sString<2048> InputFileName; sString<2048> CPPFileName; sString<2048> HPPFileName; sString<2048> ProjectName; }; extern Document *Doc; /****************************************************************************/ #endif // FILE_WZ4OPS_DOC_HPP
bsd-2-clause
decamp/util
util-common/src/main/java/bits/util/reflect/ClassFinder.java
15316
/* * Copyright (c) 2012, Massachusetts Institute of Technology * Released under the BSD 2-Clause License * http://opensource.org/licenses/BSD-2-Clause */ package bits.util.reflect; import java.io.*; import java.net.*; import java.util.*; import java.util.jar.*; import java.util.logging.Logger; import java.util.regex.*; public class ClassFinder { private static final Pattern CLASS_PAT = Pattern.compile( "^[a-z]++[a-z0-9_]*+$", Pattern.CASE_INSENSITIVE ); private static final Logger sLog = Logger.getLogger( ClassFinder.class.getName() ); /** * Finds all the resources spanned by the provided packageName. Resources * are returned as URLs and may represent directories or jar files. * * Resources are found using the calling thread's context class loader:<br> * {@code Thread.currentThread().getContextClassLoader()} * * @param packageName A package to check for resources. * @return a list of all resources found. * @throws ClassNotFoundException if provided package could not be found or any other error occurs. // */ public static List<URL> findPackageResources( String packageName ) throws ClassNotFoundException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if( classLoader == null ) { throw new ClassNotFoundException( "Failed to retrieve context ClassLoader." ); } return findPackageResources( packageName, classLoader ); } /** * Finds all the resources spanned by the provided packageName. Resources * are returned as URLs and may represent directories or jar files. * * @param packageName A package to check for resources. * @param classLoader The ClassLoader to use to search for resources. * @return a list of all resources found. * @throws ClassNotFoundException if provided package could not be found or any other error occurs. */ public static List<URL> findPackageResources( String packageName, ClassLoader classLoader ) throws ClassNotFoundException { String packagePath = packageName.replace( '.', '/' ); Enumeration<URL> resourceList; try { resourceList = classLoader.getResources( packagePath ); } catch( IOException ex ) { throw new ClassNotFoundException( packageName + " could not be found.", ex ); } List<URL> outList = new ArrayList<>(); while( resourceList.hasMoreElements() ) { outList.add( resourceList.nextElement() ); } return outList; } /** * Finds all the roots of resources spanned by the packageName. The * <i>resource root</i> means that the resource path is trimmed to * encapsulate the <i>default package</i> instead of the requested * package. * <p> * Resources are found using the calling thread's context class loader: <br> * {@code Thread.currentThread().getClassLoader()} * * @param packageName A package to check for resources. * @param classLoader The ClassLoader to use to search for resources. * @return a list of all resources found, trimmed to represent the default package. * @throws ClassNotFoundException if the provided package could not be found or any other error occurs. */ public static List<URL> findPackageResourceRoots( String packageName, ClassLoader classLoader ) throws ClassNotFoundException { List<URL> inList = findPackageResources( packageName, classLoader ); List<URL> outList = new ArrayList<>(); for( URL url : inList ) { if( url.getProtocol().equalsIgnoreCase( "file" ) ) { File file; try { file = new File( url.toURI() ); } catch( URISyntaxException ex ) { throw new ClassNotFoundException( "Could not create file from URL.", ex ); } while( packageName != null && packageName.length() > 0 ) { file = file.getParentFile(); if( file == null ) throw new ClassNotFoundException( "Could not traverse source tree for resource " + url.toString() ); int index = packageName.indexOf( "." ); if( index < 0 ) { packageName = null; } else { packageName = packageName.substring( index + 1 ); } } try { outList.add( new URL( "file:" + file.getPath() ) ); } catch( MalformedURLException ex ) { throw new ClassNotFoundException( "Could not create URL for file:" + file.getPath(), ex ); } } else if( url.getProtocol().equalsIgnoreCase( "jar" ) ) { String path = url.toString(); int i = path.lastIndexOf( "!" ); if( i < 0 ) { outList.add( url ); } else { path = path.substring( 0, i + 1 ) + "/"; try { outList.add( new URL( path ) ); } catch( MalformedURLException ex ) { throw new ClassNotFoundException( "Could not create URL for " + path, ex ); } } } else { throw new ClassNotFoundException( "Could not recognize protocol for resource " + url.toString() ); } } return outList; } /** * Finds all the roots of resources spanned by the packageName. The * <i>resource root</i> means that the resource path is trimmed to * encapsulate the <i>default package</i> instead of the requested * package. * <p> * Resources are found using the calling thread's context class loader: <br> * {@code Thread.currentThread().getClassLoader()} * * @param packageName A package to check for resources. * @return a list of all resources found, trimmed to represent the default package. * @throws ClassNotFoundException if the provided package could not be found or any other error occurs. */ public static List<URL> findPackageResourceRoots( String packageName ) throws ClassNotFoundException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if( classLoader == null ) { throw new ClassNotFoundException( "Failed to retrieve context ClassLoader." ); } return findPackageResourceRoots( packageName, classLoader ); } /** * Finds all the classes in a specified package. This method scans both * directories and/or jar files as necessary. * <p> * Classes are not initialized when loaded. Loading is performed by the * calling thread's context class loader:<br> * {@code Thread.currentThread().getContextClassLoader()} * * @param packageName The name of the package. * @param recurse Specifies whether class from subpackages should be included. * @return the list of classes in specified package. * @throws ClassNotFoundException if the package is not found or any other error occurs. */ public static List<Class<?>> findClasses( String packageName, boolean recurse ) throws ClassNotFoundException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); return findClasses( packageName, recurse, classLoader ); } /** * Finds all the classes in a specified package. This method scans both * directories and/or jar files as necessary. This method does not * initialize the classes it loads. * <p> * Classes are not initialized when loaded. * * @param packageName The name of the package. * @param recurse Specifies whether class from subpackages should be included. * @param classLoader The ClassLoader to use to search for and load classes. * @return the list of classes in specified package. * @throws ClassNotFoundException if the package is not found or any other error occurs. */ public static List<Class<?>> findClasses( String packageName, boolean recurse, ClassLoader classLoader ) throws ClassNotFoundException { List<URL> list = findPackageResources( packageName, classLoader ); List<Class<?>> outList = new ArrayList<>(); for( URL url : list ) { try { if( url.getProtocol().equalsIgnoreCase( "file" ) ) { searchDirForClasses( classLoader, packageName, new File( url.toURI() ), recurse, outList ); } else if( url.getProtocol().equalsIgnoreCase( "jar" ) ) { File file = getJarResourceFile( url ); searchJarForClasses( classLoader, packageName, file, recurse, outList ); } else { throw new IOException( "Unknown protocol: " + url.getProtocol() ); } } catch( URISyntaxException | IOException | NullPointerException ex ) { throw new ClassNotFoundException( "Failed to search package resource " + url, ex ); } } return outList; } /** * Finds all the classes in a resource. * <p> * Classes are not initialized when loaded. Loading is performed by the * calling thread's context class loader:<br> * {@code Thread.currentThread().getContextClassLoader()} * * @param resource URL of resource to scan. URL must represent a local directory or jar file. * @return the list of classes in specified package. * @throws ClassNotFoundException if the package is not found or any other error occurs. */ public static List<Class<?>> findClasses( URL resource ) throws ClassNotFoundException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); return findClasses( resource, loader ); } /** * Finds all the classes in a resource. * <p> * Classes are not initialized when loaded. Loading is performed by the * calling thread's context class loader:<br> * {@code Thread.currentThread().getContextClassLoader()} * * @param resource URL of resource to scan. URL must represent a local directory or jar file. * @param classLoader The ClassLoader to use to search for and load classes. * @return the list of classes in specified package. * @throws ClassNotFoundException if the package is not found or any other error occurs. */ public static List<Class<?>> findClasses( URL resource, ClassLoader classLoader ) throws ClassNotFoundException { List<Class<?>> outList = new ArrayList<>(); try { if( resource.getProtocol().equalsIgnoreCase( "file" ) ) { searchDirForClasses( classLoader, "", new File( resource.toURI() ), true, outList ); } else if( resource.getProtocol().equalsIgnoreCase( "jar" ) ) { File file = getJarResourceFile( resource ); searchJarForClasses( classLoader, "", file, true, outList ); } else { throw new IOException( "Unknown protocol: " + resource.getProtocol() ); } } catch( URISyntaxException | IOException | NullPointerException ex ) { throw new ClassNotFoundException( "Failed to search package resource " + resource, ex ); } return outList; } private static void searchDirForClasses( ClassLoader loader, String packageName, File dir, boolean recurse, List<Class<?>> outList ) throws URISyntaxException { File[] files = dir.listFiles(); if( files == null ) return; for( File f : files ) { if( f.isFile() && !f.isHidden() ) { String fileName = f.getName(); if( !fileName.toLowerCase().endsWith( ".class" ) ) continue; String className = packageName + "." + fileName.substring( 0, fileName.length() - 6 ); try { outList.add( Class.forName( className, false, loader ) ); } catch( NoClassDefFoundError | ClassNotFoundException ex ) { sLog.warning( "Failed to load class: " + className ); } } } if( recurse ) { for( File f : files ) { if( f.isDirectory() && !f.isHidden() ) { Matcher m = CLASS_PAT.matcher( f.getName() ); if( !m.matches() ) { continue; } String p = packageName; if( p.length() > 0 ) { p += "."; } p += f.getName(); searchDirForClasses( loader, p, f, true, outList ); } } } } private static void searchJarForClasses( ClassLoader loader, String packageName, File file, boolean recurse, List<Class<?>> outList ) throws IOException { String packagePath = packageName.replace( ".", File.separator ); JarFile jar = new JarFile( file ); Enumeration<JarEntry> entries = jar.entries(); while( entries.hasMoreElements() ) { String className = entries.nextElement().getName(); if( !className.startsWith( packagePath ) || !className.toLowerCase().endsWith( ".class" ) ) { continue; } if( !recurse && className.lastIndexOf( "/" ) > packagePath.length() ) { continue; } className = className.substring( 0, className.length() - 6 ).replace( File.separator, "." ); try { outList.add( Class.forName( className, false, loader ) ); } catch( NoClassDefFoundError | ClassNotFoundException ex ) { sLog.warning( "Failed to load class: " + className ); } } } private static File getJarResourceFile( URL url ) throws IOException { String jarPath = url.getPath(); if( !jarPath.startsWith( "file:" ) ) { throw new IOException( "Could not parse jar URL: " + url.toString() ); } jarPath = jarPath.substring( 5 ); int index = jarPath.indexOf( "!" ); if( index >= 0 ) { jarPath = jarPath.substring( 0, index ); } File file = new File( jarPath ); if( !file.exists() ) { throw new FileNotFoundException( "Could not parse jar URL: " + url.toString() ); } return file; } }
bsd-2-clause
camillemonchicourt/Geotrek
geotrek/common/factories.py
1280
import factory from django.contrib.contenttypes.models import ContentType from paperclip.models import Attachment from geotrek.authent.factories import UserFactory from geotrek.common.utils.testdata import get_dummy_uploaded_file from . import models class OrganismFactory(factory.Factory): FACTORY_FOR = models.Organism organism = factory.Sequence(lambda n: u"Organism %s" % n) class FileTypeFactory(factory.Factory): FACTORY_FOR = models.FileType type = factory.Sequence(lambda n: u"FileType %s" % n) class AttachmentFactory(factory.Factory): """ Create an attachment. You must provide an 'obj' keywords, the object (saved in db) to which the attachment will be bound. """ FACTORY_FOR = Attachment attachment_file = get_dummy_uploaded_file() filetype = factory.SubFactory(FileTypeFactory) creator = factory.SubFactory(UserFactory) title = factory.Sequence(u"Title {0}".format) legend = factory.Sequence(u"Legend {0}".format) # date_insert, date_update @classmethod def _prepare(cls, create, obj=None, **kwargs): kwargs['content_type'] = ContentType.objects.get_for_model(obj) kwargs['object_id'] = obj.pk return super(AttachmentFactory, cls)._prepare(create, **kwargs)
bsd-2-clause
jvehent/homebrew-core
Formula/pick.rb
938
class Pick < Formula desc "Utility to choose one option from a set of choices" homepage "https://github.com/calleerlandsson/pick" url "https://github.com/calleerlandsson/pick/releases/download/v1.5.2/pick-1.5.2.tar.gz" sha256 "183b278981233c70ac7f4d9af0728bf99d9d237e3f88d979f93fcc5968c2f789" bottle do cellar :any_skip_relocation sha256 "1506894b189eab7af6986b79615df5389b42d117150e65670e95019ce88d13ac" => :sierra sha256 "5769c0848be846f86d21bf96dfcd028f500cc65ae32aee15e7a8a15a21db9648" => :el_capitan sha256 "834a181d5579e308ecbc09aadf9104ca631ee66c82177cb42b383ce75e375f94" => :yosemite end def install ENV["TERM"] = "xterm" system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make", "check" system "make", "install" end test do system "#{bin}/pick", "-v" end end
bsd-2-clause
xranby/nifty-gui
nifty-core/src/test/java/de/lessvoid/xml/lwxs/elements/XmlProcessorElementTest.java
4004
package de.lessvoid.xml.lwxs.elements; import static org.easymock.classextension.EasyMock.createMock; import static org.easymock.classextension.EasyMock.replay; import static org.easymock.classextension.EasyMock.verify; import org.junit.After; import org.junit.Before; import org.junit.Test; import de.lessvoid.xml.lwxs.XmlType; import de.lessvoid.xml.lwxs.elements.OccursEnum; import de.lessvoid.xml.lwxs.elements.XmlProcessorElement; import de.lessvoid.xml.lwxs.elements.XmlProcessorType; import de.lessvoid.xml.xpp3.XmlParser; public class XmlProcessorElementTest { private XmlParser xmlParserMock; private XmlProcessorType xmlElementProcessorMock; @Before public void setUp() throws Exception { xmlParserMock = createMock(XmlParser.class); xmlElementProcessorMock = createMock(XmlProcessorType.class); } @After public void tearDown() { verify(xmlParserMock); verify(xmlElementProcessorMock); } @Test(expected = Exception.class) public void testElementProcessorNull() throws Exception { replay(xmlElementProcessorMock); replay(xmlParserMock); new XmlProcessorElement(null, null, null, null); } @Test(expected = Exception.class) public void testElementNameNull() throws Exception { replay(xmlElementProcessorMock); replay(xmlParserMock); new XmlProcessorElement(xmlElementProcessorMock, null, null, null); } @Test(expected = Exception.class) public void testTypeNull() throws Exception { replay(xmlElementProcessorMock); replay(xmlParserMock); new XmlProcessorElement(xmlElementProcessorMock, "name", null, null); } @Test(expected = Exception.class) public void testOccuresNull() throws Exception { replay(xmlElementProcessorMock); replay(xmlParserMock); new XmlProcessorElement(xmlElementProcessorMock, "name", "type", null); } @Test public void testOccuresRequired() throws Exception { xmlParserMock.required("name", xmlElementProcessorMock); replay(xmlParserMock); XmlType parent = createMock(XmlType.class); replay(parent); xmlElementProcessorMock.parentLinkSet(parent, "name"); replay(xmlElementProcessorMock); XmlProcessorElement child = new XmlProcessorElement(xmlElementProcessorMock, "name", "type", OccursEnum.required); child.process(xmlParserMock, parent); verify(parent); } @Test public void testOccuresOneOrMore() throws Exception { xmlParserMock.oneOrMore("name", xmlElementProcessorMock); replay(xmlParserMock); XmlType parent = createMock(XmlType.class); replay(parent); xmlElementProcessorMock.parentLinkAdd(parent, "name"); replay(xmlElementProcessorMock); XmlProcessorElement child = new XmlProcessorElement(xmlElementProcessorMock, "name", "type", OccursEnum.oneOrMore); child.process(xmlParserMock, parent); verify(parent); } @Test public void testOccuresOptional() throws Exception { xmlParserMock.optional("name", xmlElementProcessorMock); replay(xmlParserMock); XmlType parent = createMock(XmlType.class); replay(parent); xmlElementProcessorMock.parentLinkSet(parent, "name"); replay(xmlElementProcessorMock); XmlProcessorElement child = new XmlProcessorElement(xmlElementProcessorMock, "name", "type", OccursEnum.optional); child.process(xmlParserMock, parent); verify(parent); } @Test public void testOccuresZeroOrMore() throws Exception { xmlParserMock.zeroOrMore("name", xmlElementProcessorMock); replay(xmlParserMock); XmlType parent = createMock(XmlType.class); replay(parent); xmlElementProcessorMock.parentLinkAdd(parent, "name"); replay(xmlElementProcessorMock); XmlProcessorElement child = new XmlProcessorElement(xmlElementProcessorMock, "name", "type", OccursEnum.zeroOrMore); child.process(xmlParserMock, parent); verify(parent); } }
bsd-2-clause
Blei/rust-protobuf
src/protoc-gen-rust.rs
869
#![crate_type = "bin"] extern crate protobuf; use std::io::stdin; use std::io::stdout; use std::str; use plugin::*; use protobuf::parse_from_reader; use protobuf::Message; use protobuf::codegen::*; mod descriptor { pub use protobuf::descriptor::*; } mod plugin; fn main() { let req = parse_from_reader::<CodeGeneratorRequest>(&mut stdin()).unwrap(); let gen_options = GenOptions { dummy: false, }; let result = gen(req.get_proto_file(), req.get_file_to_generate(), &gen_options); let mut resp = CodeGeneratorResponse::new(); resp.set_file(result.iter().map(|file| { let mut r = CodeGeneratorResponse_File::new(); r.set_name(file.name.to_string()); r.set_content(str::from_utf8(file.content.as_ref()).unwrap().to_string()); r }).collect()); resp.write_to_writer(&mut stdout()).unwrap(); }
bsd-2-clause
GliderWinchCommons/hc
src/AddEditPanels/AddEditRunwayFrame.java
12365
package AddEditPanels; import Communications.Observer; import Configuration.UnitConversionRate; import Configuration.UnitLabelUtilities; import DataObjects.CurrentDataObjectSet; import DataObjects.Runway; import DatabaseUtilities.DatabaseDataObjectUtilities; import DatabaseUtilities.DatabaseEntryEdit; import DatabaseUtilities.DatabaseEntryIdCheck; import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.Font; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.sql.SQLException; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.border.MatteBorder; public class AddEditRunwayFrame extends JFrame { private JPanel contentPane; private JTextField magneticHeadingField; private JTextField nameField; //private JTextField altitudeField; private CurrentDataObjectSet objectSet; private Runway currentRunway; private boolean isEditEntry; private Observer parent; //private JLabel runwayAltitudeUnitsLabel = new JLabel(); //private int runwayAltitudeUnitsID; /*public void setupUnits() { runwayAltitudeUnitsID = objectSet.getCurrentProfile().getUnitSetting("runwayAltitude"); String RunwayAltitudeUnitsString = UnitLabelUtilities.lenghtUnitIndexToString(runwayAltitudeUnitsID); runwayAltitudeUnitsLabel.setText(RunwayAltitudeUnitsString); }*/ public void attach(Observer o) { parent = o; } /** * Create the frame. */ public AddEditRunwayFrame(Runway editRunway, boolean isEditEntry) { objectSet = CurrentDataObjectSet.getCurrentDataObjectSet(); //setupUnits(); if (!isEditEntry || editRunway == null){ editRunway = new Runway("", 0, "", 0, ""); } this.isEditEntry = isEditEntry; currentRunway = editRunway; setTitle("Runway"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); JPanel panel = new JPanel(); panel.setLayout(null); contentPane.add(panel, BorderLayout.CENTER); JLabel nameLabel = new JLabel("Name:"); nameLabel.setBounds(10, 14, 106, 14); panel.add(nameLabel); JLabel magneticHeadingLabel = new JLabel("Magnetic Heading:"); magneticHeadingLabel.setBounds(10, 39, 106, 14); panel.add(magneticHeadingLabel); //JLabel altitudeLabel = new JLabel("Altitude:"); //altitudeLabel.setBounds(10, 64, 106, 14); //panel.add(altitudeLabel); magneticHeadingField = new JTextField(); if (isEditEntry) { magneticHeadingField.setText(String.valueOf(currentRunway.getMagneticHeading())); } magneticHeadingField.setColumns(10); magneticHeadingField.setBounds(140, 36, 200, 20); panel.add(magneticHeadingField); nameField = new JTextField(currentRunway.getName()); nameField.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0))); nameField.setColumns(10); nameField.setBounds(140, 11, 200, 20); panel.add(nameField); /*altitudeField = new JTextField(); if (isEditEntry) { altitudeField.setText(String.valueOf(editRunway.getAltitude() * UnitConversionRate.convertDistanceUnitIndexToFactor(runwayAltitudeUnitsID))); } altitudeField.setColumns(10); altitudeField.setBounds(140, 61, 200, 20); panel.add(altitudeField);*/ JButton submitButton = new JButton("Submit"); submitButton.setBounds(0, 229, 89, 23); submitButton.setBackground(new Color(200,200,200)); panel.add(submitButton); submitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { submitData(); } }); JButton deleteButton = new JButton("Delete"); deleteButton.setEnabled(isEditEntry); deleteButton.setBounds(90, 229, 89, 23); deleteButton.setBackground(new Color(200,200,200)); panel.add(deleteButton); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { deleteCommand(); } }); JButton clearButton = new JButton("Clear"); clearButton.setBounds(180, 229, 89, 23); clearButton.setBackground(new Color(200,200,200)); panel.add(clearButton); clearButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { clearData(); } }); JButton cancelButton = new JButton("Cancel"); cancelButton.setBounds(270, 229, 89, 23); cancelButton.setBackground(new Color(200,200,200)); panel.add(cancelButton); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { dispose(); } }); JLabel requiredNoteLabel = new JLabel("All fields are required"); requiredNoteLabel.setBounds(10, 210, 200, 14); panel.add(requiredNoteLabel); JLabel parentAirfieldLabel = new JLabel(); try{ parentAirfieldLabel .setText("Parent Airfield: " + objectSet.getCurrentAirfield().getDesignator()); }catch (Exception e){ } parentAirfieldLabel.setBounds(10, 100, 220, 14); panel.add(parentAirfieldLabel); JLabel magneticHeadingUnitsLabel = new JLabel("degrees"); magneticHeadingUnitsLabel.setBounds(350, 39, 60, 14); panel.add(magneticHeadingUnitsLabel); //runwayAltitudeUnitsLabel.setBounds(350, 64, 46, 14); //panel.add(runwayAltitudeUnitsLabel); } public void deleteCommand() { try{ int choice = JOptionPane.showConfirmDialog(rootPane, "Are you sure you want to delete " + currentRunway.getId() + "?" + "\n This will also delete all glider and winch positions associated with this runway.", "Delete Runway", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (choice == 0){ DatabaseUtilities.DatabaseEntryDelete.DeleteEntry(currentRunway); objectSet.clearRunway(); JOptionPane.showMessageDialog(rootPane, currentRunway.toString() + " successfully deleted."); parent.update("2"); this.dispose(); } }catch (ClassNotFoundException e2) { JOptionPane.showMessageDialog(rootPane, "Error: No access to database currently. Please try again later.", "Error", JOptionPane.INFORMATION_MESSAGE); }catch (Exception e3) { } } public void clearData(){ nameField.setText(""); magneticHeadingField.setText(""); //altitudeField.setText(""); nameField.setBackground(Color.WHITE); magneticHeadingField.setBackground(Color.WHITE); //altitudeField.setBackground(Color.WHITE); } protected void submitData(){ if (isComplete()){ String name = nameField.getText(); float magneticHeading = Float.parseFloat(magneticHeadingField.getText()); //float altitude = Float.parseFloat(altitudeField.getText()) / UnitConversionRate.convertDistanceUnitIndexToFactor(runwayAltitudeUnitsID); String parentAirfield = ""; String parentId = ""; try{ parentAirfield = objectSet.getCurrentAirfield().getDesignator(); parentId = objectSet.getCurrentAirfield().getId(); }catch (Exception e){ } Runway newRunway = new Runway(name, magneticHeading, parentAirfield, 0, ""); newRunway.setId(currentRunway.getId()); newRunway.setParentId(parentId); try{ objectSet.setCurrentRunway(newRunway); Object[] options = {"One-time Launch", "Save to Database"}; int choice = JOptionPane.showOptionDialog(rootPane, "Do you want to use this Runway for a one-time launch or save it to the database?", "", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); System.out.println(choice); if (choice == 0){ parent.update("2"); this.dispose(); } else { if (isEditEntry){ DatabaseEntryEdit.UpdateEntry(newRunway); } else{ Random randomId = new Random(); newRunway.setId(String.valueOf(randomId.nextInt(100000000))); while (DatabaseEntryIdCheck.IdCheck(newRunway)){ newRunway.setId(String.valueOf(randomId.nextInt(100000000))); } DatabaseUtilities.DatabaseDataObjectUtilities.addRunwayToDB(newRunway); } parent.update("2"); this.dispose(); } }catch(SQLException e1) { if(e1.getErrorCode() == 30000){ System.out.println(e1.getMessage()); JOptionPane.showMessageDialog(rootPane, "Sorry, but the runway " + newRunway.toString() + " already exists in the database", "Error", JOptionPane.INFORMATION_MESSAGE); } }catch (ClassNotFoundException e2) { JOptionPane.showMessageDialog(rootPane, "Error: No access to database currently. Please try again later.", "Error", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e3) { } } } public boolean isComplete() { try { boolean emptyFields = false; String name = nameField.getText(); String magneticHeading = magneticHeadingField.getText(); //String altitude = altitudeField.getText(); nameField.setBackground(Color.WHITE); magneticHeadingField.setBackground(Color.WHITE); //altitudeField.setBackground(Color.WHITE); if(name.isEmpty()) { nameField.setBackground(Color.PINK); emptyFields = true; } if(magneticHeading.isEmpty()) { magneticHeadingField.setBackground(Color.PINK); emptyFields = true; } /*if(altitude.isEmpty()) { altitudeField.setBackground(Color.PINK); emptyFields = true; }*/ if (emptyFields){ throw new Exception(""); } Float.parseFloat(magneticHeading); //Float.parseFloat(altitude); }catch(NumberFormatException e){ JOptionPane.showMessageDialog(rootPane, "Please input correct numerical values", "Error", JOptionPane.INFORMATION_MESSAGE); //ew = new ErrWindow("Please input correct numerical values"); return false; }catch(Exception e){ JOptionPane.showMessageDialog(rootPane, "Please complete all required fields\n" + e.getMessage(), "Error", JOptionPane.INFORMATION_MESSAGE); //ew = new ErrWindow("Please complete all required fields\n" + e.getMessage()); return false; } return true; } }
bsd-2-clause
godenji/slaq
src/main/scala/slaq/scalaquery/meta/MTable.scala
1622
package slaq.meta import slaq.{ResultSetInvoker, UnitInvoker} /** * A wrapper for a row in the ResultSet returned by DatabaseMetaData.getTables(). */ case class MTable( name: MQName, tableType: String, remarks: String, typeName: Option[MQName], selfRefColName: Option[String], refGen: Option[String] ) { def getColumns = MColumn.getColumns(name, "%") def getPrimaryKeys = MPrimaryKey.getPrimaryKeys(name) def getImportedKeys = MForeignKey.getImportedKeys(name) def getExportedKeys = MForeignKey.getExportedKeys(name) def getVersionColumns = MVersionColumn.getVersionColumns(name) def getTablePrivileges = MTablePrivilege.getTablePrivileges(name) def getBestRowIdentifier(scope: MBestRowIdentifierColumn.Scope, nullable: Boolean = false) = MBestRowIdentifierColumn.getBestRowIdentifier(name, scope, nullable) def getIndexInfo(unique: Boolean = false, approximate: Boolean = false) = MIndexInfo.getIndexInfo(name, unique, approximate) } object MTable { def getTables(cat: Option[String], schemaPattern: Option[String], namePattern: Option[String], types: Option[Seq[String]]) = ResultSetInvoker[MTable]( _.metaData.getTables(cat.orNull, schemaPattern.orNull, namePattern.orNull, types.map(_.toArray).orNull) ) { r => if (r.numColumns > 5) MTable(MQName.from(r), r<<, r<<, MQName.optionalFrom(r), r<<, r<<) else MTable(MQName.from(r), r<<, r<<, None, None, None) } def getTables(namePattern: String): UnitInvoker[MTable] = getTables(Some(""), Some(""), Some(namePattern), None) def getTables: UnitInvoker[MTable] = getTables(Some(""), Some(""), None, None) }
bsd-2-clause
osroom/osroom
apps/utils/format/obj_format.py
2640
#!/usr/bin/env python # -*-coding:utf-8-*- # @Time : 2017/11/1 ~ 2019/9/1 # @Author : Allen Woo import json import sys import regex as re from pymongo.cursor import Cursor def objid_to_str(datas, fields=["_id"]): """ mongodb ObjectId to str :param datas: :param field: :return: """ if isinstance(datas, (list, Cursor)): _datas = [] for data in datas: for field in fields: data[field] = str(data[field]) _datas.append(data) return _datas else: datas_keys = datas.keys() for field in fields: if field in datas_keys: datas[field] = str(datas[field]) return datas def json_to_pyseq(tjson): """ json to python sequencer :param json: :return: """ if tjson in [None, "None"]: return None elif not isinstance(tjson, (list, dict, tuple)) and tjson != "": if isinstance(tjson, (str, bytes)) and tjson[0] not in ["{", "[", "("]: return tjson elif isinstance(tjson, (int, float)): return tjson try: tjson = json.loads(tjson) except BaseException: tjson = eval(tjson) else: if isinstance(tjson, str): tjson = eval(tjson) return tjson def pyseq_to_json(pyseq): if isinstance(pyseq, tuple): pyseq = list(pyseq) if isinstance(pyseq, (dict, list)): try: pyseq = json.dumps(pyseq) except TypeError: if isinstance(pyseq, list): pyseq = list(pyseq) pyseq = json.dumps(pyseq) else: for k, v in pyseq.items(): if isinstance(v, list): pyseq[k] = list(v) pyseq = json.dumps(pyseq) return pyseq def str_to_num(string, type=int): """ 字符串转数字 :param string: 字符串 :param type: 转变方法(obj) :return: """ try: return type(string) except BaseException: if string: return 1 elif not string or string.lower() == "false": return 0 class ConfDictToClass(object): def __init__(self, config, key=None): if not isinstance(config, dict): print("[ERROR]:Must be a dictionary") sys.exit(-1) if key == "value": for k, v in config.items(): if not re.search(r"^__.*__$", k): self.__dict__[k] = v["value"] else: for k, v in config.items(): self.__dict__[k] = v
bsd-2-clause
white-lab/pyproteome
tests/motif_enrichment_test.py
7462
from unittest import TestCase import pandas as pd from pyproteome import motif FOREGROUND = ''' KQTDLELsPLTKEEK SLSTKRSsPDDGNDV DVSPYSLsPVSNKSQ SSRDRWIsENQDSAD ARRNDDIsELEDLSE ISELEDLsELEDLKD TAFGREHsPYGPSPL EHSPYGPsPLGWPSS EHSPYGPsPLGWPSS SYDPYDFsDTEEEMP SYDPYDFsDTEEEMP EEMPQVHtPKTADSQ SKSDLRKsPVFSDED LRKSPVFsDEDSDLD PVFSDEDsDLDFDIS EDENGDItPIKAKKM DDDLVEFsDLESEDD VEFSDLEsEDDERPR KLTDEDFsPFGSGGG TAADMYLsPVRSPKK MYLSPVRsPKKKGST REKEAVItPVASATQ KGSTLDLsDLEAEKL STEDGDGtDDFLTDK DGTDDFLtDKEDEKA ''' BACKGROUND = ''' KKMPLDLsPLATPII SSPAQNWtPPQPRTL PIRSSAFsPLGGCTP FFRQRMFsPMEEKEL DINTFVGtPVEKLDL GKKTKFAsDDEHDEH QEALDYFsDKESGKQ PDKQFLIsPPASPPV FLISPPAsPPVGWKQ HDDFFSTtPLQHQRI GEDEFVPsDGLDKDE DEIFYTLsPVNGKIT DELFYTLsPINGKIS GKQPLLLsEDEEDTK PPGDYSTtPGGTLFS GGTLFSTtPGGTRII PGGTLFStTPGGTRI GGTLFSTtPGGTRII LPHDYCTtPGGTLFS GGTLFSTtPGGTRII IDDDFFPsSGEEAEA DDDFFPSsGEEAEAA KQTDLELsPLTKEEK ASELACPtPKEDGLA TDSSSYPsPCASPSP SYPSPCAsPSPPSSG DVSPYSLsPVSNKSQ SLSTKRSsPDDGNDV DVSPYSLsPVSNKSQ SSRDRWIsENQDSAD NDIYNFFsPLNPVRV ARRNDDIsELEDLSE ARRNDDIsELEDLSE ISELEDLsELEDLKD ASRYYVPsYEEVMNT GEDGLILtPLGRYQI APEVWGLsPKNPEPD DVEDMELsDVEDDGS SEDGQVFsPKKGQKK KEHRGCDsPDPDTSY PDTSYVLtPHTEEKY TAFGREHsPYGPSPL EHSPYGPsPLGWPSS EHSPYGPsPLGWPSS GHRELVLsSPEDLTQ HRELVLSsPEDLTQD RSVNFSLtPNEIKVS EQYGFLTtPTKQLGA KSDISPLtPRESSPL PLTPRESsPLYSPTF RESSPLYsPTFSDST SYDPYDFsDTEEEMP SYDPYDFsDTEEEMP EEMPQVHtPKTADSQ SKSDLRKsPVFSDED LRKSPVFsDEDSDLD PVFSDEDsDLDFDIS EDENGDItPIKAKKM RLPPKVEsLESLYFT SLESLYFtPIPARSQ LNNSNLFsPVNRDSE RDSENLAsPSEYPEN KKEQMPLtPPRFDHD DDDLVEFsDLESEDD VEFSDLEsEDDERPR STRRGTFsDQELDAQ YPAVNRFsPSPRNSP AVNRFSPsPRNSPRP KDEILPTtPISEQKG KLTDEDFsPFGSGGG RPQDSEFsPVDNCLQ DRSSGTAsSVAFTPL TASSVAFtPLQGLEI GEEPSEYtDEEDTKD GEEPTVYsDEEEPKD VLIVYELtPTAEQKA TEDIFPVtPPELEET TAADMYLsPVRSPKK MYLSPVRsPKKKGST REKEAVItPVASATQ DPQQLQLsPLKGLSL GGKRSRLtPVSPESS GGKRSRLtPVSPESS RSRLTPVsPESSSTE LRNPYLLsEEEDDDV VVRRRSFsISPVRLR RRRSFSIsPVRLRRS DRGEFSAsPMLKSGM EHKELSNsPLRENSF LRENSFGsPLEFRNS KGSTLDLsDLEAEKL DGTDDFLtDKEDEKA STEDGDGtDDFLTDK DGTDDFLtDKEDEKA EEWDPEYtPKSKKYY ''' OUTPUT = ''' | .....D.x....... | 8 / 25 | 10 / 95 | 2.73E-04 | | .....-.x....... | 12 / 25 | 20 / 95 | 3.27E-04 | | .....-.s....... | 10 / 25 | 15 / 95 | 3.98E-04 | | .....-.x-...... | 8 / 25 | 11 / 95 | 8.24E-04 | | .....-.s....E.. | 5 / 25 | 5 / 95 | 9.17E-04 | | ..-..D.x....... | 5 / 25 | 5 / 95 | 9.17E-04 | | .....-.s-.-.... | 7 / 25 | 9 / 95 | 1.05E-03 | | .....-.s....-.. | 6 / 25 | 7 / 95 | 1.17E-03 | | .....D.x-...... | 6 / 25 | 7 / 95 | 1.17E-03 | | .......x-...... | 12 / 25 | 23 / 95 | 2.09E-03 | | .....D.s....... | 6 / 25 | 8 / 95 | 3.80E-03 | | .....-.s-.E.... | 6 / 25 | 8 / 95 | 3.80E-03 | | ..-..-.x....... | 6 / 25 | 8 / 95 | 3.80E-03 | | .....-.xD...... | 6 / 25 | 8 / 95 | 3.80E-03 | | .....-.sD.E.E.. | 4 / 25 | 4 / 95 | 3.97E-03 | | .....-.s.L..-.. | 4 / 25 | 4 / 95 | 3.97E-03 | | .......sD.-.-O. | 4 / 25 | 4 / 95 | 3.97E-03 | | ..-..D.x-...... | 4 / 25 | 4 / 95 | 3.97E-03 | | .....D.xD...... | 4 / 25 | 4 / 95 | 3.97E-03 | | ...-...xP..S... | 4 / 25 | 4 / 95 | 3.97E-03 | | .....D.s-.E.... | 5 / 25 | 6 / 95 | 4.48E-03 | | .....-.sD.-.-.. | 5 / 25 | 6 / 95 | 4.48E-03 | | .....-.s-L-.... | 5 / 25 | 6 / 95 | 4.48E-03 | | .......xD.E.E.. | 5 / 25 | 6 / 95 | 4.48E-03 | | .......s-...... | 10 / 25 | 19 / 95 | 5.81E-03 | | .......xD.-.-.. | 7 / 25 | 11 / 95 | 6.47E-03 | | .....-.s.L..... | 6 / 25 | 9 / 95 | 9.30E-03 | | .......s-.-.... | 9 / 25 | 17 / 95 | 9.30E-03 | | .......sD.-.-.. | 6 / 25 | 9 / 95 | 9.30E-03 | | ....-..x....... | 6 / 25 | 9 / 95 | 9.30E-03 | | .......x-.-.... | 10 / 25 | 20 / 95 | 9.60E-03 | ''' class MotifEnrichmentFullTest(TestCase): ''' Test pyproteome.motif.motif_enrichment using a full data set, provided by Brian Joughin. Compares the results to those produced by his set of perl scripts. ''' def setUp(self): self.foreground = [ i.strip() for i in FOREGROUND.split('\n') if i.strip() ] self.background = [ i.strip() for i in BACKGROUND.split('\n') if i.strip() ] self.output = [] for line in OUTPUT.split('\n'): line = line.strip() if not line: continue tokens = line.split('|') m = motif.Motif(tokens[1].strip()) fore_hits = int(tokens[2].split('/')[0]) fore_size = int(tokens[2].split('/')[1]) back_hits = int(tokens[3].split('/')[0]) back_size = int(tokens[3].split('/')[1]) p_val = float(tokens[4]) self.output.append( ( m, fore_hits, fore_size, back_hits, back_size, p_val, ) ) self.output = pd.DataFrame( data=self.output, columns=[ 'Motif', 'Foreground Hits', 'Foreground Size', 'Background Hits', 'Background Size', 'p-value', ], ) # Re-sort as the p-values on Brian's tables are truncated a bit short. self.output['sort-p-value'] = pd.Series( [ motif._motif_sig( row['Foreground Hits'], row['Foreground Size'], row['Background Hits'], row['Background Size'], ) for _, row in self.output.iterrows() ], index=self.output.index, ) self.output.sort_values(by=['sort-p-value', 'Motif'], inplace=True) self.output.reset_index(drop=True) def test_motif_enrichment(self): hits = motif.motif_enrichment( self.foreground, self.background, )[0] true_positives = list(self.output['Motif']) true_hits = list(hits['Motif']) # Check for false positives for m in true_hits: self.assertIn(m, true_positives) # Check for false-negatives for m in true_positives: self.assertIn(m, true_hits) # Check every row of output is the same for calc_row, out_row in zip(hits.iterrows(), self.output.iterrows()): _, calc_row = calc_row _, out_row = out_row self.assertEqual( calc_row['Motif'], out_row['Motif'], ) self.assertEqual( calc_row['Foreground Hits'], out_row['Foreground Hits'], ) self.assertEqual( calc_row['Foreground Size'], out_row['Foreground Size'], ) self.assertEqual( calc_row['Background Hits'], out_row['Background Hits'], ) self.assertEqual( calc_row['Background Size'], out_row['Background Size'], ) self.assertLess( abs(calc_row['p-value'] - out_row['p-value']), 0.001, )
bsd-2-clause
angr/angr
angr/procedures/definitions/win32_api-ms-win-appmodel-runtime-l1-1-3.py
3002
# pylint:disable=line-too-long import logging from ...sim_type import SimTypeFunction, SimTypeShort, SimTypeInt, SimTypeLong, SimTypeLongLong, SimTypeDouble, SimTypeFloat, SimTypePointer, SimTypeChar, SimStruct, SimTypeFixedSizeArray, SimTypeBottom, SimUnion, SimTypeBool from ...calling_conventions import SimCCStdcall, SimCCMicrosoftAMD64 from .. import SIM_PROCEDURES as P from . import SimLibrary _l = logging.getLogger(name=__name__) lib = SimLibrary() lib.set_default_cc('X86', SimCCStdcall) lib.set_default_cc('AMD64', SimCCMicrosoftAMD64) lib.set_library_names("api-ms-win-appmodel-runtime-l1-1-3.dll") prototypes = \ { # 'GetPackagePathByFullName2': SimTypeFunction([SimTypePointer(SimTypeChar(label="Char"), offset=0), SimTypeInt(signed=False, label="PackagePathType"), SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0), SimTypePointer(SimTypeChar(label="Char"), label="LPArray", offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["packageFullName", "packagePathType", "pathLength", "path"]), # 'GetStagedPackagePathByFullName2': SimTypeFunction([SimTypePointer(SimTypeChar(label="Char"), offset=0), SimTypeInt(signed=False, label="PackagePathType"), SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0), SimTypePointer(SimTypeChar(label="Char"), label="LPArray", offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["packageFullName", "packagePathType", "pathLength", "path"]), # 'GetCurrentPackageInfo2': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypeInt(signed=False, label="PackagePathType"), SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["flags", "packagePathType", "bufferLength", "buffer", "count"]), # 'GetCurrentPackagePath2': SimTypeFunction([SimTypeInt(signed=False, label="PackagePathType"), SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0), SimTypePointer(SimTypeChar(label="Char"), label="LPArray", offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["packagePathType", "pathLength", "path"]), # 'GetPackageInfo2': SimTypeFunction([SimTypePointer(SimStruct({"reserved": SimTypePointer(SimTypeBottom(label="Void"), offset=0)}, name="_PACKAGE_INFO_REFERENCE", pack=False, align=None), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypeInt(signed=False, label="PackagePathType"), SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["packageInfoReference", "flags", "packagePathType", "bufferLength", "buffer", "count"]), } lib.set_prototypes(prototypes)
bsd-2-clause
textamina/scriban
src/Scriban/Syntax/ScriptRewriter.cs
1960
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. #nullable disable using System.Collections.Generic; namespace Scriban.Syntax { /// <summary> /// Base class for a script rewriter. /// </summary> #if SCRIBAN_PUBLIC public #else internal #endif abstract partial class ScriptRewriter : ScriptVisitor<ScriptNode> { protected ScriptRewriter() { CopyTrivias = true; } public bool CopyTrivias { get; set; } public override ScriptNode Visit(ScriptNode node) { if (node == null) return null; var newNode = node.Accept(this); newNode.Span = node.Span; if (CopyTrivias && !ReferenceEquals(node, newNode) && node is IScriptTerminal nodeTerminal && newNode is IScriptTerminal newNodeTerminal) { newNodeTerminal.Trivias = nodeTerminal.Trivias; } return newNode; } public override ScriptNode Visit(ScriptVariableGlobal node) { return new ScriptVariableGlobal(node.BaseName); } public override ScriptNode Visit(ScriptVariableLocal node) { return new ScriptVariableLocal(node.BaseName); } public override ScriptNode Visit(ScriptVariableLoop node) { return new ScriptVariableLoop(node.BaseName); } protected ScriptList<TNode> VisitAll<TNode>(ScriptList<TNode> nodes) where TNode : ScriptNode { if (nodes == null) return null; var newNodes = new ScriptList<TNode>(); foreach (var node in nodes) { var newNode = (TNode) Visit(node); newNodes.Add(newNode); } return newNodes; } } }
bsd-2-clause
lattera/jaild
classes/Service.php
2353
<?php /* Copyright (c) 2013, Shawn Webb 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ class Service { public $path; public $jail; public static function Load($jail) { global $db; $services = array(); $results = $db->Query("SELECT * FROM jailadmin_services WHERE jail = :jail", array(":jail" => $jail->name)); foreach ($results as $record) $services[] = Service::LoadFromRecord($jail, $record); return $services; } public static function LoadFromRecord($jail, $record=array()) { $service = new Service; $service->path = $record['path']; $service->jail = $jail; return $service; } public function Create() { global $db; return $db->Execute("INSERT INTO jailadmin_services (path, jail) VALUES (:path, :jail)", array(":path" => $this->path, ":jail" => $this->jail->name)); } public function Delete() { global $db; return $db->Execute("DELETE FROM jailadmin_services WHERE jail = :jail AND path = :path", array(":jail" => $this->jail->name, ":path" => $this->path)); } }
bsd-2-clause