code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * Copyright 2014-2019 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.lightsail.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Describes the source of a CloudFormation stack record (i.e., the export snapshot record). * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CloudFormationStackRecordSourceInfo" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CloudFormationStackRecordSourceInfo implements Serializable, Cloneable, StructuredPojo { /** * <p> * The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>). * </p> */ private String resourceType; /** * <p> * The name of the record. * </p> */ private String name; /** * <p> * The Amazon Resource Name (ARN) of the export snapshot record. * </p> */ private String arn; /** * <p> * The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>). * </p> * * @param resourceType * The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>). * @see CloudFormationStackRecordSourceType */ public void setResourceType(String resourceType) { this.resourceType = resourceType; } /** * <p> * The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>). * </p> * * @return The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>). * @see CloudFormationStackRecordSourceType */ public String getResourceType() { return this.resourceType; } /** * <p> * The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>). * </p> * * @param resourceType * The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>). * @return Returns a reference to this object so that method calls can be chained together. * @see CloudFormationStackRecordSourceType */ public CloudFormationStackRecordSourceInfo withResourceType(String resourceType) { setResourceType(resourceType); return this; } /** * <p> * The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>). * </p> * * @param resourceType * The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>). * @return Returns a reference to this object so that method calls can be chained together. * @see CloudFormationStackRecordSourceType */ public CloudFormationStackRecordSourceInfo withResourceType(CloudFormationStackRecordSourceType resourceType) { this.resourceType = resourceType.toString(); return this; } /** * <p> * The name of the record. * </p> * * @param name * The name of the record. */ public void setName(String name) { this.name = name; } /** * <p> * The name of the record. * </p> * * @return The name of the record. */ public String getName() { return this.name; } /** * <p> * The name of the record. * </p> * * @param name * The name of the record. * @return Returns a reference to this object so that method calls can be chained together. */ public CloudFormationStackRecordSourceInfo withName(String name) { setName(name); return this; } /** * <p> * The Amazon Resource Name (ARN) of the export snapshot record. * </p> * * @param arn * The Amazon Resource Name (ARN) of the export snapshot record. */ public void setArn(String arn) { this.arn = arn; } /** * <p> * The Amazon Resource Name (ARN) of the export snapshot record. * </p> * * @return The Amazon Resource Name (ARN) of the export snapshot record. */ public String getArn() { return this.arn; } /** * <p> * The Amazon Resource Name (ARN) of the export snapshot record. * </p> * * @param arn * The Amazon Resource Name (ARN) of the export snapshot record. * @return Returns a reference to this object so that method calls can be chained together. */ public CloudFormationStackRecordSourceInfo withArn(String arn) { setArn(arn); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getResourceType() != null) sb.append("ResourceType: ").append(getResourceType()).append(","); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getArn() != null) sb.append("Arn: ").append(getArn()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CloudFormationStackRecordSourceInfo == false) return false; CloudFormationStackRecordSourceInfo other = (CloudFormationStackRecordSourceInfo) obj; if (other.getResourceType() == null ^ this.getResourceType() == null) return false; if (other.getResourceType() != null && other.getResourceType().equals(this.getResourceType()) == false) return false; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getArn() == null ^ this.getArn() == null) return false; if (other.getArn() != null && other.getArn().equals(this.getArn()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getResourceType() == null) ? 0 : getResourceType().hashCode()); hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode()); return hashCode; } @Override public CloudFormationStackRecordSourceInfo clone() { try { return (CloudFormationStackRecordSourceInfo) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.lightsail.model.transform.CloudFormationStackRecordSourceInfoMarshaller.getInstance().marshall(this, protocolMarshaller); } }
jentfoo/aws-sdk-java
aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/CloudFormationStackRecordSourceInfo.java
Java
apache-2.0
8,005
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.common; import org.apache.rocketmq.common.annotation.ImportantField; import org.apache.rocketmq.common.constant.PermName; import org.apache.rocketmq.remoting.common.RemotingUtil; import java.net.InetAddress; import java.net.UnknownHostException; public class BrokerConfig { private String rocketmqHome = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV)); @ImportantField private String namesrvAddr = System.getProperty(MixAll.NAMESRV_ADDR_PROPERTY, System.getenv(MixAll.NAMESRV_ADDR_ENV)); @ImportantField private String brokerIP1 = RemotingUtil.getLocalAddress(); private String brokerIP2 = RemotingUtil.getLocalAddress(); @ImportantField private String brokerName = localHostName(); @ImportantField private String brokerClusterName = "DefaultCluster"; @ImportantField private long brokerId = MixAll.MASTER_ID; /** * Broker 权限(读写等) */ private int brokerPermission = PermName.PERM_READ | PermName.PERM_WRITE; private int defaultTopicQueueNums = 8; @ImportantField private boolean autoCreateTopicEnable = true; private boolean clusterTopicEnable = true; private boolean brokerTopicEnable = true; @ImportantField private boolean autoCreateSubscriptionGroup = true; private String messageStorePlugIn = ""; private int sendMessageThreadPoolNums = 1; //16 + Runtime.getRuntime().availableProcessors() * 4; private int pullMessageThreadPoolNums = 16 + Runtime.getRuntime().availableProcessors() * 2; private int adminBrokerThreadPoolNums = 16; private int clientManageThreadPoolNums = 32; private int consumerManageThreadPoolNums = 32; private int flushConsumerOffsetInterval = 1000 * 5; private int flushConsumerOffsetHistoryInterval = 1000 * 60; @ImportantField private boolean rejectTransactionMessage = false; @ImportantField private boolean fetchNamesrvAddrByAddressServer = false; private int sendThreadPoolQueueCapacity = 10000; private int pullThreadPoolQueueCapacity = 100000; private int clientManagerThreadPoolQueueCapacity = 1000000; private int consumerManagerThreadPoolQueueCapacity = 1000000; private int filterServerNums = 0; private boolean longPollingEnable = true; private long shortPollingTimeMills = 1000; private boolean notifyConsumerIdsChangedEnable = true; private boolean highSpeedMode = false; private boolean commercialEnable = true; private int commercialTimerCount = 1; private int commercialTransCount = 1; private int commercialBigCount = 1; private int commercialBaseCount = 1; private boolean transferMsgByHeap = true; private int maxDelayTime = 40; // TODO 疑问:这个是干啥的 private String regionId = MixAll.DEFAULT_TRACE_REGION_ID; private int registerBrokerTimeoutMills = 6000; private boolean slaveReadEnable = false; private boolean disableConsumeIfConsumerReadSlowly = false; private long consumerFallbehindThreshold = 1024L * 1024 * 1024 * 16; private long waitTimeMillsInSendQueue = 200; /** * 开始接收请求时间 * TODO 疑问:什么时候设置的 */ private long startAcceptSendRequestTimeStamp = 0L; private boolean traceOn = true; public static String localHostName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { e.printStackTrace(); } return "DEFAULT_BROKER"; } public boolean isTraceOn() { return traceOn; } public void setTraceOn(final boolean traceOn) { this.traceOn = traceOn; } public long getStartAcceptSendRequestTimeStamp() { return startAcceptSendRequestTimeStamp; } public void setStartAcceptSendRequestTimeStamp(final long startAcceptSendRequestTimeStamp) { this.startAcceptSendRequestTimeStamp = startAcceptSendRequestTimeStamp; } public long getWaitTimeMillsInSendQueue() { return waitTimeMillsInSendQueue; } public void setWaitTimeMillsInSendQueue(final long waitTimeMillsInSendQueue) { this.waitTimeMillsInSendQueue = waitTimeMillsInSendQueue; } public long getConsumerFallbehindThreshold() { return consumerFallbehindThreshold; } public void setConsumerFallbehindThreshold(final long consumerFallbehindThreshold) { this.consumerFallbehindThreshold = consumerFallbehindThreshold; } public boolean isDisableConsumeIfConsumerReadSlowly() { return disableConsumeIfConsumerReadSlowly; } public void setDisableConsumeIfConsumerReadSlowly(final boolean disableConsumeIfConsumerReadSlowly) { this.disableConsumeIfConsumerReadSlowly = disableConsumeIfConsumerReadSlowly; } public boolean isSlaveReadEnable() { return slaveReadEnable; } public void setSlaveReadEnable(final boolean slaveReadEnable) { this.slaveReadEnable = slaveReadEnable; } public int getRegisterBrokerTimeoutMills() { return registerBrokerTimeoutMills; } public void setRegisterBrokerTimeoutMills(final int registerBrokerTimeoutMills) { this.registerBrokerTimeoutMills = registerBrokerTimeoutMills; } public String getRegionId() { return regionId; } public void setRegionId(final String regionId) { this.regionId = regionId; } public boolean isTransferMsgByHeap() { return transferMsgByHeap; } public void setTransferMsgByHeap(final boolean transferMsgByHeap) { this.transferMsgByHeap = transferMsgByHeap; } public String getMessageStorePlugIn() { return messageStorePlugIn; } public void setMessageStorePlugIn(String messageStorePlugIn) { this.messageStorePlugIn = messageStorePlugIn; } public boolean isHighSpeedMode() { return highSpeedMode; } public void setHighSpeedMode(final boolean highSpeedMode) { this.highSpeedMode = highSpeedMode; } public String getRocketmqHome() { return rocketmqHome; } public void setRocketmqHome(String rocketmqHome) { this.rocketmqHome = rocketmqHome; } public String getBrokerName() { return brokerName; } public void setBrokerName(String brokerName) { this.brokerName = brokerName; } public int getBrokerPermission() { return brokerPermission; } public void setBrokerPermission(int brokerPermission) { this.brokerPermission = brokerPermission; } public int getDefaultTopicQueueNums() { return defaultTopicQueueNums; } public void setDefaultTopicQueueNums(int defaultTopicQueueNums) { this.defaultTopicQueueNums = defaultTopicQueueNums; } public boolean isAutoCreateTopicEnable() { return autoCreateTopicEnable; } public void setAutoCreateTopicEnable(boolean autoCreateTopic) { this.autoCreateTopicEnable = autoCreateTopic; } public String getBrokerClusterName() { return brokerClusterName; } public void setBrokerClusterName(String brokerClusterName) { this.brokerClusterName = brokerClusterName; } public String getBrokerIP1() { return brokerIP1; } public void setBrokerIP1(String brokerIP1) { this.brokerIP1 = brokerIP1; } public String getBrokerIP2() { return brokerIP2; } public void setBrokerIP2(String brokerIP2) { this.brokerIP2 = brokerIP2; } public int getSendMessageThreadPoolNums() { return sendMessageThreadPoolNums; } public void setSendMessageThreadPoolNums(int sendMessageThreadPoolNums) { this.sendMessageThreadPoolNums = sendMessageThreadPoolNums; } public int getPullMessageThreadPoolNums() { return pullMessageThreadPoolNums; } public void setPullMessageThreadPoolNums(int pullMessageThreadPoolNums) { this.pullMessageThreadPoolNums = pullMessageThreadPoolNums; } public int getAdminBrokerThreadPoolNums() { return adminBrokerThreadPoolNums; } public void setAdminBrokerThreadPoolNums(int adminBrokerThreadPoolNums) { this.adminBrokerThreadPoolNums = adminBrokerThreadPoolNums; } public int getFlushConsumerOffsetInterval() { return flushConsumerOffsetInterval; } public void setFlushConsumerOffsetInterval(int flushConsumerOffsetInterval) { this.flushConsumerOffsetInterval = flushConsumerOffsetInterval; } public int getFlushConsumerOffsetHistoryInterval() { return flushConsumerOffsetHistoryInterval; } public void setFlushConsumerOffsetHistoryInterval(int flushConsumerOffsetHistoryInterval) { this.flushConsumerOffsetHistoryInterval = flushConsumerOffsetHistoryInterval; } public boolean isClusterTopicEnable() { return clusterTopicEnable; } public void setClusterTopicEnable(boolean clusterTopicEnable) { this.clusterTopicEnable = clusterTopicEnable; } public String getNamesrvAddr() { return namesrvAddr; } public void setNamesrvAddr(String namesrvAddr) { this.namesrvAddr = namesrvAddr; } public long getBrokerId() { return brokerId; } public void setBrokerId(long brokerId) { this.brokerId = brokerId; } public boolean isAutoCreateSubscriptionGroup() { return autoCreateSubscriptionGroup; } public void setAutoCreateSubscriptionGroup(boolean autoCreateSubscriptionGroup) { this.autoCreateSubscriptionGroup = autoCreateSubscriptionGroup; } public boolean isRejectTransactionMessage() { return rejectTransactionMessage; } public void setRejectTransactionMessage(boolean rejectTransactionMessage) { this.rejectTransactionMessage = rejectTransactionMessage; } public boolean isFetchNamesrvAddrByAddressServer() { return fetchNamesrvAddrByAddressServer; } public void setFetchNamesrvAddrByAddressServer(boolean fetchNamesrvAddrByAddressServer) { this.fetchNamesrvAddrByAddressServer = fetchNamesrvAddrByAddressServer; } public int getSendThreadPoolQueueCapacity() { return sendThreadPoolQueueCapacity; } public void setSendThreadPoolQueueCapacity(int sendThreadPoolQueueCapacity) { this.sendThreadPoolQueueCapacity = sendThreadPoolQueueCapacity; } public int getPullThreadPoolQueueCapacity() { return pullThreadPoolQueueCapacity; } public void setPullThreadPoolQueueCapacity(int pullThreadPoolQueueCapacity) { this.pullThreadPoolQueueCapacity = pullThreadPoolQueueCapacity; } public boolean isBrokerTopicEnable() { return brokerTopicEnable; } public void setBrokerTopicEnable(boolean brokerTopicEnable) { this.brokerTopicEnable = brokerTopicEnable; } public int getFilterServerNums() { return filterServerNums; } public void setFilterServerNums(int filterServerNums) { this.filterServerNums = filterServerNums; } public boolean isLongPollingEnable() { return longPollingEnable; } public void setLongPollingEnable(boolean longPollingEnable) { this.longPollingEnable = longPollingEnable; } public boolean isNotifyConsumerIdsChangedEnable() { return notifyConsumerIdsChangedEnable; } public void setNotifyConsumerIdsChangedEnable(boolean notifyConsumerIdsChangedEnable) { this.notifyConsumerIdsChangedEnable = notifyConsumerIdsChangedEnable; } public long getShortPollingTimeMills() { return shortPollingTimeMills; } public void setShortPollingTimeMills(long shortPollingTimeMills) { this.shortPollingTimeMills = shortPollingTimeMills; } public int getClientManageThreadPoolNums() { return clientManageThreadPoolNums; } public void setClientManageThreadPoolNums(int clientManageThreadPoolNums) { this.clientManageThreadPoolNums = clientManageThreadPoolNums; } public boolean isCommercialEnable() { return commercialEnable; } public void setCommercialEnable(final boolean commercialEnable) { this.commercialEnable = commercialEnable; } public int getCommercialTimerCount() { return commercialTimerCount; } public void setCommercialTimerCount(final int commercialTimerCount) { this.commercialTimerCount = commercialTimerCount; } public int getCommercialTransCount() { return commercialTransCount; } public void setCommercialTransCount(final int commercialTransCount) { this.commercialTransCount = commercialTransCount; } public int getCommercialBigCount() { return commercialBigCount; } public void setCommercialBigCount(final int commercialBigCount) { this.commercialBigCount = commercialBigCount; } public int getMaxDelayTime() { return maxDelayTime; } public void setMaxDelayTime(final int maxDelayTime) { this.maxDelayTime = maxDelayTime; } public int getClientManagerThreadPoolQueueCapacity() { return clientManagerThreadPoolQueueCapacity; } public void setClientManagerThreadPoolQueueCapacity(int clientManagerThreadPoolQueueCapacity) { this.clientManagerThreadPoolQueueCapacity = clientManagerThreadPoolQueueCapacity; } public int getConsumerManagerThreadPoolQueueCapacity() { return consumerManagerThreadPoolQueueCapacity; } public void setConsumerManagerThreadPoolQueueCapacity(int consumerManagerThreadPoolQueueCapacity) { this.consumerManagerThreadPoolQueueCapacity = consumerManagerThreadPoolQueueCapacity; } public int getConsumerManageThreadPoolNums() { return consumerManageThreadPoolNums; } public void setConsumerManageThreadPoolNums(int consumerManageThreadPoolNums) { this.consumerManageThreadPoolNums = consumerManageThreadPoolNums; } public int getCommercialBaseCount() { return commercialBaseCount; } public void setCommercialBaseCount(int commercialBaseCount) { this.commercialBaseCount = commercialBaseCount; } }
Coneboy-k/incubator-rocketmq
common/src/main/java/org/apache/rocketmq/common/BrokerConfig.java
Java
apache-2.0
15,205
package command import ( "github.com/goodmustache/pt/actor" "github.com/goodmustache/pt/command/display" ) //counterfeiter:generate . ProjectListActor type ProjectListActor interface { Projects() ([]actor.Project, error) } type ProjectList struct { UserID uint64 `short:"u" long:"user-id" description:"User ID to run commands with"` Actor ProjectListActor UI UI } func (cmd ProjectList) Execute(_ []string) error { projects, err := cmd.Actor.Projects() if err != nil { return err } displayProjects := make([]display.ProjectRow, 0, len(projects)) for _, project := range projects { displayProjects = append(displayProjects, display.ProjectRow{ ID: project.ID, Name: project.Name, Description: project.Description, Visibility: project.Visibility(), }) } cmd.UI.PrintTable(displayProjects) return nil }
goodmustache/pt
command/project_list.go
GO
apache-2.0
860
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_06) on Fri May 05 14:52:10 PDT 2006 --> <TITLE> Uses of Class org.apache.hadoop.record.compiler.JFile (Hadoop 0.2.0 API) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Class org.apache.hadoop.record.compiler.JFile (Hadoop 0.2.0 API)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/hadoop/record/compiler//class-useJFile.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="JFile.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.hadoop.record.compiler.JFile</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler">JFile</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.hadoop.record.compiler.generated"><B>org.apache.hadoop.record.compiler.generated</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.hadoop.record.compiler.generated"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler">JFile</A> in <A HREF="../../../../../../org/apache/hadoop/record/compiler/generated/package-summary.html">org.apache.hadoop.record.compiler.generated</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/hadoop/record/compiler/generated/package-summary.html">org.apache.hadoop.record.compiler.generated</A> that return <A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler">JFile</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler">JFile</A></CODE></FONT></TD> <TD><CODE><B>Rcc.</B><B><A HREF="../../../../../../org/apache/hadoop/record/compiler/generated/Rcc.html#Include()">Include</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler">JFile</A></CODE></FONT></TD> <TD><CODE><B>Rcc.</B><B><A HREF="../../../../../../org/apache/hadoop/record/compiler/generated/Rcc.html#Input()">Input</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/hadoop/record/compiler//class-useJFile.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="JFile.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &copy; 2006 The Apache Software Foundation </BODY> </HTML>
moreus/hadoop
hadoop-0.2.0/docs/api/org/apache/hadoop/record/compiler/class-use/JFile.html
HTML
apache-2.0
8,468
/* * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.product.index; import static com.opengamma.strata.collect.TestHelper.assertSerialization; import static com.opengamma.strata.collect.TestHelper.coverBeanEquals; import static com.opengamma.strata.collect.TestHelper.coverImmutableBean; import static com.opengamma.strata.collect.TestHelper.date; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.data.Offset.offset; import java.time.LocalDate; import java.util.Optional; import org.junit.jupiter.api.Test; import com.opengamma.strata.basics.ReferenceData; import com.opengamma.strata.basics.currency.Currency; import com.opengamma.strata.product.PortfolioItemSummary; import com.opengamma.strata.product.PortfolioItemType; import com.opengamma.strata.product.ProductType; import com.opengamma.strata.product.TradeInfo; import com.opengamma.strata.product.TradedPrice; /** * Test {@link IborFutureTrade}. */ public class IborFutureTradeTest { private static final ReferenceData REF_DATA = ReferenceData.standard(); private static final LocalDate TRADE_DATE = date(2015, 3, 18); private static final TradeInfo TRADE_INFO = TradeInfo.of(TRADE_DATE); private static final IborFuture PRODUCT = IborFutureTest.sut(); private static final IborFuture PRODUCT2 = IborFutureTest.sut2(); private static final double QUANTITY = 35; private static final double QUANTITY2 = 36; private static final double PRICE = 0.99; private static final double PRICE2 = 0.98; //------------------------------------------------------------------------- @Test public void test_builder() { IborFutureTrade test = sut(); assertThat(test.getInfo()).isEqualTo(TRADE_INFO); assertThat(test.getProduct()).isEqualTo(PRODUCT); assertThat(test.getPrice()).isEqualTo(PRICE); assertThat(test.getQuantity()).isEqualTo(QUANTITY); assertThat(test.withInfo(TRADE_INFO).getInfo()).isEqualTo(TRADE_INFO); assertThat(test.withQuantity(0.9129).getQuantity()).isCloseTo(0.9129d, offset(1e-10)); assertThat(test.withPrice(0.9129).getPrice()).isCloseTo(0.9129d, offset(1e-10)); } @Test public void test_builder_badPrice() { assertThatIllegalArgumentException() .isThrownBy(() -> sut().toBuilder().price(2.1).build()); } //------------------------------------------------------------------------- @Test public void test_summarize() { IborFutureTrade trade = sut(); PortfolioItemSummary expected = PortfolioItemSummary.builder() .id(TRADE_INFO.getId().orElse(null)) .portfolioItemType(PortfolioItemType.TRADE) .productType(ProductType.IBOR_FUTURE) .currencies(Currency.USD) .description("IborFuture x 35") .build(); assertThat(trade.summarize()).isEqualTo(expected); } //------------------------------------------------------------------------- @Test public void test_resolve() { IborFutureTrade test = sut(); ResolvedIborFutureTrade resolved = test.resolve(REF_DATA); assertThat(resolved.getInfo()).isEqualTo(TRADE_INFO); assertThat(resolved.getProduct()).isEqualTo(PRODUCT.resolve(REF_DATA)); assertThat(resolved.getQuantity()).isEqualTo(QUANTITY); assertThat(resolved.getTradedPrice()).isEqualTo(Optional.of(TradedPrice.of(TRADE_DATE, PRICE))); } //------------------------------------------------------------------------- @Test public void test_withQuantity() { IborFutureTrade base = sut(); double quantity = 65243; IborFutureTrade computed = base.withQuantity(quantity); IborFutureTrade expected = IborFutureTrade.builder() .info(TRADE_INFO) .product(PRODUCT) .quantity(quantity) .price(PRICE) .build(); assertThat(computed).isEqualTo(expected); } @Test public void test_withPrice() { IborFutureTrade base = sut(); double price = 0.95; IborFutureTrade computed = base.withPrice(price); IborFutureTrade expected = IborFutureTrade.builder() .info(TRADE_INFO) .product(PRODUCT) .quantity(QUANTITY) .price(price) .build(); assertThat(computed).isEqualTo(expected); } //------------------------------------------------------------------------- @Test public void coverage() { coverImmutableBean(sut()); coverBeanEquals(sut(), sut2()); } @Test public void test_serialization() { assertSerialization(sut()); } //------------------------------------------------------------------------- static IborFutureTrade sut() { return IborFutureTrade.builder() .info(TRADE_INFO) .product(PRODUCT) .quantity(QUANTITY) .price(PRICE) .build(); } static IborFutureTrade sut2() { return IborFutureTrade.builder() .product(PRODUCT2) .quantity(QUANTITY2) .price(PRICE2) .build(); } }
OpenGamma/Strata
modules/product/src/test/java/com/opengamma/strata/product/index/IborFutureTradeTest.java
Java
apache-2.0
5,092
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * 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 debop4k.redisson.spring.cache; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.inject.Inject; import static org.assertj.core.api.Assertions.assertThat; /** * @author [email protected] */ @RunWith(SpringRunner.class) @SpringBootTest(classes = {RedissonCacheConfiguration.class}) public class RedissonCacheTest { @Inject UserRepository userRepo; @Test public void testConfiguration() { assertThat(userRepo).isNotNull(); } @Test public void testNull() { userRepo.save("user1", null); assertThat(userRepo.getNull("user1")).isNull(); userRepo.remove("user1"); assertThat(userRepo.getNull("user1")).isNull(); } @Test public void testRemove() { userRepo.save("user1", UserRepository.UserObject.of("name1", "value1")); assertThat(userRepo.get("user1")) .isNotNull() .isInstanceOf(UserRepository.UserObject.class); userRepo.remove("user1"); assertThat(userRepo.getNull("user1")).isNull(); } @Test public void testPutGet() { userRepo.save("user1", UserRepository.UserObject.of("name1", "value1")); UserRepository.UserObject u = userRepo.get("user1"); assertThat(u).isNotNull(); assertThat(u.getName()).isEqualTo("name1"); assertThat(u.getValue()).isEqualTo("value1"); } @Test(expected = IllegalStateException.class) public void testGet() { userRepo.get("notExists"); } }
debop/debop4k
debop4k-redis/src/test/java/debop4k/redisson/spring/cache/RedissonCacheTest.java
Java
apache-2.0
2,169
#!/usr/bin/env perl # Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute # Copyright [2016-2021] EMBL-European Bioinformatics Institute # # 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. use strict; use warnings; use Bio::EnsEMBL::Registry; use Getopt::Long qw(:config pass_through); my $species; my $version; my $host; my $user; my $dbname; my $display_name; my $source; my $show_links; my $ret = Getopt::Long::GetOptions ('dbname=s' => \$dbname, 'species=s' => \$species, 'host=s' => \$host, 'user=s' => \$user, 'version=s' => \$version, 'name=s' => \$display_name, 'source=s' => \$source, 'show_links' => \$show_links, 'help' => sub {usage(); exit(0); } ); if(!defined $host){ $host = "ensembldb.ensembl.org"; $user = "anonymous"; } if(defined $dbname){ if(!defined $species){ $species = "no_eye_deer"; } Bio::EnsEMBL::DBSQL::DBAdaptor->new( -user => $user, -dbname => $dbname, -host => $host, -species => $species, -group => "core"); } elsif(defined $version){ Bio::EnsEMBL::Registry->load_registry_from_db( -host => $host, -user => $user, -db_version => $version); } else{ Bio::EnsEMBL::Registry->load_registry_from_db( -host => $host, -user => $user); } if(defined $display_name){ specific_example($display_name, $source); } #elsif(defined $display_name){ # die "must specify source if using -name option\n"; #} my $adap = Bio::EnsEMBL::Registry->get_adaptor($species,"core","gene"); if(!defined $adap){ die "Could not get adaptor for $species\n"; } my $dbi = $adap->dbc(); # General my $gen_sql =(<<'GEN'); SELECT e.db_name, x.info_type, count(*) FROM xref x, external_db e WHERE x.external_db_id = e.external_db_id GROUP BY e.db_name, x.info_type GEN my %big_hash; my $gen_sth = $dbi->prepare($gen_sql); my ($name, $type, $count); $gen_sth->execute(); $gen_sth->bind_columns(\$name, \$type, \$count); while($gen_sth->fetch){ $type ||= "GeneBuilder"; $big_hash{$name}{$type} = $count; } $gen_sth->finish; # dependent xrefs my $dependent_sql =(<<'DEP'); SELECT master.db_name, dependent.db_name, count(1) FROM xref as xd, xref as xm, external_db as master, external_db as dependent, dependent_xref dx WHERE dx.dependent_xref_id = xd.xref_id AND dx.master_xref_id = xm.xref_id AND xm.external_db_id = master.external_db_id AND xd.external_db_id = dependent.external_db_id GROUP BY master.db_name, dependent.db_name DEP my $dep_sth = $dbi->prepare($dependent_sql); $dep_sth->execute(); my ($master, $dependent); $dep_sth->bind_columns(\$master, \$dependent, \$count); my %dependents; while($dep_sth->fetch()){ $dependents{$dependent}{$master} = $count; } $dep_sth->finish; foreach my $dbname (sort keys %big_hash){ foreach my $info_type (keys %{$big_hash{$dbname}}){ print "$dbname\t$info_type\t".$big_hash{$dbname}{$info_type}."\n"; if($info_type eq "DEPENDENT"){ foreach my $master_db (keys %{$dependents{$dbname}} ){ print "\tvia $master_db\t".$dependents{$dbname}{$master_db}."\n"; } } } } sub specific_example { my ($search_name, $source_name) = @_; my $db_adap = Bio::EnsEMBL::Registry->get_adaptor($species,"core","dbentry"); my $gene_adap = Bio::EnsEMBL::Registry->get_adaptor($species,"core","gene"); my $dbentrys = $db_adap->fetch_all_by_name($search_name, $source_name); my $found = 0; foreach my $dbentry (@$dbentrys){ $found = 1; print "##############################\ndbname :".$dbentry->db_display_name."\n"; print "accession is: ".$dbentry->primary_id."\n"; print "display id: ".$dbentry->display_id."\n"; print "info type: ".$dbentry->info_type."\n"; if($dbentry->info_type =~ /DEPENDENT/ms){ my @masters = @{$dbentry->get_all_masters()}; foreach my $entry (@masters){ print "\tMaster: ".$entry->db_display_name." : ".$entry->primary_id."\n"; } } if(defined $dbentry->info_text){ print "info text: ".$dbentry->info_text."\n"; } if($show_links && !($dbentry->info_type =~ /UNMAPPED/ms)){ print "Linked to the following genes: "; foreach my $gene (@{$gene_adap->fetch_all_by_external_name($dbentry->primary_id, $dbentry->dbname)}){ print $gene->stable_id." "; } print "\n"; } print "##############################\n"; } if(!$found){ if(defined $source_name){ print "$search_name NOT FOUND for $source_name\n"; } else{ print "$search_name NOT FOUND\n"; } } exit(0); } sub usage { print << 'EOF'; This script will report where external database references come from and give numbers for each of these. If a name is given, information about only those ones are given. Options -species The species you want to look at. This MUST be set unless you use dbname -dbname The database you want data on. -user The user to use to read the core database in ro mode (default anonymous) -host The mysql server (default ensembldb.ensembl.org) -version Can be used to change the version of the database to be examined. -name Get data for this display_label/name. -source the source name for the accession (i.e. HGNC, MGI, RefSeq_mRNA) -show_links If name used then show which ensembl objects is is linked to. A typical run would be to see what xrefs are there for human :- perl xref_data_analysis.pl -species human this would generate a list of the number of xrefs for the human database on ensembldb.ensembl.org that matches the API version you are running. If you want to look at the 64 version and you are not using the 64 API :- perl xref_data_analysis.pl -species human -version 64 If you want to look at a test database perl xref_data_analysis.pl -dbname ianl_human_core_65 -host ens-research -user ro To find how a partcular xref was mapped use -name to specify this and -source if more than one xref may have the same accession e.g. how was accession BRCA2 in HGNC mapped to ensembl and to which genes perl xref_data_analysis.pl -species human -name BRCA2 -source HGNC -show_links EOF return; }
Ensembl/ensembl
misc-scripts/xref_mapping/xref_data_analysis.pl
Perl
apache-2.0
7,089
from django_filters.rest_framework import DjangoFilterBackend from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rdmo.core.exports import XMLResponse from rdmo.core.permissions import HasModelPermission from rdmo.core.views import ChoicesViewSet from rdmo.core.viewsets import CopyModelMixin from .models import Condition from .renderers import ConditionRenderer from .serializers.export import ConditionExportSerializer from .serializers.v1 import ConditionIndexSerializer, ConditionSerializer class ConditionViewSet(CopyModelMixin, ModelViewSet): permission_classes = (HasModelPermission, ) queryset = Condition.objects.select_related('source', 'target_option') \ .prefetch_related('optionsets', 'questionsets', 'questions', 'tasks') serializer_class = ConditionSerializer filter_backends = (DjangoFilterBackend,) filterset_fields = ( 'uri', 'key', 'source', 'relation', 'target_text', 'target_option' ) @action(detail=False) def index(self, request): queryset = Condition.objects.select_related('source', 'target_option') serializer = ConditionIndexSerializer(queryset, many=True) return Response(serializer.data) @action(detail=False, permission_classes=[HasModelPermission]) def export(self, request): serializer = ConditionExportSerializer(self.get_queryset(), many=True) xml = ConditionRenderer().render(serializer.data) return XMLResponse(xml, name='conditions') @action(detail=True, url_path='export', permission_classes=[HasModelPermission]) def detail_export(self, request, pk=None): serializer = ConditionExportSerializer(self.get_object()) xml = ConditionRenderer().render([serializer.data]) return XMLResponse(xml, name=self.get_object().key) class RelationViewSet(ChoicesViewSet): permission_classes = (IsAuthenticated, ) queryset = Condition.RELATION_CHOICES
rdmorganiser/rdmo
rdmo/conditions/viewsets.py
Python
apache-2.0
2,141
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.redis.internal; import java.io.IOException; import java.net.URL; import java.util.Collection; import org.apache.geode.distributed.internal.DistributedSystemService; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.internal.InternalDataSerializer; import org.apache.geode.internal.classloader.ClassPathLoader; public class RedisDistributedSystemService implements DistributedSystemService { @Override public void init(InternalDistributedSystem internalDistributedSystem) { } @Override public Class getInterface() { return getClass(); } @Override public Collection<String> getSerializationAcceptlist() throws IOException { URL sanctionedSerializables = ClassPathLoader.getLatest().getResource(getClass(), "sanctioned-geode-apis-compatible-with-redis-serializables.txt"); return InternalDataSerializer.loadClassNames(sanctionedSerializables); } }
masaki-yamakawa/geode
geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/RedisDistributedSystemService.java
Java
apache-2.0
1,750
/* * Copyright 2014 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 leap.lang.meta; import leap.lang.Named; import leap.lang.Titled; public interface MNamed extends MObject,Named,Titled { }
leapframework/framework
base/lang/src/main/java/leap/lang/meta/MNamed.java
Java
apache-2.0
748
package com.vladmihalcea.book.hpjp.hibernate.type.array; import org.hibernate.dialect.PostgreSQL95Dialect; import java.sql.Types; /** * @author Vlad Mihalcea */ public class PostgreSQL95ArrayDialect extends PostgreSQL95Dialect { public PostgreSQL95ArrayDialect() { super(); this.registerColumnType(Types.ARRAY, "array"); } }
vladmihalcea/high-performance-java-persistence
core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/type/array/PostgreSQL95ArrayDialect.java
Java
apache-2.0
355
require_dependency 'libraetd/lib/serviceclient/user_info_client' require_dependency 'libraetd/lib/helpers/user_info' require_dependency 'libraetd/lib/serviceclient/entity_id_client' module Helpers class EtdHelper def self.process_inbound_sis_authorization( deposit_authorization ) # lookup the user and create their account as necessary user, _ = lookup_or_create_user( deposit_authorization.who ) if user.nil? return false end # determine if this is an update to an existing work work_source = "#{GenericWork::THESIS_SOURCE_SIS}:#{deposit_authorization.id}" existing = find_existing_work( work_source ) if existing.present? puts "INFO: found existing work for this authorization (#{deposit_authorization.id})" # only apply updates to draft works if existing.is_draft? before = existing.title.present? ? existing.title[ 0 ] : '' if deposit_authorization.title != before existing.title = [ deposit_authorization.title ] existing.save! puts "INFO: updated work #{existing.id} title from: '#{before}' to '#{deposit_authorization.title}'" end return true else puts "ERROR: SIS update for a published work (#{existing.id}); ignoring" return false end end ok = true w = GenericWork.create!( title: [ deposit_authorization.title ] ) do |w| # generic work attributes w.apply_depositor_metadata( user ) w.creator = user.email w.author_email = user.email w.author_first_name = deposit_authorization.first_name w.author_last_name = deposit_authorization.last_name w.author_institution = GenericWork::DEFAULT_INSTITUTION w.date_created = CurationConcerns::TimeService.time_in_utc.strftime( "%Y-%m-%d" ) w.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC w.embargo_state = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC w.visibility_during_embargo = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC w.work_type = GenericWork::WORK_TYPE_THESIS w.draft = 'true' w.publisher = GenericWork::DEFAULT_PUBLISHER w.department = deposit_authorization.department w.degree = deposit_authorization.degree w.language = GenericWork::DEFAULT_LANGUAGE w.license = GenericWork::DEFAULT_LICENSE # where the authorization comes from w.work_source = work_source end status, id = ServiceClient::EntityIdClient.instance.newid( w ) if ServiceClient::EntityIdClient.instance.ok?( status ) && id.present? w.identifier = id w.permanent_url = GenericWork.doi_url( id ) else puts "ERROR: cannot mint DOI (#{status}). Using public view" w.identifier = nil w.permanent_url = Rails.application.routes.url_helpers.public_view_url( w ) end ok = w.save # send the email if necessary ThesisMailers.sis_thesis_can_be_submitted( user.email, user.display_name, MAIL_SENDER ).deliver_later if ok return ok end def self.process_inbound_optional_authorization( deposit_request ) # lookup the user and create their account as necessary user, extended_info = lookup_or_create_user( deposit_request.who ) if user.nil? return false end # default values default_title = 'Enter your title here' ok = true w = GenericWork.create!( title: [ default_title ] ) do |w| # generic work attributes w.apply_depositor_metadata( user ) w.creator = user.email w.author_email = user.email w.author_first_name = extended_info.first_name || 'First name' w.author_last_name = extended_info.last_name || 'Last name' w.author_institution = GenericWork::DEFAULT_INSTITUTION w.date_created = CurationConcerns::TimeService.time_in_utc.strftime( "%Y-%m-%d" ) w.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC w.visibility_during_embargo = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC w.embargo_state = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC w.work_type = GenericWork::WORK_TYPE_THESIS w.draft = 'true' w.publisher = GenericWork::DEFAULT_PUBLISHER w.department = deposit_request.department w.degree = deposit_request.degree w.language = GenericWork::DEFAULT_LANGUAGE w.license = GenericWork::DEFAULT_LICENSE # where the authorization comes from w.work_source = "#{GenericWork::THESIS_SOURCE_OPTIONAL}:#{deposit_request.id}" # who requested it w.registrar_computing_id = deposit_request.requester unless deposit_request.requester.nil? end status, id = ServiceClient::EntityIdClient.instance.newid( w ) if ServiceClient::EntityIdClient.instance.ok?( status ) && id.present? w.identifier = id w.permanent_url = GenericWork.doi_url( id ) else puts "ERROR: cannot mint DOI (#{status}). Using public view" w.permanent_url = Rails.application.routes.url_helpers.public_view_url( w ) end ok = w.save ThesisMailers.optional_thesis_can_be_submitted( user.email, user.display_name, MAIL_SENDER ).deliver_later if ok return ok end private # # look for a work that corresponds to the specified work source. This tells us that we have # previously created a placeholder ETD for the student # def self.find_existing_work( work_source ) works = GenericWork.where( {work_source: work_source } ) if works.present? return works.first end return nil end def self.lookup_or_create_user( cid ) # lookup the user by computing id user_info = lookup_user( cid ) if user_info.nil? puts "ERROR: cannot locate user info for #{cid}" return nil, nil end # locate the user and create the account if we cannot... cant create an ETD without an owner email = user_info.email email = User.email_from_cid( user_info.id ) if email.nil? || email.blank? user = User.find_by_email( email ) user = create_user( user_info, email ) if user.nil? return user, user_info end def self.create_user( user_info, email ) default_password = 'password' user = User.new( email: email, password: default_password, password_confirmation: default_password, display_name: user_info.display_name, department: user_info.department.first, office: user_info.office, telephone: user_info.phone, title: user_info.description ) user.save! puts "INFO: created new account for #{user_info.id}" return( user ) end def self.lookup_user( id ) status, resp = ServiceClient::UserInfoClient.instance.get_by_id( id ) if ServiceClient::UserInfoClient.instance.ok?( status ) return Helpers::UserInfo.create( resp ) end return nil end end end # # end of file #
uvalib/Libra2
lib/libraetd/lib/helpers/etd_helper.rb
Ruby
apache-2.0
7,345
#!/usr/bin/env python from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals 'fbcode_builder steps to build Facebook Thrift' import specs.fbthrift as fbthrift def fbcode_builder_spec(builder): return { 'depends_on': [fbthrift], } config = { 'github_project': 'facebook/fbthrift', 'fbcode_builder_spec': fbcode_builder_spec, }
getyourguide/fbthrift
build/fbcode_builder_config.py
Python
apache-2.0
449
package grammar.model.nouns; import grammar.model.Multiplicity; import grammar.model.PseudoEnum; import grammar.model.SubjectGender; import grammar.util.Utilities; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Noun implements PseudoEnum<Noun> { private static final Map<String, Noun> INSTANCE_MAP = new HashMap<String, Noun>(); private static final Set<Noun> INSTANCES = new HashSet<Noun>(); private static int sequenceGenerator = 0; private final int sequence; private final Map<NounClass, Map<Multiplicity, NounForm>> formMap = new HashMap<NounClass, Map<Multiplicity, NounForm>>(); private final Set<NounForm> formSet; private final Set<NounTag> classifications; public Noun(Set<NounForm> forms, Set<NounTag> classifications) { for (NounForm form : forms) { for (NounClass nc : form.getNounClasses()) { Map<Multiplicity, NounForm> ms = Utilities.initialiseIfReqd(nc, formMap); ms.put(form.getMultiplicity(), form); } form.setNoun(this); } sequence = sequenceGenerator++; this.formSet = forms; this.classifications = classifications; INSTANCE_MAP.put(toString(), this); INSTANCES.add(this); } public Set<NounForm> getForms() { return formSet; } public boolean isRegular() { for (NounForm form : formSet) { if (!form.isRegular()) return false; } return true; } public int ordinal() { return sequence; } public int compareTo(Noun o) { return ordinal() - o.ordinal(); } public static Noun[] values() { return INSTANCES.toArray(new Noun[]{}); } public static Noun valueOf(String key) { Noun m = INSTANCE_MAP.get(key); if (m == null) throw new IllegalArgumentException("No such Noun: '"+key+"'."); return m; } public String getText(SubjectGender subjectGender, Multiplicity multiplicity) { NounClass nc = mapSubjectGenderToNounClass(subjectGender); Map<Multiplicity, NounForm> multiplicities = formMap.get(nc); if (multiplicities == null) multiplicities = formMap.values().iterator().next(); NounForm form = multiplicities.get(multiplicity); if (form != null) return form.getText(); if (multiplicity.equals(Multiplicity.PLURAL)) { form = multiplicities.get(Multiplicity.SINGULAR); return form + (form.getText().endsWith("s") ? "es" : "s"); // TODO this should come from some xml somewhere... } else // singular requested; only a plural form exists throw new IllegalArgumentException("No singular form exists for noun "+getText(subjectGender, Multiplicity.PLURAL)+"."); } public String toString() { try { return getText(SubjectGender.MASCULINE, Multiplicity.SINGULAR); } catch (IllegalArgumentException iae) { return getText(SubjectGender.MASCULINE, Multiplicity.PLURAL); } } public NounClass getNounClass(SubjectGender subjectGender) { NounClass nc = mapSubjectGenderToNounClass(subjectGender); if (formMap.keySet().contains(nc)) return nc; return formMap.keySet().iterator().next(); } private static NounClass mapSubjectGenderToNounClass(SubjectGender subjectGender) { NounClass nc; if (subjectGender.equals(SubjectGender.MASCULINE)) // TODO mapping is specific to french... nc = NounClass.valueOf("MASCULINE"); else if (subjectGender.equals(SubjectGender.FEMININE)) nc = NounClass.valueOf("FEMININE"); else nc = null; return nc; } public Set<NounTag> getClassifications() { return classifications; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + sequence; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Noun)) return false; final Noun other = (Noun) obj; if (sequence != other.sequence) return false; return true; } }
dliroberts/lang
RomanceConjugator/src/main/java/grammar/model/nouns/Noun.java
Java
apache-2.0
3,873
/* * Copyright 2012-2017 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.route53domains.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/route53domains-2014-05-15/EnableDomainAutoRenew" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class EnableDomainAutoRenewResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof EnableDomainAutoRenewResult == false) return false; EnableDomainAutoRenewResult other = (EnableDomainAutoRenewResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public EnableDomainAutoRenewResult clone() { try { return (EnableDomainAutoRenewResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
dagnir/aws-sdk-java
aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53domains/model/EnableDomainAutoRenewResult.java
Java
apache-2.0
2,301
/* * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.powermock.api.mockito.repackaged.asm.tree; import org.powermock.api.mockito.repackaged.asm.AnnotationVisitor; import org.powermock.api.mockito.repackaged.asm.Attribute; import org.powermock.api.mockito.repackaged.asm.ClassVisitor; import org.powermock.api.mockito.repackaged.asm.Label; import org.powermock.api.mockito.repackaged.asm.MethodVisitor; import org.powermock.api.mockito.repackaged.asm.Opcodes; import org.powermock.api.mockito.repackaged.asm.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * A node that represents a method. * * @author Eric Bruneton */ public class MethodNode extends MemberNode implements MethodVisitor { /** * The method's access flags (see {@link Opcodes}). This field also * indicates if the method is synthetic and/or deprecated. */ public int access; /** * The method's name. */ public String name; /** * The method's descriptor (see {@link Type}). */ public String desc; /** * The method's signature. May be <tt>null</tt>. */ public String signature; /** * The internal names of the method's exception classes (see * {@link Type#getInternalName() getInternalName}). This list is a list of * {@link String} objects. */ public List exceptions; /** * The default value of this annotation interface method. This field must be * a {@link Byte}, {@link Boolean}, {@link Character}, {@link Short}, * {@link Integer}, {@link Long}, {@link Float}, {@link Double}, * {@link String} or {@link Type}, or an two elements String array (for * enumeration values), a {@link AnnotationNode}, or a {@link List} of * values of one of the preceding types. May be <tt>null</tt>. */ public Object annotationDefault; /** * The runtime visible parameter annotations of this method. These lists are * lists of {@link AnnotationNode} objects. May be <tt>null</tt>. * * @associates org.powermock.api.mockito.repackaged.asm.tree.AnnotationNode * @label invisible parameters */ public List[] visibleParameterAnnotations; /** * The runtime invisible parameter annotations of this method. These lists * are lists of {@link AnnotationNode} objects. May be <tt>null</tt>. * * @associates org.powermock.api.mockito.repackaged.asm.tree.AnnotationNode * @label visible parameters */ public List[] invisibleParameterAnnotations; /** * The instructions of this method. This list is a list of * {@link AbstractInsnNode} objects. * * @associates org.powermock.api.mockito.repackaged.asm.tree.AbstractInsnNode * @label instructions */ public InsnList instructions; /** * The try catch blocks of this method. This list is a list of * {@link TryCatchBlockNode} objects. * * @associates org.powermock.api.mockito.repackaged.asm.tree.TryCatchBlockNode */ public List tryCatchBlocks; /** * The maximum stack size of this method. */ public int maxStack; /** * The maximum number of local variables of this method. */ public int maxLocals; /** * The local variables of this method. This list is a list of * {@link LocalVariableNode} objects. May be <tt>null</tt> * * @associates org.powermock.api.mockito.repackaged.asm.tree.LocalVariableNode */ public List localVariables; /** * Constructs an unitialized . */ public MethodNode() { this.instructions = new InsnList(); } /** * Constructs a new . * * @param access the method's access flags (see {@link Opcodes}). This * parameter also indicates if the method is synthetic and/or * deprecated. * @param name the method's name. * @param desc the method's descriptor (see {@link Type}). * @param signature the method's signature. May be <tt>null</tt>. * @param exceptions the internal names of the method's exception classes * (see {@link Type#getInternalName() getInternalName}). May be * <tt>null</tt>. */ public MethodNode( final int access, final String name, final String desc, final String signature, final String[] exceptions) { this(); this.access = access; this.name = name; this.desc = desc; this.signature = signature; this.exceptions = new ArrayList(exceptions == null ? 0 : exceptions.length); boolean isAbstract = (access & Opcodes.ACC_ABSTRACT) != 0; if (!isAbstract) { this.localVariables = new ArrayList(5); } this.tryCatchBlocks = new ArrayList(); if (exceptions != null) { this.exceptions.addAll(Arrays.asList(exceptions)); } } // ------------------------------------------------------------------------ // Implementation of the MethodVisitor interface // ------------------------------------------------------------------------ public AnnotationVisitor visitAnnotationDefault() { return new AnnotationNode(new ArrayList(0) { public boolean add(final Object o) { annotationDefault = o; return super.add(o); } }); } public AnnotationVisitor visitParameterAnnotation( final int parameter, final String desc, final boolean visible) { AnnotationNode an = new AnnotationNode(desc); if (visible) { if (visibleParameterAnnotations == null) { int params = Type.getArgumentTypes(this.desc).length; visibleParameterAnnotations = new List[params]; } if (visibleParameterAnnotations[parameter] == null) { visibleParameterAnnotations[parameter] = new ArrayList(1); } visibleParameterAnnotations[parameter].add(an); } else { if (invisibleParameterAnnotations == null) { int params = Type.getArgumentTypes(this.desc).length; invisibleParameterAnnotations = new List[params]; } if (invisibleParameterAnnotations[parameter] == null) { invisibleParameterAnnotations[parameter] = new ArrayList(1); } invisibleParameterAnnotations[parameter].add(an); } return an; } public void visitCode() { } public void visitFrame( final int type, final int nLocal, final Object[] local, final int nStack, final Object[] stack) { instructions.add(new FrameNode(type, nLocal, local == null ? null : getLabelNodes(local), nStack, stack == null ? null : getLabelNodes(stack))); } public void visitInsn(final int opcode) { instructions.add(new InsnNode(opcode)); } public void visitIntInsn(final int opcode, final int operand) { instructions.add(new IntInsnNode(opcode, operand)); } public void visitVarInsn(final int opcode, final int var) { instructions.add(new VarInsnNode(opcode, var)); } public void visitTypeInsn(final int opcode, final String type) { instructions.add(new TypeInsnNode(opcode, type)); } public void visitFieldInsn( final int opcode, final String owner, final String name, final String desc) { instructions.add(new FieldInsnNode(opcode, owner, name, desc)); } public void visitMethodInsn( final int opcode, final String owner, final String name, final String desc) { instructions.add(new MethodInsnNode(opcode, owner, name, desc)); } public void visitJumpInsn(final int opcode, final Label label) { instructions.add(new JumpInsnNode(opcode, getLabelNode(label))); } public void visitLabel(final Label label) { instructions.add(getLabelNode(label)); } public void visitLdcInsn(final Object cst) { instructions.add(new LdcInsnNode(cst)); } public void visitIincInsn(final int var, final int increment) { instructions.add(new IincInsnNode(var, increment)); } public void visitTableSwitchInsn( final int min, final int max, final Label dflt, final Label[] labels) { instructions.add(new TableSwitchInsnNode(min, max, getLabelNode(dflt), getLabelNodes(labels))); } public void visitLookupSwitchInsn( final Label dflt, final int[] keys, final Label[] labels) { instructions.add(new LookupSwitchInsnNode(getLabelNode(dflt), keys, getLabelNodes(labels))); } public void visitMultiANewArrayInsn(final String desc, final int dims) { instructions.add(new MultiANewArrayInsnNode(desc, dims)); } public void visitTryCatchBlock( final Label start, final Label end, final Label handler, final String type) { tryCatchBlocks.add(new TryCatchBlockNode(getLabelNode(start), getLabelNode(end), getLabelNode(handler), type)); } public void visitLocalVariable( final String name, final String desc, final String signature, final Label start, final Label end, final int index) { localVariables.add(new LocalVariableNode(name, desc, signature, getLabelNode(start), getLabelNode(end), index)); } public void visitLineNumber(final int line, final Label start) { instructions.add(new LineNumberNode(line, getLabelNode(start))); } public void visitMaxs(final int maxStack, final int maxLocals) { this.maxStack = maxStack; this.maxLocals = maxLocals; } /** * Returns the LabelNode corresponding to the given Label. Creates a new * LabelNode if necessary. The default implementation of this method uses * the {@link Label#info} field to store associations between labels and * label nodes. * * @param l a Label. * @return the LabelNode corresponding to l. */ protected LabelNode getLabelNode(final Label l) { if (!(l.info instanceof LabelNode)) { l.info = new LabelNode(l); } return (LabelNode) l.info; } private LabelNode[] getLabelNodes(final Label[] l) { LabelNode[] nodes = new LabelNode[l.length]; for (int i = 0; i < l.length; ++i) { nodes[i] = getLabelNode(l[i]); } return nodes; } private Object[] getLabelNodes(final Object[] objs) { Object[] nodes = new Object[objs.length]; for (int i = 0; i < objs.length; ++i) { Object o = objs[i]; if (o instanceof Label) { o = getLabelNode((Label) o); } nodes[i] = o; } return nodes; } // ------------------------------------------------------------------------ // Accept method // ------------------------------------------------------------------------ /** * Makes the given class visitor visit this method. * * @param cv a class visitor. */ public void accept(final ClassVisitor cv) { String[] exceptions = new String[this.exceptions.size()]; this.exceptions.toArray(exceptions); MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions); if (mv != null) { accept(mv); } } /** * Makes the given method visitor visit this method. * * @param mv a method visitor. */ public void accept(final MethodVisitor mv) { // visits the method attributes int i, j, n; if (annotationDefault != null) { AnnotationVisitor av = mv.visitAnnotationDefault(); AnnotationNode.accept(av, null, annotationDefault); if (av != null) { av.visitEnd(); } } n = visibleAnnotations == null ? 0 : visibleAnnotations.size(); for (i = 0; i < n; ++i) { AnnotationNode an = (AnnotationNode) visibleAnnotations.get(i); an.accept(mv.visitAnnotation(an.desc, true)); } n = invisibleAnnotations == null ? 0 : invisibleAnnotations.size(); for (i = 0; i < n; ++i) { AnnotationNode an = (AnnotationNode) invisibleAnnotations.get(i); an.accept(mv.visitAnnotation(an.desc, false)); } n = visibleParameterAnnotations == null ? 0 : visibleParameterAnnotations.length; for (i = 0; i < n; ++i) { List l = visibleParameterAnnotations[i]; if (l == null) { continue; } for (j = 0; j < l.size(); ++j) { AnnotationNode an = (AnnotationNode) l.get(j); an.accept(mv.visitParameterAnnotation(i, an.desc, true)); } } n = invisibleParameterAnnotations == null ? 0 : invisibleParameterAnnotations.length; for (i = 0; i < n; ++i) { List l = invisibleParameterAnnotations[i]; if (l == null) { continue; } for (j = 0; j < l.size(); ++j) { AnnotationNode an = (AnnotationNode) l.get(j); an.accept(mv.visitParameterAnnotation(i, an.desc, false)); } } n = attrs == null ? 0 : attrs.size(); for (i = 0; i < n; ++i) { mv.visitAttribute((Attribute) attrs.get(i)); } // visits the method's code if (instructions.size() > 0) { mv.visitCode(); // visits try catch blocks for (i = 0; i < tryCatchBlocks.size(); ++i) { ((TryCatchBlockNode) tryCatchBlocks.get(i)).accept(mv); } // visits instructions instructions.accept(mv); // visits local variables n = localVariables == null ? 0 : localVariables.size(); for (i = 0; i < n; ++i) { ((LocalVariableNode) localVariables.get(i)).accept(mv); } // visits maxs mv.visitMaxs(maxStack, maxLocals); } mv.visitEnd(); } }
gstamac/powermock
powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/repackaged/asm/tree/MethodNode.java
Java
apache-2.0
16,512
USE `modo-import`; CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `modo-import`.`Center` AS SELECT center.id AS id, center.name AS name, center.code AS code, "ef80ab638b" AS mailchimpListId, "[email protected]" AS contactEmail FROM `crm-import`.`Center` AS center WHERE code = 095; CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `modo-import`.`User` AS SELECT * FROM `crm-import`.`User` AS user WHERE user.centerCode = 095; CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `modo-import`.`Card` AS SELECT * FROM `crm-import`.`Card` AS card WHERE card.centerCode = 095; CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `modo-import`.`Child` AS SELECT child.* FROM `crm-import`.`Child` AS child INNER JOIN `crm-import`.`User` AS parent ON child.parentReference = parent.reference WHERE parent.centerCode = 095; CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `modo-import`.`CardRequest` AS SELECT * FROM `crm-import`.`CardRequest` AS cardRequest WHERE cardRequest.centerCode = 095;
incodehq/ecpcrm
application/src/main/java/org/incode/eurocommercial/ecpcrm/module/application/fixture/scripts/import-views-modo.sql
SQL
apache-2.0
1,211
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ManagerShop.Domain.DomainEvents { public class MessageSentEventHandler : IEventHandler<MessageSentEvent> { public void Handle(MessageSentEvent evt) { Console.WriteLine("Order_Number:{0},Send a Email.", evt.OrderID); } } }
dawutao/ManagerShop
ManagerShop.UI/ManagerShop.Domain.Event/EventHandlers/MessageSentEventHandler.cs
C#
apache-2.0
400
/* * 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.facebook.presto.operator; import com.facebook.airlift.log.Logger; import com.facebook.presto.common.Page; import com.facebook.presto.common.block.BlockEncodingSerde; import com.facebook.presto.execution.buffer.PagesSerdeFactory; import com.facebook.presto.metadata.Split; import com.facebook.presto.metadata.Split.SplitIdentifier; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.page.PagesSerde; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalListener; import com.google.common.cache.RemovalNotification; import com.google.common.collect.AbstractIterator; import io.airlift.slice.InputStreamSliceInput; import io.airlift.slice.OutputStreamSliceOutput; import io.airlift.slice.SliceOutput; import javax.inject.Inject; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import static com.facebook.presto.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR; import static com.facebook.presto.spi.page.PagesSerdeUtil.readPages; import static com.facebook.presto.spi.page.PagesSerdeUtil.writePages; import static com.google.common.util.concurrent.Futures.immediateFuture; import static java.nio.file.Files.newInputStream; import static java.nio.file.Files.newOutputStream; import static java.nio.file.StandardOpenOption.APPEND; import static java.util.Objects.requireNonNull; import static java.util.UUID.randomUUID; import static java.util.concurrent.TimeUnit.MILLISECONDS; public class FileFragmentResultCacheManager implements FragmentResultCacheManager { private static final Logger log = Logger.get(FileFragmentResultCacheManager.class); private final Path baseDirectory; private final long maxInFlightBytes; private final PagesSerde pagesSerde; private final FragmentCacheStats fragmentCacheStats; private final ExecutorService flushExecutor; private final ExecutorService removalExecutor; private final Cache<CacheKey, Path> cache; // TODO: Decouple CacheKey by encoding PlanNode and SplitIdentifier separately so we don't have to keep too many objects in memory @Inject public FileFragmentResultCacheManager( FileFragmentResultCacheConfig cacheConfig, BlockEncodingSerde blockEncodingSerde, FragmentCacheStats fragmentCacheStats, ExecutorService flushExecutor, ExecutorService removalExecutor) { requireNonNull(cacheConfig, "cacheConfig is null"); requireNonNull(blockEncodingSerde, "blockEncodingSerde is null"); this.baseDirectory = Paths.get(cacheConfig.getBaseDirectory()); this.maxInFlightBytes = cacheConfig.getMaxInFlightSize().toBytes(); this.pagesSerde = new PagesSerdeFactory(blockEncodingSerde, cacheConfig.isBlockEncodingCompressionEnabled()).createPagesSerde(); this.fragmentCacheStats = requireNonNull(fragmentCacheStats, "fragmentCacheStats is null"); this.flushExecutor = requireNonNull(flushExecutor, "flushExecutor is null"); this.removalExecutor = requireNonNull(removalExecutor, "removalExecutor is null"); this.cache = CacheBuilder.newBuilder() .maximumSize(cacheConfig.getMaxCachedEntries()) .expireAfterAccess(cacheConfig.getCacheTtl().toMillis(), MILLISECONDS) .removalListener(new CacheRemovalListener()) .recordStats() .build(); File target = new File(baseDirectory.toUri()); if (!target.exists()) { try { Files.createDirectories(target.toPath()); } catch (IOException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "cannot create cache directory " + target, e); } } else { File[] files = target.listFiles(); if (files == null) { return; } this.removalExecutor.submit(() -> Arrays.stream(files).forEach(file -> { try { Files.delete(file.toPath()); } catch (IOException e) { // ignore } })); } } @Override public Future<?> put(String serializedPlan, Split split, List<Page> result) { CacheKey key = new CacheKey(serializedPlan, split.getSplitIdentifier()); long resultSize = getPagesSize(result); if (fragmentCacheStats.getInFlightBytes() + resultSize > maxInFlightBytes || cache.getIfPresent(key) != null) { return immediateFuture(null); } fragmentCacheStats.addInFlightBytes(resultSize); Path path = baseDirectory.resolve(randomUUID().toString().replaceAll("-", "_")); return flushExecutor.submit(() -> cachePages(key, path, result)); } private static long getPagesSize(List<Page> pages) { return pages.stream() .mapToLong(Page::getSizeInBytes) .sum(); } private void cachePages(CacheKey key, Path path, List<Page> pages) { // TODO: To support both memory and disk limit, we should check cache size before putting to cache and use written bytes as weight for cache try { Files.createFile(path); try (SliceOutput output = new OutputStreamSliceOutput(newOutputStream(path, APPEND))) { writePages(pagesSerde, output, pages.iterator()); cache.put(key, path); } catch (UncheckedIOException | IOException e) { log.warn(e, "%s encountered an error while writing to path %s", Thread.currentThread().getName(), path); tryDeleteFile(path); } } catch (UncheckedIOException | IOException e) { log.warn(e, "%s encountered an error while writing to path %s", Thread.currentThread().getName(), path); tryDeleteFile(path); } finally { fragmentCacheStats.addInFlightBytes(-getPagesSize(pages)); } } private static void tryDeleteFile(Path path) { try { File file = new File(path.toUri()); if (file.exists()) { Files.delete(file.toPath()); } } catch (IOException e) { // ignore } } @Override public Optional<Iterator<Page>> get(String serializedPlan, Split split) { CacheKey key = new CacheKey(serializedPlan, split.getSplitIdentifier()); Path path = cache.getIfPresent(key); if (path == null) { fragmentCacheStats.incrementCacheMiss(); return Optional.empty(); } try { InputStream inputStream = newInputStream(path); Iterator<Page> result = readPages(pagesSerde, new InputStreamSliceInput(inputStream)); fragmentCacheStats.incrementCacheHit(); return Optional.of(closeWhenExhausted(result, inputStream)); } catch (UncheckedIOException | IOException e) { // there might be a chance the file has been deleted. We would return cache miss in this case. fragmentCacheStats.incrementCacheMiss(); return Optional.empty(); } } private static <T> Iterator<T> closeWhenExhausted(Iterator<T> iterator, Closeable resource) { requireNonNull(iterator, "iterator is null"); requireNonNull(resource, "resource is null"); return new AbstractIterator<T>() { @Override protected T computeNext() { if (iterator.hasNext()) { return iterator.next(); } try { resource.close(); } catch (IOException e) { throw new UncheckedIOException(e); } return endOfData(); } }; } public static class CacheKey { private final String serializedPlan; private final SplitIdentifier splitIdentifier; public CacheKey(String serializedPlan, SplitIdentifier splitIdentifier) { this.serializedPlan = requireNonNull(serializedPlan, "serializedPlan is null"); this.splitIdentifier = requireNonNull(splitIdentifier, "splitIdentifier is null"); } public String getSerializedPlan() { return serializedPlan; } public SplitIdentifier getSplitIdentifier() { return splitIdentifier; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CacheKey cacheKey = (CacheKey) o; return Objects.equals(serializedPlan, cacheKey.serializedPlan) && Objects.equals(splitIdentifier, cacheKey.splitIdentifier); } @Override public int hashCode() { return Objects.hash(serializedPlan, splitIdentifier); } } private class CacheRemovalListener implements RemovalListener<CacheKey, Path> { @Override public void onRemoval(RemovalNotification<CacheKey, Path> notification) { removalExecutor.submit(() -> tryDeleteFile(notification.getValue())); } } }
EvilMcJerkface/presto
presto-main/src/main/java/com/facebook/presto/operator/FileFragmentResultCacheManager.java
Java
apache-2.0
10,483
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache.distributed.near; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import org.apache.ignite.IgniteCache; import org.apache.ignite.cache.CachePeekMode; import org.apache.ignite.cache.store.CacheStoreAdapter; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.spi.discovery.DiscoverySpi; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import static org.apache.ignite.cache.CacheMode.PARTITIONED; import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC; /** * Test that persistent store is not used when loading invalidated entry from backup node. */ public class GridPartitionedBackupLoadSelfTest extends GridCommonAbstractTest { /** */ private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true); /** */ private static final int GRID_CNT = 3; /** */ private final TestStore store = new TestStore(); /** */ private final AtomicInteger cnt = new AtomicInteger(); /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); cfg.setDiscoverySpi(discoverySpi()); cfg.setCacheConfiguration(cacheConfiguration()); return cfg; } /** * @return Discovery SPI. */ private DiscoverySpi discoverySpi() { TcpDiscoverySpi spi = new TcpDiscoverySpi(); spi.setIpFinder(IP_FINDER); return spi; } /** * @return Cache configuration. */ @SuppressWarnings("unchecked") private CacheConfiguration cacheConfiguration() { CacheConfiguration cfg = defaultCacheConfiguration(); cfg.setCacheMode(PARTITIONED); cfg.setBackups(1); cfg.setCacheStoreFactory(singletonFactory(store)); cfg.setReadThrough(true); cfg.setWriteThrough(true); cfg.setLoadPreviousValue(true); cfg.setWriteSynchronizationMode(FULL_SYNC); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { startGridsMultiThreaded(GRID_CNT); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { stopAllGrids(); } /** * @throws Exception If failed. */ public void testBackupLoad() throws Exception { grid(0).cache(null).put(1, 1); assert store.get(1) == 1; for (int i = 0; i < GRID_CNT; i++) { IgniteCache<Integer, Integer> cache = jcache(i); if (grid(i).affinity(null).isBackup(grid(i).localNode(), 1)) { assert cache.localPeek(1, CachePeekMode.ONHEAP) == 1; jcache(i).localClear(1); assert cache.localPeek(1, CachePeekMode.ONHEAP) == null; // Store is called in putx method, so we reset counter here. cnt.set(0); assert cache.get(1) == 1; assert cnt.get() == 0; } } } /** * Test store. */ private class TestStore extends CacheStoreAdapter<Integer, Integer> { /** */ private Map<Integer, Integer> map = new ConcurrentHashMap<>(); /** {@inheritDoc} */ @Override public Integer load(Integer key) { cnt.incrementAndGet(); return null; } /** {@inheritDoc} */ @Override public void write(javax.cache.Cache.Entry<? extends Integer, ? extends Integer> e) { map.put(e.getKey(), e.getValue()); } /** {@inheritDoc} */ @Override public void delete(Object key) { // No-op } /** * @param key Key. * @return Value. */ public Integer get(Integer key) { return map.get(key); } } }
nivanov/ignite
modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/near/GridPartitionedBackupLoadSelfTest.java
Java
apache-2.0
5,117
package org.opencommercesearch.client.impl; import java.util.Date; /** * Represents a sku's availability. * * @author rmerizalde */ public class Availability { public enum Status { InStock, OutOfStock, PermanentlyOutOfStock, Backorderable, Preorderable } private Status status; private Long stockLevel; private Long backorderLevel; private Date date; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public Long getStockLevel() { return stockLevel; } public void setStockLevel(Long stockLevel) { this.stockLevel = stockLevel; } public Long getBackorderLevel() { return backorderLevel; } public void setBackorderLevel(Long backorderLevel) { this.backorderLevel = backorderLevel; } }
madickson/opencommercesearch
opencommercesearch-sdk-java/src/main/java/org/opencommercesearch/client/impl/Availability.java
Java
apache-2.0
947
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_51) on Tue Aug 27 20:57:01 WEST 2013 --> <TITLE> OFActionTypeTest </TITLE> <META NAME="date" CONTENT="2013-08-27"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="OFActionTypeTest"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/OFActionTypeTest.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../org/openflow/protocol/Instantiable.html" title="interface in org.openflow.protocol"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../org/openflow/protocol/OFBarrierReply.html" title="class in org.openflow.protocol"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?org/openflow/protocol/OFActionTypeTest.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="OFActionTypeTest.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.openflow.protocol</FONT> <BR> Class OFActionTypeTest</H2> <PRE> java.lang.Object <IMG SRC="../../../resources/inherit.gif" ALT="extended by ">junit.framework.Assert <IMG SRC="../../../resources/inherit.gif" ALT="extended by ">junit.framework.TestCase <IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>org.openflow.protocol.OFActionTypeTest</B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD>junit.framework.Test</DD> </DL> <HR> <DL> <DT><PRE>public class <B>OFActionTypeTest</B><DT>extends junit.framework.TestCase</DL> </PRE> <P> <HR> <P> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../org/openflow/protocol/OFActionTypeTest.html#OFActionTypeTest()">OFActionTypeTest</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../org/openflow/protocol/OFActionTypeTest.html#testMapping()">testMapping</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_junit.framework.TestCase"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class junit.framework.TestCase</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString</CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_junit.framework.Assert"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class junit.framework.Assert</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail, failNotEquals, failNotSame, failSame, format</CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="OFActionTypeTest()"><!-- --></A><H3> OFActionTypeTest</H3> <PRE> public <B>OFActionTypeTest</B>()</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="testMapping()"><!-- --></A><H3> testMapping</H3> <PRE> public void <B>testMapping</B>() throws java.lang.Exception</PRE> <DL> <DD><DL> <DT><B>Throws:</B> <DD><CODE>java.lang.Exception</CODE></DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/OFActionTypeTest.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../org/openflow/protocol/Instantiable.html" title="interface in org.openflow.protocol"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../org/openflow/protocol/OFBarrierReply.html" title="class in org.openflow.protocol"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?org/openflow/protocol/OFActionTypeTest.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="OFActionTypeTest.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
fbotelho-university-code/poseidon
doc/org/openflow/protocol/OFActionTypeTest.html
HTML
apache-2.0
11,450
/*! * angular-loading-bar v0.8.0 * https://chieffancypants.github.io/angular-loading-bar * Copyright (c) 2015 Wes Cruver * License: MIT */ /* * angular-loading-bar * * intercepts XHR requests and creates a loading bar. * Based on the excellent nprogress work by rstacruz (more info in readme) * * (c) 2013 Wes Cruver * License: MIT */ (function() { 'use strict'; // Alias the loading bar for various backwards compatibilities since the project has matured: angular.module('angular-loading-bar', ['cfp.loadingBarInterceptor']); angular.module('chieffancypants.loadingBar', ['cfp.loadingBarInterceptor']); /** * loadingBarInterceptor service * * Registers itself as an Angular interceptor and listens for XHR requests. */ angular.module('cfp.loadingBarInterceptor', ['cfp.loadingBar']) .config(['$httpProvider', function ($httpProvider) { var interceptor = ['$q', '$cacheFactory', '$timeout', '$rootScope', '$log', 'cfpLoadingBar', function ($q, $cacheFactory, $timeout, $rootScope, $log, cfpLoadingBar) { /** * The total number of requests made */ var reqsTotal = 0; /** * The number of requests completed (either successfully or not) */ var reqsCompleted = 0; /** * The amount of time spent fetching before showing the loading bar */ var latencyThreshold = cfpLoadingBar.latencyThreshold; /** * $timeout handle for latencyThreshold */ var startTimeout; /** * calls cfpLoadingBar.complete() which removes the * loading bar from the DOM. */ function setComplete() { $timeout.cancel(startTimeout); cfpLoadingBar.complete(); reqsCompleted = 0; reqsTotal = 0; } /** * Determine if the response has already been cached * @param {Object} config the config option from the request * @return {Boolean} retrns true if cached, otherwise false */ function isCached(config) { var cache; var defaultCache = $cacheFactory.get('$http'); var defaults = $httpProvider.defaults; // Choose the proper cache source. Borrowed from angular: $http service if ((config.cache || defaults.cache) && config.cache !== false && (config.method === 'GET' || config.method === 'JSONP')) { cache = angular.isObject(config.cache) ? config.cache : angular.isObject(defaults.cache) ? defaults.cache : defaultCache; } var cached = cache !== undefined ? cache.get(config.url) !== undefined : false; if (config.cached !== undefined && cached !== config.cached) { return config.cached; } config.cached = cached; return cached; } return { 'request': function(config) { // Check to make sure this request hasn't already been cached and that // the requester didn't explicitly ask us to ignore this request: if (!config.ignoreLoadingBar && !isCached(config)) { $rootScope.$broadcast('cfpLoadingBar:loading', {url: config.url}); if (reqsTotal === 0) { startTimeout = $timeout(function() { cfpLoadingBar.start(); }, latencyThreshold); } reqsTotal++; cfpLoadingBar.set(reqsCompleted / reqsTotal); } return config; }, 'response': function(response) { if (!response || !response.config) { $log.error('Broken interceptor detected: Config object not supplied in response:\n https://github.com/chieffancypants/angular-loading-bar/pull/50'); return response; } if (!response.config.ignoreLoadingBar && !isCached(response.config)) { reqsCompleted++; $rootScope.$broadcast('cfpLoadingBar:loaded', {url: response.config.url, result: response}); if (reqsCompleted >= reqsTotal) { setComplete(); } else { cfpLoadingBar.set(reqsCompleted / reqsTotal); } } return response; }, 'responseError': function(rejection) { if (!rejection || !rejection.config) { $log.error('Broken interceptor detected: Config object not supplied in rejection:\n https://github.com/chieffancypants/angular-loading-bar/pull/50'); return $q.reject(rejection); } if (!rejection.config.ignoreLoadingBar && !isCached(rejection.config)) { reqsCompleted++; $rootScope.$broadcast('cfpLoadingBar:loaded', {url: rejection.config.url, result: rejection}); if (reqsCompleted >= reqsTotal) { setComplete(); } else { cfpLoadingBar.set(reqsCompleted / reqsTotal); } } return $q.reject(rejection); } }; }]; $httpProvider.interceptors.push(interceptor); }]); /** * Loading Bar * * This service handles adding and removing the actual element in the DOM. * Generally, best practices for DOM manipulation is to take place in a * directive, but because the element itself is injected in the DOM only upon * XHR requests, and it's likely needed on every view, the best option is to * use a service. */ angular.module('cfp.loadingBar', []) .provider('cfpLoadingBar', function() { this.autoIncrement = true; this.includeSpinner = true; this.includeBar = true; this.latencyThreshold = 100; this.startSize = 0.02; this.parentSelector = 'body'; this.spinnerTemplate = '<div id="loading-bar-spinner"><div class="spinner-icon"></div></div>'; this.loadingBarTemplate = '<div id="loading-bar"><div class="bar"><div class="peg"></div></div></div>'; this.$get = ['$injector', '$document', '$timeout', '$rootScope', function ($injector, $document, $timeout, $rootScope) { var $animate; var $parentSelector = this.parentSelector, loadingBarContainer = angular.element(this.loadingBarTemplate), loadingBar = loadingBarContainer.find('div').eq(0), spinner = angular.element(this.spinnerTemplate); var incTimeout, completeTimeout, started = false, status = 0; var autoIncrement = this.autoIncrement; var includeSpinner = this.includeSpinner; var includeBar = this.includeBar; var startSize = this.startSize; /** * Inserts the loading bar element into the dom, and sets it to 2% */ function _start() { if (!$animate) { $animate = $injector.get('$animate'); } var $parent = $document.find($parentSelector).eq(0); $timeout.cancel(completeTimeout); // do not continually broadcast the started event: if (started) { return; } $rootScope.$broadcast('cfpLoadingBar:started'); started = true; if (includeBar) { $animate.enter(loadingBarContainer, $parent, angular.element($parent[0].lastChild)); } if (includeSpinner) { $animate.enter(spinner, $parent, angular.element($parent[0].lastChild)); } _set(startSize); } /** * Set the loading bar's width to a certain percent. * * @param n any value between 0 and 1 */ function _set(n) { if (!started) { return; } var pct = (n * 100) + '%'; loadingBar.css('width', pct); status = n; // increment loadingbar to give the illusion that there is always // progress but make sure to cancel the previous timeouts so we don't // have multiple incs running at the same time. if (autoIncrement) { $timeout.cancel(incTimeout); incTimeout = $timeout(function() { _inc(); }, 250); } } /** * Increments the loading bar by a random amount * but slows down as it progresses */ function _inc() { if (_status() >= 1) { return; } var rnd = 0; // TODO: do this mathmatically instead of through conditions var stat = _status(); if (stat >= 0 && stat < 0.25) { // Start out between 3 - 6% increments rnd = (Math.random() * (5 - 3 + 1) + 3) / 100; } else if (stat >= 0.25 && stat < 0.65) { // increment between 0 - 3% rnd = (Math.random() * 3) / 100; } else if (stat >= 0.65 && stat < 0.9) { // increment between 0 - 2% rnd = (Math.random() * 2) / 100; } else if (stat >= 0.9 && stat < 0.99) { // finally, increment it .5 % rnd = 0.005; } else { // after 99%, don't increment: rnd = 0; } var pct = _status() + rnd; _set(pct); } function _status() { return status; } function _completeAnimation() { status = 0; started = false; } function _complete() { if (!$animate) { $animate = $injector.get('$animate'); } $rootScope.$broadcast('cfpLoadingBar:completed'); _set(1); $timeout.cancel(completeTimeout); // Attempt to aggregate any start/complete calls within 500ms: completeTimeout = $timeout(function() { var promise = $animate.leave(loadingBarContainer, _completeAnimation); if (promise && promise.then) { promise.then(_completeAnimation); } $animate.leave(spinner); }, 500); } return { start : _start, set : _set, status : _status, inc : _inc, complete : _complete, autoIncrement : this.autoIncrement, includeSpinner : this.includeSpinner, latencyThreshold : this.latencyThreshold, parentSelector : this.parentSelector, startSize : this.startSize }; }]; // }); // wtf javascript. srsly })(); //
rexren/Enterprise-Quality
hephaestus-site/src/main/resources/static/scripts/vendor/angular-loading-bar/angular-loading-bar.js
JavaScript
apache-2.0
10,213
package distribution // import "github.com/tiborvass/docker/distribution" import ( "bufio" "compress/gzip" "context" "fmt" "io" "github.com/docker/distribution/reference" "github.com/tiborvass/docker/distribution/metadata" "github.com/tiborvass/docker/pkg/progress" "github.com/tiborvass/docker/registry" "github.com/sirupsen/logrus" ) // Pusher is an interface that abstracts pushing for different API versions. type Pusher interface { // Push tries to push the image configured at the creation of Pusher. // Push returns an error if any, as well as a boolean that determines whether to retry Push on the next configured endpoint. // // TODO(tiborvass): have Push() take a reference to repository + tag, so that the pusher itself is repository-agnostic. Push(ctx context.Context) error } const compressionBufSize = 32768 // NewPusher creates a new Pusher interface that will push to either a v1 or v2 // registry. The endpoint argument contains a Version field that determines // whether a v1 or v2 pusher will be created. The other parameters are passed // through to the underlying pusher implementation for use during the actual // push operation. func NewPusher(ref reference.Named, endpoint registry.APIEndpoint, repoInfo *registry.RepositoryInfo, imagePushConfig *ImagePushConfig) (Pusher, error) { switch endpoint.Version { case registry.APIVersion2: return &v2Pusher{ v2MetadataService: metadata.NewV2MetadataService(imagePushConfig.MetadataStore), ref: ref, endpoint: endpoint, repoInfo: repoInfo, config: imagePushConfig, }, nil case registry.APIVersion1: return nil, fmt.Errorf("protocol version %d no longer supported. Please contact admins of registry %s", endpoint.Version, endpoint.URL) } return nil, fmt.Errorf("unknown version %d for registry %s", endpoint.Version, endpoint.URL) } // Push initiates a push operation on ref. // ref is the specific variant of the image to be pushed. // If no tag is provided, all tags will be pushed. func Push(ctx context.Context, ref reference.Named, imagePushConfig *ImagePushConfig) error { // FIXME: Allow to interrupt current push when new push of same image is done. // Resolve the Repository name from fqn to RepositoryInfo repoInfo, err := imagePushConfig.RegistryService.ResolveRepository(ref) if err != nil { return err } endpoints, err := imagePushConfig.RegistryService.LookupPushEndpoints(reference.Domain(repoInfo.Name)) if err != nil { return err } progress.Messagef(imagePushConfig.ProgressOutput, "", "The push refers to repository [%s]", repoInfo.Name.Name()) associations := imagePushConfig.ReferenceStore.ReferencesByName(repoInfo.Name) if len(associations) == 0 { return fmt.Errorf("An image does not exist locally with the tag: %s", reference.FamiliarName(repoInfo.Name)) } var ( lastErr error // confirmedV2 is set to true if a push attempt managed to // confirm that it was talking to a v2 registry. This will // prevent fallback to the v1 protocol. confirmedV2 bool // confirmedTLSRegistries is a map indicating which registries // are known to be using TLS. There should never be a plaintext // retry for any of these. confirmedTLSRegistries = make(map[string]struct{}) ) for _, endpoint := range endpoints { if imagePushConfig.RequireSchema2 && endpoint.Version == registry.APIVersion1 { continue } if confirmedV2 && endpoint.Version == registry.APIVersion1 { logrus.Debugf("Skipping v1 endpoint %s because v2 registry was detected", endpoint.URL) continue } if endpoint.URL.Scheme != "https" { if _, confirmedTLS := confirmedTLSRegistries[endpoint.URL.Host]; confirmedTLS { logrus.Debugf("Skipping non-TLS endpoint %s for host/port that appears to use TLS", endpoint.URL) continue } } logrus.Debugf("Trying to push %s to %s %s", repoInfo.Name.Name(), endpoint.URL, endpoint.Version) pusher, err := NewPusher(ref, endpoint, repoInfo, imagePushConfig) if err != nil { lastErr = err continue } if err := pusher.Push(ctx); err != nil { // Was this push cancelled? If so, don't try to fall // back. select { case <-ctx.Done(): default: if fallbackErr, ok := err.(fallbackError); ok { confirmedV2 = confirmedV2 || fallbackErr.confirmedV2 if fallbackErr.transportOK && endpoint.URL.Scheme == "https" { confirmedTLSRegistries[endpoint.URL.Host] = struct{}{} } err = fallbackErr.err lastErr = err logrus.Infof("Attempting next endpoint for push after error: %v", err) continue } } logrus.Errorf("Not continuing with push after error: %v", err) return err } imagePushConfig.ImageEventLogger(reference.FamiliarString(ref), reference.FamiliarName(repoInfo.Name), "push") return nil } if lastErr == nil { lastErr = fmt.Errorf("no endpoints found for %s", repoInfo.Name.Name()) } return lastErr } // compress returns an io.ReadCloser which will supply a compressed version of // the provided Reader. The caller must close the ReadCloser after reading the // compressed data. // // Note that this function returns a reader instead of taking a writer as an // argument so that it can be used with httpBlobWriter's ReadFrom method. // Using httpBlobWriter's Write method would send a PATCH request for every // Write call. // // The second return value is a channel that gets closed when the goroutine // is finished. This allows the caller to make sure the goroutine finishes // before it releases any resources connected with the reader that was // passed in. func compress(in io.Reader) (io.ReadCloser, chan struct{}) { compressionDone := make(chan struct{}) pipeReader, pipeWriter := io.Pipe() // Use a bufio.Writer to avoid excessive chunking in HTTP request. bufWriter := bufio.NewWriterSize(pipeWriter, compressionBufSize) compressor := gzip.NewWriter(bufWriter) go func() { _, err := io.Copy(compressor, in) if err == nil { err = compressor.Close() } if err == nil { err = bufWriter.Flush() } if err != nil { pipeWriter.CloseWithError(err) } else { pipeWriter.Close() } close(compressionDone) }() return pipeReader, compressionDone }
tiborvass/docker
distribution/push.go
GO
apache-2.0
6,226
#pragma once #ifndef GEODE_INTEGRATION_TEST_QUERYHELPER_H_ #define GEODE_INTEGRATION_TEST_QUERYHELPER_H_ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstdlib> #include <geode/SystemProperties.hpp> #include <ace/OS.h> #include "DistributedSystemImpl.hpp" #include "testobject/Portfolio.hpp" #include "testobject/Position.hpp" #include "testobject/PdxType.hpp" #include "testobject/PortfolioPdx.hpp" #include "testobject/PositionPdx.hpp" #include <geode/ResultSet.hpp> #include <geode/StructSet.hpp> #include "CacheRegionHelper.hpp" #include "CacheImpl.hpp" //#include <geode/Struct.hpp> //#ifndef ROOT_NAME // ROOT_NAME+++ DEFINE ROOT_NAME before including QueryHelper.hpp //#endif #ifndef ROOT_SCOPE #define ROOT_SCOPE LOCAL #endif using namespace apache::geode::client; using namespace testData; using namespace PdxTests; using namespace testobject; class QueryHelper { public: static QueryHelper* singleton; static QueryHelper& getHelper() { if (singleton == nullptr) { singleton = new QueryHelper(); } return *singleton; } QueryHelper() { portfolioSetSize = 20; portfolioNumSets = 1; positionSetSize = 20; positionNumSets = 1; } virtual ~QueryHelper() { ; } virtual void populatePortfolioData( std::shared_ptr<Region>& pregion, size_t setSize, size_t numSets, int32_t objSize = 1, std::shared_ptr<CacheableStringArray> nm = nullptr); virtual void populatePositionData(std::shared_ptr<Region>& pregion, size_t setSize, size_t numSets); virtual void populatePortfolioPdxData(std::shared_ptr<Region>& pregion, size_t setSize, size_t numSets, int32_t objSize = 1, char** nm = nullptr); virtual void populatePositionPdxData(std::shared_ptr<Region>& pregion, size_t setSize, size_t numSets); virtual void populatePDXObject(std::shared_ptr<Region>& pregion); virtual void getPDXObject(std::shared_ptr<Region>& pregion); virtual bool verifyRS(std::shared_ptr<SelectResults>& resultset, size_t rowCount); virtual bool verifySS(std::shared_ptr<SelectResults>& structset, size_t rowCount, int32_t fieldCount); // utility methods virtual size_t getPortfolioSetSize() { return portfolioSetSize; }; virtual size_t getPortfolioNumSets() { return portfolioNumSets; }; virtual size_t getPositionSetSize() { return positionSetSize; }; virtual size_t getPositionNumSets() { return positionNumSets; }; bool isExpectedRowsConstantRS(int queryindex) { for (int i = (sizeof(constantExpectedRowsRS) / sizeof(int)) - 1; i > -1; i--) { if (constantExpectedRowsRS[i] == queryindex) { printf("index %d is having constant rows \n", constantExpectedRowsRS[i]); return true; } } return false; } bool isExpectedRowsConstantPQRS(int queryindex) { for (int i = (sizeof(constantExpectedRowsPQRS) / sizeof(int)) - 1; i > -1; i--) { if (constantExpectedRowsPQRS[i] == queryindex) { printf("index %d is having constant rows \n", constantExpectedRowsPQRS[i]); return true; } } return false; } bool isExpectedRowsConstantSS(int queryindex) { for (int i = (sizeof(constantExpectedRowsSS) / sizeof(int)) - 1; i > -1; i--) { if (constantExpectedRowsSS[i] == queryindex) { printf("index %d is having constant rows \n", constantExpectedRowsSS[i]); return true; } } return false; } bool isExpectedRowsConstantSSPQ(int queryindex) { for (int i = (sizeof(constantExpectedRowsSSPQ) / sizeof(int)) - 1; i > -1; i--) { if (constantExpectedRowsSSPQ[i] == queryindex) { printf("index %d is having constant rows \n", constantExpectedRowsSSPQ[i]); return true; } } return false; } private: size_t portfolioSetSize; size_t portfolioNumSets; size_t positionSetSize; size_t positionNumSets; }; QueryHelper* QueryHelper::singleton = nullptr; //=========================================================================================== void QueryHelper::populatePortfolioData( std::shared_ptr<Region>& rptr, size_t setSize, size_t numSets, int32_t objSize, std::shared_ptr<CacheableStringArray> nm) { // lets reset the counter for uniform population of position objects Position::resetCounter(); for (size_t set = 1; set <= numSets; set++) { for (size_t current = 1; current <= setSize; current++) { auto port = std::make_shared<Portfolio>(static_cast<int32_t>(current), objSize, nm); char portname[100] = {0}; ACE_OS::sprintf(portname, "port%zd-%zd", set, current); auto keyport = CacheableKey::create(portname); // printf(" QueryHelper::populatePortfolioData creating key = %s and // puting data \n",portname); rptr->put(keyport, port); } } // portfolioSetSize = setSize; portfolioNumSets = numSets; objectSize = // objSize; printf("all puts done \n"); } const char* secIds[] = {"SUN", "IBM", "YHOO", "GOOG", "MSFT", "AOL", "APPL", "ORCL", "SAP", "DELL"}; void QueryHelper::populatePositionData(std::shared_ptr<Region>& rptr, size_t setSize, size_t numSets) { int numSecIds = sizeof(secIds) / sizeof(char*); for (size_t set = 1; set <= numSets; set++) { for (size_t current = 1; current <= setSize; current++) { auto pos = std::make_shared<Position>( secIds[current % numSecIds], static_cast<int32_t>(current * 100)); char posname[100] = {0}; ACE_OS::sprintf(posname, "pos%zd-%zd", set, current); auto keypos = CacheableKey::create(posname); rptr->put(keypos, pos); } } // positionSetSize = setSize; positionNumSets = numSets; } void QueryHelper::populatePortfolioPdxData(std::shared_ptr<Region>& rptr, size_t setSize, size_t numSets, int32_t objSize, char**) { // lets reset the counter for uniform population of position objects PositionPdx::resetCounter(); for (size_t set = 1; set <= numSets; set++) { for (size_t current = 1; current <= setSize; current++) { auto port = std::make_shared<PortfolioPdx>(static_cast<int32_t>(current), objSize); char portname[100] = {0}; ACE_OS::sprintf(portname, "port%zd-%zd", set, current); auto keyport = CacheableKey::create(portname); rptr->put(keyport, port); LOGDEBUG("populatePortfolioPdxData:: Put for iteration current = %d done", current); } } // portfolioSetSize = setSize; portfolioNumSets = numSets; objectSize = // objSize; printf("all puts done \n"); } void QueryHelper::populatePositionPdxData(std::shared_ptr<Region>& rptr, size_t setSize, size_t numSets) { auto numSecIds = sizeof(secIds) / sizeof(char*); for (size_t set = 1; set <= numSets; set++) { for (size_t current = 1; current <= setSize; current++) { auto pos = std::make_shared<PositionPdx>( secIds[current % numSecIds], static_cast<int32_t>(current * 100)); char posname[100] = {0}; ACE_OS::sprintf(posname, "pos%zd-%zd", set, current); auto keypos = CacheableKey::create(posname); rptr->put(keypos, pos); } } // positionSetSize = setSize; positionNumSets = numSets; } void QueryHelper::populatePDXObject(std::shared_ptr<Region>& rptr) { // Register PdxType Object auto cacheImpl = CacheRegionHelper::getCacheImpl(&rptr->getCache()); cacheImpl->getSerializationRegistry()->addPdxType( PdxTests::PdxType::createDeserializable); LOG("PdxObject Registered Successfully...."); // Creating object of type PdxObject auto pdxobj = std::make_shared<PdxTests::PdxType>(); auto keyport = CacheableKey::create("ABC"); // PUT Operation rptr->put(keyport, pdxobj); // locally destroy PdxObject rptr->localDestroy(keyport); LOG("localDestroy() operation....Done"); // Remote GET for PdxObject auto obj2 = std::dynamic_pointer_cast<PdxTests::PdxType>(rptr->get(keyport)); LOGINFO("get... Result-1: Returned float=%f, String val = %s double=%lf", obj2->getFloat(), obj2->getString().c_str(), obj2->getDouble()); // LOGINFO("get.. Result-2: Returned BOOL = %d and BYTE = %s SHORT=%d INT=%d", // obj2->getBool(), obj2->getByte(), obj2->getShort(), obj2->getInt()); // TODO /* ASSERT(obj2->getID1() == 101, "ID1 = 101 expected"); ASSERT(obj2->getID2() == 201, "ID2 = 201 expected"); ASSERT(obj2->getID3() == 301, "ID3 = 301 expected"); */ LOG("NIL:200:PUT Operation successfully Done....End"); } void QueryHelper::getPDXObject(std::shared_ptr<Region>& rptr) { // Remote GET for PdxObject // PdxObject *obj2 = dynamic_cast<PdxObject *> ((rptr->get(keyport)).get()); auto keyport = CacheableKey::create("ABC"); LOG("Client-2 PdxObject GET OP Start...."); auto obj2 = std::dynamic_pointer_cast<PdxTests::PdxType>(rptr->get(keyport)); LOG("Client-2 PdxObject GET OP Done...."); /* LOGINFO("GET OP Result: BoolVal=%d", obj2->getBool()); LOGINFO("GET OP Result: ByteVal=%d", obj2->getByte()); LOGINFO("GET OP Result: ShortVal=%d", obj2->getShort());*/ // LOGINFO("GET OP Result: IntVal=%d", obj2->getInt()); /* LOGINFO("GET OP Result: LongVal=%ld", obj2->getLong()); LOGINFO("GET OP Result: FloatVal=%f", obj2->getFloat()); LOGINFO("GET OP Result: DoubleVal=%lf", obj2->getDouble()); LOGINFO("GET OP Result: StringVal=%s", obj2->getString()); */ } bool QueryHelper::verifyRS(std::shared_ptr<SelectResults>& resultSet, size_t expectedRows) { if (!std::dynamic_pointer_cast<ResultSet>(resultSet)) { return false; } auto rsptr = std::static_pointer_cast<ResultSet>(resultSet); size_t foundRows = 0; SelectResultsIterator iter = rsptr->getIterator(); for (size_t rows = 0; rows < rsptr->size(); rows++) { auto ser = (*rsptr)[rows]; foundRows++; } printf("found rows %zd, expected %zd \n", foundRows, expectedRows); if (foundRows == expectedRows) return true; return false; } bool QueryHelper::verifySS(std::shared_ptr<SelectResults>& structSet, size_t expectedRows, int32_t expectedFields) { if (!std::dynamic_pointer_cast<StructSet>(structSet)) { if (expectedRows == 0 && expectedFields == 0) { return true; // quite possible we got a null set back. } printf("we have structSet itself nullptr \n"); return false; } auto ssptr = std::static_pointer_cast<StructSet>(structSet); size_t foundRows = 0; for (SelectResults::Iterator iter = ssptr->begin(); iter != ssptr->end(); iter++) { auto ser = (*iter); foundRows++; Struct* siptr = dynamic_cast<Struct*>(ser.get()); if (siptr == nullptr) { printf("siptr is nullptr \n\n"); return false; } int32_t foundFields = 0; for (int32_t cols = 0; cols < siptr->length(); cols++) { auto field = (*siptr)[cols]; foundFields++; } if (foundFields != expectedFields) { char buffer[1024] = {'\0'}; sprintf(buffer, "found fields %d, expected fields %d \n", foundFields, expectedFields); LOG(buffer); return false; } } if (foundRows == expectedRows) return true; // lets log and return in case of error only situation char buffer[1024] = {'\0'}; sprintf(buffer, "found rows %zd, expected rows %zd\n", foundRows, expectedRows); LOG(buffer); return false; } #endif // GEODE_INTEGRATION_TEST_QUERYHELPER_H_
mmartell/geode-native
cppcache/integration-test/QueryHelper.hpp
C++
apache-2.0
12,719
/* * testdatefmtrange_wo_SN.js - test the date range formatter object Wolof-Senegal * * Copyright © 2021, JEDLSoft * * 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. */ if (typeof(GregorianDate) === "undefined") { var GregorianDate = require("../../lib/GregorianDate.js"); } if (typeof(DateRngFmt) === "undefined") { var DateRngFmt = require("../../lib/DateRngFmt.js"); } if (typeof(ilib) === "undefined") { var ilib = require("../../lib/ilib.js"); } module.exports.testdatefmtrange_wo_SN = { setUp: function(callback) { ilib.clearCache(); callback(); }, testDateRngFmtRangeInDayShort_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "short"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "31-12-2011 - 13:45 – 14:30"); test.done(); }, testDateRngFmtRangeInDayMedium_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "medium"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "31 Des, 2011 - 13:45 – 14:30"); test.done(); }, testDateRngFmtRangeInDayLong_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "long"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "31 Desàmbar, 2011 ci 13:45 – 14:30"); test.done(); }, testDateRngFmtRangeInDayFull_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "full"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "31 Des, 2011 ci 13:45 – 14:30"); test.done(); }, testDateRngFmtRangeNextDayShort_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "short"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 12, day: 30, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "30-12-2011 - 13:45 – 31-12-2011 - 14:30"); test.done(); }, testDateRngFmtRangeNextDayMedium_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "medium"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 12, day: 30, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "30 Des, 2011 - 13:45 – 31 Des, 2011 - 14:30"); test.done(); }, testDateRngFmtRangeNextDayLong_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "long"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 12, day: 30, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "30 Desàmbar, 2011 ci 13:45 – 31 Desàmbar, 2011 ci 14:30"); test.done(); }, testDateRngFmtRangeNextDayFull_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "full"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 12, day: 30, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "30 Des, 2011 ci 13:45 – 31 Des, 2011 ci 14:30"); test.done(); }, testDateRngFmtRangeMultiDayShort_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "short"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 12, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "20 – 31-12-2011"); test.done(); }, testDateRngFmtRangeMultiDayMedium_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "medium"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 12, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "20 – 31 Des, 2011"); test.done(); }, testDateRngFmtRangeMultiDayLong_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "long"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 12, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "20 – 31 Desàmbar, 2011"); test.done(); }, testDateRngFmtRangeMultiDayFull_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "full"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 12, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "20 – 31 Des, 2011"); test.done(); }, testDateRngFmtRangeNextMonthShort_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "short"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 11, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "20-11 – 31-12-2011"); test.done(); }, testDateRngFmtRangeNextMonthMedium_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "medium"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 11, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "20 Now – 31 Des, 2011"); test.done(); }, testDateRngFmtRangeNextMonthLong_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "long"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 11, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "20 Nowàmbar – 31 Desàmbar, 2011"); test.done(); }, testDateRngFmtRangeNextMonthFull_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "full"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 11, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2011, month: 12, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "20 Now – 31 Des, 2011"); test.done(); }, testDateRngFmtRangeNextYearShort_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "short"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 11, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2012, month: 1, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "20-11-2011 – 31-01-2012"); test.done(); }, testDateRngFmtRangeNextYearMedium_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "medium"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 11, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2012, month: 1, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "20 Now, 2011 – 31 Sam, 2012"); test.done(); }, testDateRngFmtRangeNextYearLong_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "long"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 11, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2012, month: 1, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "20 Nowàmbar, 2011 – 31 Samwiyee, 2012"); test.done(); }, testDateRngFmtRangeNextYearFull_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "full"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 11, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2012, month: 1, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "20 Now, 2011 – 31 Sam, 2012"); test.done(); }, testDateRngFmtRangeMultiYearShort_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "short"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 11, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2014, month: 1, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "11-2011 – 01-2014"); test.done(); }, testDateRngFmtRangeMultiYearMedium_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "medium"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 11, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2014, month: 1, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "Now, 2011 – Sam, 2014"); test.done(); }, testDateRngFmtRangeMultiYearLong_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "long"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 11, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2014, month: 1, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "Nowàmbar, 2011 – Samwiyee, 2014"); test.done(); }, testDateRngFmtRangeMultiYearFull_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "full"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 11, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2014, month: 1, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "Now, 2011 – Sam, 2014"); test.done(); }, testDateRngFmtManyYearsFull_wo_SN: function(test) { test.expect(2); var fmt = new DateRngFmt({locale: "wo-SN", length: "full"}); test.ok(fmt !== null); var start = new GregorianDate({ year: 2011, month: 11, day: 20, hour: 13, minute: 45, second: 0, millisecond: 0 }); var end = new GregorianDate({ year: 2064, month: 1, day: 31, hour: 14, minute: 30, second: 0, millisecond: 0 }); test.equal(fmt.format(start, end), "2011 – 2064"); test.done(); } };
iLib-js/iLib
js/test/daterange/testdatefmtrange_wo_SN.js
JavaScript
apache-2.0
19,135
# AUTOGENERATED FILE FROM balenalib/kitra710-ubuntu:eoan-build ENV GO_VERSION 1.16 RUN mkdir -p /usr/local/go \ && curl -SLO "https://storage.googleapis.com/golang/go$GO_VERSION.linux-arm64.tar.gz" \ && echo "3770f7eb22d05e25fbee8fb53c2a4e897da043eb83c69b9a14f8d98562cd8098 go$GO_VERSION.linux-arm64.tar.gz" | sha256sum -c - \ && tar -xzf "go$GO_VERSION.linux-arm64.tar.gz" -C /usr/local/go --strip-components=1 \ && rm -f go$GO_VERSION.linux-arm64.tar.gz ENV GOROOT /usr/local/go ENV GOPATH /go ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH" WORKDIR $GOPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@golang" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Ubuntu eoan \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.16 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
nghiant2710/base-images
balena-base-images/golang/kitra710/ubuntu/eoan/1.16/build/Dockerfile
Dockerfile
apache-2.0
1,989
# AUTOGENERATED FILE FROM balenalib/genericx86-64-ext-debian:sid-run # remove several traces of debian python RUN apt-get purge -y python.* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # install python dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates \ netbase \ && rm -rf /var/lib/apt/lists/* # key 63C7CC90: public key "Simon McVittie <[email protected]>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <[email protected]>" imported RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 3.6.12 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.0.1 ENV SETUPTOOLS_VERSION 56.0.0 RUN set -x \ && buildDeps=' \ curl \ ' \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-amd64-openssl1.1.tar.gz" \ && echo "c811b37dfb62442ccf23f28ca81e5a48eb85b071a58ee69b278f25520196cb2e Python-$PYTHON_VERSION.linux-amd64-openssl1.1.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-amd64-openssl1.1.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-amd64-openssl1.1.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config # set PYTHONPATH to point to dist-packages ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@python" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Debian Sid \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.6.12, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
nghiant2710/base-images
balena-base-images/python/genericx86-64-ext/debian/sid/3.6.12/run/Dockerfile
Dockerfile
apache-2.0
4,103
package org.usfirst.frc.team4453.robot.commands; import org.usfirst.frc.team4453.library.Vision; import org.usfirst.frc.team4453.robot.Robot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * */ public class DriveWithCamera extends Command { public DriveWithCamera() { // Use requires() here to declare subsystem dependencies requires(Robot.chassis); } // Called just before this Command runs the first time protected void initialize() { System.out.println("DriveWithCamera"); Robot.ahrs.zeroYaw(); Robot.chassis.setPidVel(0); Robot.chassis.enableChassisPID(); Robot.chassis.setAutoTurn(true); } // Called repeatedly when this Command is scheduled to run // TODO: Figure out the 3d coordinant system, so we don't have to use the 2d coordinants, and so we can be camera independant. protected void execute() { double targetXPos = Vision.getTargetImgPosition("TheTarget").X; double targetAngleOffset; if(targetXPos == -99.0) { targetAngleOffset = 0; } else { double targetXOffset = Vision.getTargetImgPosition("TheTarget").X - (Vision.getFOVx()/2); // Lots of trig, gets us the number of degrees we need to turn. targetAngleOffset = Math.toDegrees(Math.atan(targetXOffset / ((Vision.getFOVx()/2) / Math.tan(Math.toRadians(Vision.getFOV()/2))))); } //Update the setpoint (does this work?); double setpointAngle = Robot.ahrs.getYaw() + targetAngleOffset; /* if(setpointAngle > 180.0) { setpointAngle -= 360.0; } if(setpointAngle < -180.0) { setpointAngle += 360.0; } */ SmartDashboard.putNumber("DriveWithCamera Output ", targetAngleOffset); Robot.chassis.chassisSetSetpoint(setpointAngle); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return !Robot.chassis.getAutoTurn(); } // Called once after isFinished returns true protected void end() { Robot.chassis.disableChassisPID(); Robot.chassis.setAutoTurn(false); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
RedHotChiliBots/FRC4453
Robot/Programming/FRC2016Robot/src/org/usfirst/frc/team4453/robot/commands/DriveWithCamera.java
Java
apache-2.0
2,359
# Google Compute Engine PHP Sample Application ## Description This is a simple web-based example of calling the Google Compute Engine API in PHP. ## Prerequisites * Run `composer install` in this directory to install the `google/cloud-compute` library. * Follow [Getting started with authentication](https://cloud.google.com/docs/authentication/getting-started) to authenticate with Service Account credentials. ## Running the Sample Application Run app.php on your web server: ``` php -S localhost:8080 ``` Visit the website (http://localhost:8080/app.php) in your web browser.
GoogleCloudPlatform/php-docs-samples
compute/cloud-client/helloworld/README.md
Markdown
apache-2.0
589
/** * Copyright (C) 2012 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.sos.cache; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.n52.oxf.valueDomains.time.ITimePeriod; import org.n52.sos.dataTypes.EnvelopeWrapper; import org.n52.sos.dataTypes.ObservationOffering; import org.n52.sos.db.AccessGDB; public class ObservationOfferingCache extends AbstractEntityCache<ObservationOffering> { private static final String TOKEN_SEP = "@@"; private static ObservationOfferingCache instance; public static synchronized ObservationOfferingCache instance(String dbName) throws FileNotFoundException { if (instance == null) { instance = new ObservationOfferingCache(dbName); } return instance; } public static synchronized ObservationOfferingCache instance() throws FileNotFoundException { return instance; } private boolean cancelled; private ObservationOfferingCache(String dbName) throws FileNotFoundException { super(dbName); } @Override protected String getCacheFileName() { return "observationOfferingsList.cache"; } @Override protected String serializeEntity(ObservationOffering entity) throws CacheException { StringBuilder sb = new StringBuilder(); sb.append(entity.getId()); sb.append(TOKEN_SEP); sb.append(entity.getName()); sb.append(TOKEN_SEP); sb.append(entity.getProcedureIdentifier()); sb.append(TOKEN_SEP); try { sb.append(EnvelopeEncoderDecoder.encode(entity.getObservedArea())); } catch (IOException e) { throw new CacheException(e); } sb.append(TOKEN_SEP); sb.append(Arrays.toString(entity.getObservedProperties())); sb.append(TOKEN_SEP); sb.append(TimePeriodEncoder.encode(entity.getTimeExtent())); return sb.toString(); } @Override protected ObservationOffering deserializeEntity(String line) { String[] values = line.split(TOKEN_SEP); if (values == null || values.length != 6) { return null; } String id = values[0].trim(); String name = values[1].trim(); String proc = values[2].trim(); EnvelopeWrapper env = EnvelopeEncoderDecoder.decode(values[3]); String[] props = decodeStringArray(values[4]); ITimePeriod time = TimePeriodEncoder.decode(values[5]); return new ObservationOffering(id, name, props, proc, env, time); } @Override protected boolean mergeWithPreviousEntries() { return true; } protected Collection<ObservationOffering> getCollectionFromDAO(AccessGDB geoDB) throws IOException { this.cancelled = false; clearTempCacheFile(); geoDB.getOfferingAccess().getNetworksAsObservationOfferingsAsync(new OnOfferingRetrieved() { int count = 0; @Override public void retrieveExpectedOfferingsCount(int c) { setMaximumEntries(c); } @Override public void retrieveOffering(ObservationOffering oo, int currentOfferingIndex) throws RetrievingCancelledException { storeTemporaryEntity(oo); setLatestEntryIndex(currentOfferingIndex); LOGGER.info(String.format("Added ObservationOffering #%s to the cache.", count++)); if (cancelled) { throw new RetrievingCancelledException("Cache update cancelled due to shutdown."); } } }); return Collections.emptyList(); } @Override protected AbstractEntityCache<ObservationOffering> getSingleInstance() { return instance; } @Override public void cancelCurrentExecution() { this.cancelled = true; } }
52North/ArcGIS-Server-SOS-Extension
src/main/java/org/n52/sos/cache/ObservationOfferingCache.java
Java
apache-2.0
4,089
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="zh"> <head> <!-- Generated by javadoc (1.8.0_91) on Thu Jul 13 16:16:26 CST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>程序包 com.webside.role.service.impl的使用 (webside 0.0.1-SNAPSHOT API)</title> <meta name="date" content="2017-07-13"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="\u7A0B\u5E8F\u5305 com.webside.role.service.impl\u7684\u4F7F\u7528 (webside 0.0.1-SNAPSHOT API)"; } } catch(err) { } //--> </script> <noscript> <div>您的浏览器已禁用 JavaScript。</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="跳过导航链接">跳过导航链接</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="导航"> <li><a href="../../../../../overview-summary.html">概览</a></li> <li><a href="package-summary.html">程序包</a></li> <li>类</li> <li class="navBarCell1Rev">使用</li> <li><a href="package-tree.html">树</a></li> <li><a href="../../../../../deprecated-list.html">已过时</a></li> <li><a href="../../../../../index-all.html">索引</a></li> <li><a href="../../../../../help-doc.html">帮助</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>上一个</li> <li>下一个</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/webside/role/service/impl/package-use.html" target="_top">框架</a></li> <li><a href="package-use.html" target="_top">无框架</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">所有类</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="程序包的使用 com.webside.role.service.impl" class="title">程序包的使用<br>com.webside.role.service.impl</h1> </div> <div class="contentContainer">没有com.webside.role.service.impl的用法</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="跳过导航链接">跳过导航链接</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="导航"> <li><a href="../../../../../overview-summary.html">概览</a></li> <li><a href="package-summary.html">程序包</a></li> <li>类</li> <li class="navBarCell1Rev">使用</li> <li><a href="package-tree.html">树</a></li> <li><a href="../../../../../deprecated-list.html">已过时</a></li> <li><a href="../../../../../index-all.html">索引</a></li> <li><a href="../../../../../help-doc.html">帮助</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>上一个</li> <li>下一个</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/webside/role/service/impl/package-use.html" target="_top">框架</a></li> <li><a href="package-use.html" target="_top">无框架</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">所有类</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2017. All rights reserved.</small></p> </body> </html>
ofpteam/ofp
target/apidocs/com/webside/role/service/impl/package-use.html
HTML
apache-2.0
4,302
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_232) on Tue Sep 15 08:53:08 UTC 2020 --> <title>Uses of Class org.springframework.web.socket.config.annotation.DelegatingWebSocketConfiguration (Spring Framework 5.1.18.RELEASE API)</title> <meta name="date" content="2020-09-15"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.springframework.web.socket.config.annotation.DelegatingWebSocketConfiguration (Spring Framework 5.1.18.RELEASE API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/springframework/web/socket/config/annotation/DelegatingWebSocketConfiguration.html" title="class in org.springframework.web.socket.config.annotation">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Spring Framework</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/springframework/web/socket/config/annotation/class-use/DelegatingWebSocketConfiguration.html" target="_top">Frames</a></li> <li><a href="DelegatingWebSocketConfiguration.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.springframework.web.socket.config.annotation.DelegatingWebSocketConfiguration" class="title">Uses of Class<br>org.springframework.web.socket.config.annotation.DelegatingWebSocketConfiguration</h2> </div> <div class="classUseContainer">No usage of org.springframework.web.socket.config.annotation.DelegatingWebSocketConfiguration</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/springframework/web/socket/config/annotation/DelegatingWebSocketConfiguration.html" title="class in org.springframework.web.socket.config.annotation">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Spring Framework</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/springframework/web/socket/config/annotation/class-use/DelegatingWebSocketConfiguration.html" target="_top">Frames</a></li> <li><a href="DelegatingWebSocketConfiguration.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
akhr/java
Spring/jars/spring-framework-5.1.18.RELEASE/docs/javadoc-api/org/springframework/web/socket/config/annotation/class-use/DelegatingWebSocketConfiguration.html
HTML
apache-2.0
5,182
/** * Copyright 2010 - 2022 JetBrains s.r.o. * * 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 * * https://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 jetbrains.exodus.io; import jetbrains.exodus.core.dataStructures.Pair; import jetbrains.exodus.env.Environment; import jetbrains.exodus.env.EnvironmentConfig; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ServiceLoader; /** * Service provider interface for creation instances of {@linkplain DataReader} and {@linkplain DataWriter}. * {@linkplain DataReader} and {@linkplain DataWriter} are used by {@code Log} implementation to perform basic * operations with {@linkplain Block blocks} ({@code .xd} files) and basic read/write/delete operations. * * Service provider interface is identified by a fully-qualified name of its implementation. When opening an * {@linkplain Environment}, {@linkplain #DEFAULT_READER_WRITER_PROVIDER} is used as default provide name. To use a * custom I/O provider, specify its fully-qualified name as a parameter of {@linkplain EnvironmentConfig#setLogDataReaderWriterProvider}. * * On {@linkplain Environment} creation new instance of {@code DataReaderWriterProvider} is created. * * @see Block * @see DataReader * @see DataWriter * @see EnvironmentConfig#getLogDataReaderWriterProvider * @see EnvironmentConfig#setLogDataReaderWriterProvider * @since 1.3.0 */ public abstract class DataReaderWriterProvider { /** * Fully-qualified name of default {@code DataReaderWriteProvider}. */ public static final String DEFAULT_READER_WRITER_PROVIDER = "jetbrains.exodus.io.FileDataReaderWriterProvider"; /** * Fully-qualified name of read-only watching {@code DataReaderWriteProvider}. */ public static final String WATCHING_READER_WRITER_PROVIDER = "jetbrains.exodus.io.WatchingFileDataReaderWriterProvider"; /** * Fully-qualified name of in-memory {@code DataReaderWriteProvider}. */ public static final String IN_MEMORY_READER_WRITER_PROVIDER = "jetbrains.exodus.io.MemoryDataReaderWriterProvider"; /** * Creates pair of new instances of {@linkplain DataReader} and {@linkplain DataWriter} by specified location. * What is location depends on the implementation of {@code DataReaderWriterProvider}, e.g. for {@code FileDataReaderWriterProvider} * location is a full path on local file system where the database is located. * * @param location identifies the database in this {@code DataReaderWriterProvider} * @return pair of new instances of {@linkplain DataReader} and {@linkplain DataWriter} */ public abstract Pair<DataReader, DataWriter> newReaderWriter(@NotNull final String location); /** * Returns {@code true} if the {@code DataReaderWriterProvider} creates in-memory {@linkplain DataReader} and {@linkplain DataWriter}. * * @return {@code true} if the {@code DataReaderWriterProvider} creates in-memory {@linkplain DataReader} and {@linkplain DataWriter} */ public boolean isInMemory() { return false; } /** * Returns {@code true} if the {@code DataReaderWriterProvider} creates read-only {@linkplain DataWriter}. * * @return {@code true} if the {@code DataReaderWriterProvider} creates read-only {@linkplain DataWriter} */ public boolean isReadonly() { return false; } /** * Callback method which is called when an environment is been opened/created. Can be used in implementation of * the {@code DataReaderWriterProvider} to access directly an {@linkplain Environment} instance, * its {@linkplain Environment#getEnvironmentConfig() config}, etc. Creation of {@code environment} is not * completed when the method is called. * * @param environment {@linkplain Environment} instance which is been opened/created using this * {@code DataReaderWriterProvider} */ public void onEnvironmentCreated(@NotNull final Environment environment) { } /** * Gets a {@code DataReaderWriterProvider} implementation by specified provider name. * * @param providerName fully-qualified name of {@code DataReaderWriterProvider} implementation * @return {@code DataReaderWriterProvider} implementation or {@code null} if the service could not be loaded */ @Nullable public static DataReaderWriterProvider getProvider(@NotNull final String providerName) { ServiceLoader<DataReaderWriterProvider> serviceLoader = ServiceLoader.load(DataReaderWriterProvider.class); if (!serviceLoader.iterator().hasNext()) { serviceLoader = ServiceLoader.load(DataReaderWriterProvider.class, DataReaderWriterProvider.class.getClassLoader()); } for (DataReaderWriterProvider provider : serviceLoader) { if (provider.getClass().getCanonicalName().equalsIgnoreCase(providerName)) { return provider; } } return null; } }
JetBrains/xodus
openAPI/src/main/java/jetbrains/exodus/io/DataReaderWriterProvider.java
Java
apache-2.0
5,499
package org.commcare.tasks; import android.content.Context; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.Pair; import org.commcare.CommCareApplication; import org.commcare.models.AndroidSessionWrapper; import org.commcare.models.database.AndroidSandbox; import org.commcare.models.database.SqlStorage; import org.commcare.android.database.user.models.FormRecord; import org.commcare.android.database.user.models.SessionStateDescriptor; import org.commcare.suite.model.Text; import org.commcare.tasks.templates.ManagedAsyncTask; import org.commcare.util.FormDataUtil; import org.commcare.utils.AndroidCommCarePlatform; import java.util.ArrayList; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.NoSuchElementException; import java.util.Queue; import java.util.Set; /** * Loads textual information for a list of FormRecords. * <p/> * This text currently includes the form name, record title, and last modified * date * * @author ctsims */ public class FormRecordLoaderTask extends ManagedAsyncTask<FormRecord, Pair<FormRecord, ArrayList<String>>, Integer> { private Hashtable<String, String> descriptorCache; private final SqlStorage<SessionStateDescriptor> descriptorStorage; private final AndroidCommCarePlatform platform; private Hashtable<Integer, String[]> searchCache; private final Context context; // Functions to call when some or all of the data has been loaded. Data // can be loaded normally, or be given precedence (priority), determining // which callback is dispatched to the listeners. private final ArrayList<FormRecordLoadListener> listeners = new ArrayList<>(); // These are all synchronized together final private Queue<FormRecord> priorityQueue = new LinkedList<>(); // The IDs of FormRecords that have been loaded private final Set<Integer> loaded = new HashSet<>(); // Maps form namespace (unique id for forms) to their form title // (entry-point text). Needed because FormRecords don't have form title // info, but do have the namespace. private Hashtable<String, Text> formNames; // Is the background task done loading all the FormRecord information? private boolean loadingComplete = false; public FormRecordLoaderTask(Context c, SqlStorage<SessionStateDescriptor> descriptorStorage, AndroidCommCarePlatform platform) { this(c, descriptorStorage, null, platform); } private FormRecordLoaderTask(Context c, SqlStorage<SessionStateDescriptor> descriptorStorage, Hashtable<String, String> descriptorCache, AndroidCommCarePlatform platform) { this.context = c; this.descriptorStorage = descriptorStorage; this.descriptorCache = descriptorCache; this.platform = platform; } /** * Create a copy of this loader task. */ public FormRecordLoaderTask spawn() { FormRecordLoaderTask task = new FormRecordLoaderTask(context, descriptorStorage, descriptorCache, platform); task.setListeners(listeners); return task; } /** * Pass in hashtables that will be used to store data that is loaded. * * @param searchCache maps FormRecord ID to an array of query-able form descriptor text * @param formNames map from form namespaces to their titles */ public void init(Hashtable<Integer, String[]> searchCache, Hashtable<String, Text> formNames) { this.searchCache = searchCache; if (descriptorCache == null) { descriptorCache = new Hashtable<>(); } priorityQueue.clear(); loaded.clear(); this.formNames = formNames; } /** * Set the listeners list, whose callbacks will be executed once the data * has been loaded. * * @param listeners a list of objects to call when data is done loading */ private void setListeners(ArrayList<FormRecordLoadListener> listeners) { this.listeners.addAll(listeners); } /** * Add a listener to the list that is called once the data has been loaded. * * @param listener an objects to call when data is done loading */ public void addListener(FormRecordLoadListener listener) { this.listeners.add(listener); } @Override protected Integer doInBackground(FormRecord... params) { // Load text information for every FormRecord passed in, unless task is // cancelled before that. FormRecord current; int loadedFormCount = 0; while (loadedFormCount < params.length && !isCancelled()) { synchronized (priorityQueue) { //If we have one to do immediately, grab it if (!priorityQueue.isEmpty()) { current = priorityQueue.poll(); } else { current = params[loadedFormCount++]; } if (loaded.contains(current.getID())) { // skip if we already loaded this record due to priority queue continue; } } // load text about this record: last modified date, title of the record, and form name ArrayList<String> recordTextDesc = loadRecordText(current); loaded.add(current.getID()); // Copy data into search task and notify anything waiting on this // record. this.publishProgress(new Pair<>(current, recordTextDesc)); } return 1; } private ArrayList<String> loadRecordText(FormRecord current) { ArrayList<String> recordTextDesc = new ArrayList<>(); // Get the date in a searchable format. recordTextDesc.add(DateUtils.formatDateTime(context, current.lastModified().getTime(), DateUtils.FORMAT_NO_MONTH_DAY | DateUtils.FORMAT_NO_YEAR).toLowerCase()); String dataTitle = current.getDescriptor(); if (TextUtils.isEmpty(dataTitle)) { dataTitle = loadDataTitle(current.getID()); } recordTextDesc.add(dataTitle); if (formNames.containsKey(current.getFormNamespace())) { Text name = formNames.get(current.getFormNamespace()); recordTextDesc.add(name.evaluate()); } return recordTextDesc; } private String loadDataTitle(int formRecordId) { // Grab our record hash SessionStateDescriptor ssd = null; try { ssd = descriptorStorage.getRecordForValue(SessionStateDescriptor.META_FORM_RECORD_ID, formRecordId); } catch (NoSuchElementException nsee) { //s'all good } String dataTitle = ""; if (ssd != null) { String descriptor = ssd.getSessionDescriptor(); if (!descriptorCache.containsKey(descriptor)) { AndroidSessionWrapper asw = new AndroidSessionWrapper(platform); asw.loadFromStateDescription(ssd); try { dataTitle = FormDataUtil.getTitleFromSession(new AndroidSandbox(CommCareApplication.instance()), asw.getSession(), asw.getEvaluationContext()); } catch (RuntimeException e) { dataTitle = "[Unavailable]"; } if (dataTitle == null) { dataTitle = ""; } descriptorCache.put(descriptor, dataTitle); } else { return descriptorCache.get(descriptor); } } return dataTitle; } @Override protected void onPreExecute() { super.onPreExecute(); // Tell users of the data being loaded that it isn't ready yet. this.loadingComplete = false; } /** * Has all the FormRecords' textual data been loaded yet? Used to let * users of the data only start accessing it once it is all there. */ public boolean doneLoadingFormRecords() { return this.loadingComplete; } @Override protected void onPostExecute(Integer result) { super.onPostExecute(result); this.loadingComplete = true; for (FormRecordLoadListener listener : this.listeners) { if (listener != null) { listener.notifyLoaded(); } } // free up things we don't need to spawn new tasks priorityQueue.clear(); loaded.clear(); formNames = null; } @Override protected void onProgressUpdate(Pair<FormRecord, ArrayList<String>>... values) { super.onProgressUpdate(values); // copy a single form record's data out of method arguments String[] vals = new String[values[0].second.size()]; for (int i = 0; i < vals.length; ++i) { vals[i] = values[0].second.get(i); } // store the loaded data in the search cache this.searchCache.put(values[0].first.getID(), vals); for (FormRecordLoadListener listener : this.listeners) { if (listener != null) { // TODO PLM: pretty sure loaded.contains(values[0].first) is // always true at this point. listener.notifyPriorityLoaded(values[0].first, loaded.contains(values[0].first.getID())); } } } public boolean registerPriority(FormRecord record) { synchronized (priorityQueue) { if (loaded.contains(record.getID())) { return false; } else if (priorityQueue.contains(record)) { // if we already have it in the queue, just move along return true; } else { priorityQueue.add(record); return true; } } } }
dimagi/commcare-android
app/src/org/commcare/tasks/FormRecordLoaderTask.java
Java
apache-2.0
10,155
/* Copyright 2019 Telstra Open Source * * 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.openkilda.wfm.topology.network.controller; import org.openkilda.persistence.PersistenceManager; import org.openkilda.persistence.repositories.FeatureTogglesRepository; import org.openkilda.wfm.share.model.Endpoint; import org.openkilda.wfm.share.utils.AbstractBaseFsm; import org.openkilda.wfm.share.utils.FsmExecutor; import org.openkilda.wfm.topology.network.service.IBfdGlobalToggleCarrier; import lombok.Builder; import lombok.Value; import org.squirrelframework.foundation.fsm.StateMachineBuilder; import org.squirrelframework.foundation.fsm.StateMachineBuilderFactory; public class BfdGlobalToggleFsm extends AbstractBaseFsm<BfdGlobalToggleFsm, BfdGlobalToggleFsm.BfdGlobalToggleFsmState, BfdGlobalToggleFsm.BfdGlobalToggleFsmEvent, BfdGlobalToggleFsm.BfdGlobalToggleFsmContext> { private final IBfdGlobalToggleCarrier carrier; private final Endpoint endpoint; public static BfdGlobalToggleFsmFactory factory(PersistenceManager persistenceManager) { return new BfdGlobalToggleFsmFactory(persistenceManager); } // -- FSM actions -- public void emitBfdKill(BfdGlobalToggleFsmState from, BfdGlobalToggleFsmState to, BfdGlobalToggleFsmEvent event, BfdGlobalToggleFsmContext context) { log.info("BFD event KILL for {}", endpoint); carrier.filteredBfdKillNotification(endpoint); } public void emitBfdUp(BfdGlobalToggleFsmState from, BfdGlobalToggleFsmState to, BfdGlobalToggleFsmEvent event, BfdGlobalToggleFsmContext context) { log.info("BFD event UP for {}", endpoint); carrier.filteredBfdUpNotification(endpoint); } public void emitBfdDown(BfdGlobalToggleFsmState from, BfdGlobalToggleFsmState to, BfdGlobalToggleFsmEvent event, BfdGlobalToggleFsmContext context) { log.info("BFD event DOWN for {}", endpoint); carrier.filteredBfdDownNotification(endpoint); } public void emitBfdFail(BfdGlobalToggleFsmState from, BfdGlobalToggleFsmState to, BfdGlobalToggleFsmEvent event, BfdGlobalToggleFsmContext context) { log.info("BFD event FAIL for {}", endpoint); carrier.filteredBfdFailNotification(endpoint); } // -- private/service methods -- // -- service data types -- public BfdGlobalToggleFsm(IBfdGlobalToggleCarrier carrier, Endpoint endpoint) { this.carrier = carrier; this.endpoint = endpoint; } public static class BfdGlobalToggleFsmFactory { private final FeatureTogglesRepository featureTogglesRepository; private final StateMachineBuilder<BfdGlobalToggleFsm, BfdGlobalToggleFsmState, BfdGlobalToggleFsmEvent, BfdGlobalToggleFsmContext> builder; BfdGlobalToggleFsmFactory(PersistenceManager persistenceManager) { featureTogglesRepository = persistenceManager.getRepositoryFactory().createFeatureTogglesRepository(); final String emitBfdKillMethod = "emitBfdKill"; final String emitBfdFailMethod = "emitBfdFail"; builder = StateMachineBuilderFactory.create( BfdGlobalToggleFsm.class, BfdGlobalToggleFsmState.class, BfdGlobalToggleFsmEvent.class, BfdGlobalToggleFsmContext.class, // extra parameters IBfdGlobalToggleCarrier.class, Endpoint.class); // DOWN_ENABLED builder.transition() .from(BfdGlobalToggleFsmState.DOWN_ENABLED).to(BfdGlobalToggleFsmState.DOWN_DISABLED) .on(BfdGlobalToggleFsmEvent.DISABLE); builder.transition() .from(BfdGlobalToggleFsmState.DOWN_ENABLED).to(BfdGlobalToggleFsmState.UP_ENABLED) .on(BfdGlobalToggleFsmEvent.BFD_UP); builder.internalTransition() .within(BfdGlobalToggleFsmState.DOWN_ENABLED).on(BfdGlobalToggleFsmEvent.BFD_KILL) .callMethod(emitBfdKillMethod); builder.internalTransition() .within(BfdGlobalToggleFsmState.DOWN_ENABLED).on(BfdGlobalToggleFsmEvent.BFD_FAIL) .callMethod(emitBfdFailMethod); // DOWN_DISABLED builder.transition() .from(BfdGlobalToggleFsmState.DOWN_DISABLED).to(BfdGlobalToggleFsmState.DOWN_ENABLED) .on(BfdGlobalToggleFsmEvent.ENABLE); builder.transition() .from(BfdGlobalToggleFsmState.DOWN_DISABLED).to(BfdGlobalToggleFsmState.UP_DISABLED) .on(BfdGlobalToggleFsmEvent.BFD_UP); builder.internalTransition() .within(BfdGlobalToggleFsmState.DOWN_DISABLED).on(BfdGlobalToggleFsmEvent.BFD_FAIL) .callMethod(emitBfdFailMethod); // UP_ENABLED builder.transition() .from(BfdGlobalToggleFsmState.UP_ENABLED).to(BfdGlobalToggleFsmState.UP_DISABLED) .on(BfdGlobalToggleFsmEvent.DISABLE) .callMethod(emitBfdKillMethod); builder.transition() .from(BfdGlobalToggleFsmState.UP_ENABLED).to(BfdGlobalToggleFsmState.DOWN_ENABLED) .on(BfdGlobalToggleFsmEvent.BFD_DOWN) .callMethod("emitBfdDown"); builder.transition() .from(BfdGlobalToggleFsmState.UP_ENABLED).to(BfdGlobalToggleFsmState.DOWN_ENABLED) .on(BfdGlobalToggleFsmEvent.BFD_KILL) .callMethod(emitBfdKillMethod); builder.onEntry(BfdGlobalToggleFsmState.UP_ENABLED) .callMethod("emitBfdUp"); // UP_DISABLED builder.transition() .from(BfdGlobalToggleFsmState.UP_DISABLED).to(BfdGlobalToggleFsmState.UP_ENABLED) .on(BfdGlobalToggleFsmEvent.ENABLE); builder.transition() .from(BfdGlobalToggleFsmState.UP_DISABLED).to(BfdGlobalToggleFsmState.DOWN_DISABLED) .on(BfdGlobalToggleFsmEvent.BFD_DOWN); } public FsmExecutor<BfdGlobalToggleFsm, BfdGlobalToggleFsmState, BfdGlobalToggleFsmEvent, BfdGlobalToggleFsmContext> produceExecutor() { return new FsmExecutor<>(BfdGlobalToggleFsmEvent.NEXT); } /** * Determine initial state and create {@link BfdGlobalToggleFsm} instance. */ public BfdGlobalToggleFsm produce(IBfdGlobalToggleCarrier carrier, Endpoint endpoint) { Boolean toggle = featureTogglesRepository.getOrDefault().getUseBfdForIslIntegrityCheck(); if (toggle == null) { throw new IllegalStateException("Unable to identify initial BFD-global-toggle value (it is null at" + " this moment)"); } BfdGlobalToggleFsmState state; if (toggle) { state = BfdGlobalToggleFsmState.DOWN_ENABLED; } else { state = BfdGlobalToggleFsmState.DOWN_DISABLED; } return builder.newStateMachine(state, carrier, endpoint); } } @Value @Builder public static class BfdGlobalToggleFsmContext { } public enum BfdGlobalToggleFsmState { DOWN_DISABLED, DOWN_ENABLED, UP_DISABLED, UP_ENABLED } public enum BfdGlobalToggleFsmEvent { KILL, NEXT, ENABLE, DISABLE, BFD_UP, BFD_DOWN, BFD_KILL, BFD_FAIL } }
jonvestal/open-kilda
src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/controller/BfdGlobalToggleFsm.java
Java
apache-2.0
8,262
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.execution.datasources.orc import org.apache.hadoop.hive.common.`type`.HiveDecimal import org.apache.hadoop.hive.ql.io.sarg.{PredicateLeaf, SearchArgument} import org.apache.hadoop.hive.ql.io.sarg.SearchArgument.Builder import org.apache.hadoop.hive.ql.io.sarg.SearchArgumentFactory.newBuilder import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable import org.apache.spark.SparkException import org.apache.spark.sql.connector.catalog.CatalogV2Implicits.quoteIfNeeded import org.apache.spark.sql.sources.Filter import org.apache.spark.sql.types._ /** * Helper object for building ORC `SearchArgument`s, which are used for ORC predicate push-down. * * Due to limitation of ORC `SearchArgument` builder, we had to implement separate checking and * conversion passes through the Filter to make sure we only convert predicates that are known * to be convertible. * * An ORC `SearchArgument` must be built in one pass using a single builder. For example, you can't * build `a = 1` and `b = 2` first, and then combine them into `a = 1 AND b = 2`. This is quite * different from the cases in Spark SQL or Parquet, where complex filters can be easily built using * existing simpler ones. * * The annoying part is that, `SearchArgument` builder methods like `startAnd()`, `startOr()`, and * `startNot()` mutate internal state of the builder instance. This forces us to translate all * convertible filters with a single builder instance. However, if we try to translate a filter * before checking whether it can be converted or not, we may end up with a builder whose internal * state is inconsistent in the case of an inconvertible filter. * * For example, to convert an `And` filter with builder `b`, we call `b.startAnd()` first, and then * try to convert its children. Say we convert `left` child successfully, but find that `right` * child is inconvertible. Alas, `b.startAnd()` call can't be rolled back, and `b` is inconsistent * now. * * The workaround employed here is to trim the Spark filters before trying to convert them. This * way, we can only do the actual conversion on the part of the Filter that is known to be * convertible. * * P.S.: Hive seems to use `SearchArgument` together with `ExprNodeGenericFuncDesc` only. Usage of * builder methods mentioned above can only be found in test code, where all tested filters are * known to be convertible. */ private[sql] object OrcFilters extends OrcFiltersBase { /** * Create ORC filter as a SearchArgument instance. */ def createFilter(schema: StructType, filters: Seq[Filter]): Option[SearchArgument] = { val dataTypeMap = schema.map(f => f.name -> f.dataType).toMap // Combines all convertible filters using `And` to produce a single conjunction val conjunctionOptional = buildTree(convertibleFilters(schema, dataTypeMap, filters)) conjunctionOptional.map { conjunction => // Then tries to build a single ORC `SearchArgument` for the conjunction predicate. // The input predicate is fully convertible. There should not be any empty result in the // following recursive method call `buildSearchArgument`. buildSearchArgument(dataTypeMap, conjunction, newBuilder).build() } } def convertibleFilters( schema: StructType, dataTypeMap: Map[String, DataType], filters: Seq[Filter]): Seq[Filter] = { import org.apache.spark.sql.sources._ def convertibleFiltersHelper( filter: Filter, canPartialPushDown: Boolean): Option[Filter] = filter match { // At here, it is not safe to just convert one side and remove the other side // if we do not understand what the parent filters are. // // Here is an example used to explain the reason. // Let's say we have NOT(a = 2 AND b in ('1')) and we do not understand how to // convert b in ('1'). If we only convert a = 2, we will end up with a filter // NOT(a = 2), which will generate wrong results. // // Pushing one side of AND down is only safe to do at the top level or in the child // AND before hitting NOT or OR conditions, and in this case, the unsupported predicate // can be safely removed. case And(left, right) => val leftResultOptional = convertibleFiltersHelper(left, canPartialPushDown) val rightResultOptional = convertibleFiltersHelper(right, canPartialPushDown) (leftResultOptional, rightResultOptional) match { case (Some(leftResult), Some(rightResult)) => Some(And(leftResult, rightResult)) case (Some(leftResult), None) if canPartialPushDown => Some(leftResult) case (None, Some(rightResult)) if canPartialPushDown => Some(rightResult) case _ => None } // The Or predicate is convertible when both of its children can be pushed down. // That is to say, if one/both of the children can be partially pushed down, the Or // predicate can be partially pushed down as well. // // Here is an example used to explain the reason. // Let's say we have // (a1 AND a2) OR (b1 AND b2), // a1 and b1 is convertible, while a2 and b2 is not. // The predicate can be converted as // (a1 OR b1) AND (a1 OR b2) AND (a2 OR b1) AND (a2 OR b2) // As per the logical in And predicate, we can push down (a1 OR b1). case Or(left, right) => for { lhs <- convertibleFiltersHelper(left, canPartialPushDown) rhs <- convertibleFiltersHelper(right, canPartialPushDown) } yield Or(lhs, rhs) case Not(pred) => val childResultOptional = convertibleFiltersHelper(pred, canPartialPushDown = false) childResultOptional.map(Not) case other => for (_ <- buildLeafSearchArgument(dataTypeMap, other, newBuilder())) yield other } filters.flatMap { filter => convertibleFiltersHelper(filter, true) } } /** * Get PredicateLeafType which is corresponding to the given DataType. */ private def getPredicateLeafType(dataType: DataType) = dataType match { case BooleanType => PredicateLeaf.Type.BOOLEAN case ByteType | ShortType | IntegerType | LongType => PredicateLeaf.Type.LONG case FloatType | DoubleType => PredicateLeaf.Type.FLOAT case StringType => PredicateLeaf.Type.STRING case DateType => PredicateLeaf.Type.DATE case TimestampType => PredicateLeaf.Type.TIMESTAMP case _: DecimalType => PredicateLeaf.Type.DECIMAL case _ => throw new UnsupportedOperationException(s"DataType: ${dataType.catalogString}") } /** * Cast literal values for filters. * * We need to cast to long because ORC raises exceptions * at 'checkLiteralType' of SearchArgumentImpl.java. */ private def castLiteralValue(value: Any, dataType: DataType): Any = dataType match { case ByteType | ShortType | IntegerType | LongType => value.asInstanceOf[Number].longValue case FloatType | DoubleType => value.asInstanceOf[Number].doubleValue() case _: DecimalType => new HiveDecimalWritable(HiveDecimal.create(value.asInstanceOf[java.math.BigDecimal])) case _ => value } /** * Build a SearchArgument and return the builder so far. * * @param dataTypeMap a map from the attribute name to its data type. * @param expression the input predicates, which should be fully convertible to SearchArgument. * @param builder the input SearchArgument.Builder. * @return the builder so far. */ private def buildSearchArgument( dataTypeMap: Map[String, DataType], expression: Filter, builder: Builder): Builder = { import org.apache.spark.sql.sources._ expression match { case And(left, right) => val lhs = buildSearchArgument(dataTypeMap, left, builder.startAnd()) val rhs = buildSearchArgument(dataTypeMap, right, lhs) rhs.end() case Or(left, right) => val lhs = buildSearchArgument(dataTypeMap, left, builder.startOr()) val rhs = buildSearchArgument(dataTypeMap, right, lhs) rhs.end() case Not(child) => buildSearchArgument(dataTypeMap, child, builder.startNot()).end() case other => buildLeafSearchArgument(dataTypeMap, other, builder).getOrElse { throw new SparkException( "The input filter of OrcFilters.buildSearchArgument should be fully convertible.") } } } /** * Build a SearchArgument for a leaf predicate and return the builder so far. * * @param dataTypeMap a map from the attribute name to its data type. * @param expression the input filter predicates. * @param builder the input SearchArgument.Builder. * @return the builder so far. */ private def buildLeafSearchArgument( dataTypeMap: Map[String, DataType], expression: Filter, builder: Builder): Option[Builder] = { def getType(attribute: String): PredicateLeaf.Type = getPredicateLeafType(dataTypeMap(attribute)) import org.apache.spark.sql.sources._ // NOTE: For all case branches dealing with leaf predicates below, the additional `startAnd()` // call is mandatory. ORC `SearchArgument` builder requires that all leaf predicates must be // wrapped by a "parent" predicate (`And`, `Or`, or `Not`). // Since ORC 1.5.0 (ORC-323), we need to quote for column names with `.` characters // in order to distinguish predicate pushdown for nested columns. expression match { case EqualTo(attribute, value) if isSearchableType(dataTypeMap(attribute)) => val quotedName = quoteIfNeeded(attribute) val castedValue = castLiteralValue(value, dataTypeMap(attribute)) Some(builder.startAnd().equals(quotedName, getType(attribute), castedValue).end()) case EqualNullSafe(attribute, value) if isSearchableType(dataTypeMap(attribute)) => val quotedName = quoteIfNeeded(attribute) val castedValue = castLiteralValue(value, dataTypeMap(attribute)) Some(builder.startAnd().nullSafeEquals(quotedName, getType(attribute), castedValue).end()) case LessThan(attribute, value) if isSearchableType(dataTypeMap(attribute)) => val quotedName = quoteIfNeeded(attribute) val castedValue = castLiteralValue(value, dataTypeMap(attribute)) Some(builder.startAnd().lessThan(quotedName, getType(attribute), castedValue).end()) case LessThanOrEqual(attribute, value) if isSearchableType(dataTypeMap(attribute)) => val quotedName = quoteIfNeeded(attribute) val castedValue = castLiteralValue(value, dataTypeMap(attribute)) Some(builder.startAnd().lessThanEquals(quotedName, getType(attribute), castedValue).end()) case GreaterThan(attribute, value) if isSearchableType(dataTypeMap(attribute)) => val quotedName = quoteIfNeeded(attribute) val castedValue = castLiteralValue(value, dataTypeMap(attribute)) Some(builder.startNot().lessThanEquals(quotedName, getType(attribute), castedValue).end()) case GreaterThanOrEqual(attribute, value) if isSearchableType(dataTypeMap(attribute)) => val quotedName = quoteIfNeeded(attribute) val castedValue = castLiteralValue(value, dataTypeMap(attribute)) Some(builder.startNot().lessThan(quotedName, getType(attribute), castedValue).end()) case IsNull(attribute) if isSearchableType(dataTypeMap(attribute)) => val quotedName = quoteIfNeeded(attribute) Some(builder.startAnd().isNull(quotedName, getType(attribute)).end()) case IsNotNull(attribute) if isSearchableType(dataTypeMap(attribute)) => val quotedName = quoteIfNeeded(attribute) Some(builder.startNot().isNull(quotedName, getType(attribute)).end()) case In(attribute, values) if isSearchableType(dataTypeMap(attribute)) => val quotedName = quoteIfNeeded(attribute) val castedValues = values.map(v => castLiteralValue(v, dataTypeMap(attribute))) Some(builder.startAnd().in(quotedName, getType(attribute), castedValues.map(_.asInstanceOf[AnyRef]): _*).end()) case _ => None } } }
goldmedal/spark
sql/core/v2.3/src/main/scala/org/apache/spark/sql/execution/datasources/orc/OrcFilters.scala
Scala
apache-2.0
12,961
using System; namespace NativeAppFabricConsoleUI { internal static class CreateRegionTests { internal static void CreateRegionWithNonEmptyString() { try { Logger.PrintTestStartInformation("Creating Region with non-empty string value"); string myRegion = Guid.NewGuid().ToString(); var result = Program.myDefaultCache.CreateRegion(myRegion); if (result) { Logger.PrintSuccessfulOutcome($"Region {myRegion} successfully created"); } else { Logger.PrintFailureOutcome($"Region {myRegion} could not be created"); } } catch (Exception e) { Logger.PrintDataCacheException(e); } finally { Logger.PrintBreakLine(); } } internal static void RecreateRegionWithNonEmptyString() { try { Logger.PrintTestStartInformation("Creating Another Region with Same Name"); string myRegion = Guid.NewGuid().ToString(); var result = Program.myDefaultCache.CreateRegion(myRegion); result = Program.myDefaultCache.CreateRegion(myRegion); if (result) { Logger.PrintSuccessfulOutcome($"Region {myRegion} successfully recreated"); } else { Logger.PrintFailureOutcome($"Region {myRegion} could not be recreated"); } } catch (Exception e) { Logger.PrintDataCacheException(e); } finally { Logger.PrintBreakLine(); } } internal static void CreateRegionWithNullString() { try { Logger.PrintTestStartInformation("Creating Another Region with NULL Region Name"); string myRegion = null; var result = Program.myDefaultCache.CreateRegion(myRegion); if (result) { Logger.PrintSuccessfulOutcome($"Region successfully created"); } else { Logger.PrintFailureOutcome($"Region could not be created"); } } catch (Exception e) { Logger.PrintDataCacheException(e); } finally { Logger.PrintBreakLine(); } } } }
Alachisoft/NCache-Wrapper-For-AppFabric
samples/AppFabricWrapperTest/NativeAppFabricConsoleUI/RegionLevelBasicOperations/CreateRegionTests.cs
C#
apache-2.0
2,744
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>create canvas</title> <link rel="stylesheet" href="../canvas/main.css"> <style> div { font-family: monospace; font-size: 20px; color: white; } </style> </head> <body> <div>Break all the Bricks to win, use A and D keys to move</div> <canvas width=600 height=600></canvas> <script> canvas = document.querySelector('canvas'); c = canvas.getContext('2d'); canvasHeight = 600; canvasWidth = 600; function Sound(file) { this.sound = new Audio(file); this.play = function() { this.sound.load(); this.sound.play(); } } sound = new Sound('audio/bounce.wav') // 540.1952278698604 655.9901418947481 function init() { mousepos = { x: null, y: null }; var column = 8; var row = 3; var bSpaceY = 30; var bY = 10; var bH = 20; var bSpaceX = (canvasWidth - 10) / column var bW = bSpaceX - 10; var bX = 10; blocks = [] for (var a = 0; a < row; a++) { for (var b = 0; b < column; b++) { blocks.push(new Block(bX, bY, bW, bH)); bX += bSpaceX; } bY += bSpaceY; bX = 10 }; win = false; } function Restart(x, y, w, h) { this.x = x; this.y = y; this.w = w; this.h = h; this.tx = this.x + 10; this.ty = this.y + 10; this.tw = this.w - 20; this.draw = function() { c.beginPath(); c.strokeStyle = 'lime'; c.strokeRect(this.x, this.y, this.w, this.h); c.font = '30px Arial'; c.fillStyle = 'lime' c.fillText('Restart', this.tx, this.ty, this.tw) }; if (this.x <= mousepos.x && mousepos.x <= this.x + 100 && this.y <= mousepos.y && mousepos.y <= this.y + 40) { cancelAnimationFrame = false; restart.restart() }; this.restart = function() { init(); circle.x = Math.random() * 500 + 50 circle.y = Math.random() * 200 + 50 }; }; function Block(x, y, w, h) { this.x = x this.y = y this.w = w this.h = h this.draw = function() { c.fillStyle = 'Darkred'; c.fillRect(this.x, this.y, this.w, this.h) } this.hitDetection = function(cx, cy, i) { if (this.x <= cx && cx <= this.x + this.w && cy - 20 <= this.y + this.h && this.y <= cy + 20) { circle.ys = -circle.ys; sound.play(); blocks.splice(i, 1) }; if (this.y <= cy && cy <= this.y + this.h && cx + 20 >= this.x && this.x + bW >= cx - 20) { circle.xs = -circle.xs; sound.play(); blocks.splice(i, 1) } } } function Paddle(x, y, w, h) { this.x = x this.y = y this.w = w this.h = h this.move = function() { if (left == true && this.x > 0) { this.x -= 8; } if (right == true && this.x + 100 < 600) { this.x += 8; } } this.draw = function() { paddle.move(); c.fillStyle = 'red' c.fillRect(this.x, this.y, this.w, this.h); } this.hitDetection = function(x, y) { if (this.x < x + 20 && x - 20 < this.x + 100 && 584 >= y + 20 && y + 20 >= 580) { circle.ys = -circle.ys; sound.play(); } } } var left = false var right = false document.addEventListener('keydown', function(e) { key = e.keyCode; if (key === 65 || key === 37) { left = true; } else if (key === 68 || key === 39) { right = true; } }); document.addEventListener('keyup', function(e) { key = e.keyCode; if (key === 65 || key === 37) { left = false; } else if (key === 68 || key === 39) { right = false; } else if (key === 13) { cancelAnimationFrame = false; restart.restart() } }); mousepos = { x: null, y: null } canvas.addEventListener('click', function(e) { mousepos.x = e.offsetX mousepos.y = e.offsetY }); function Circle(x, y, r) { this.x = x this.y = y this.r = r this.xs = 6 this.ys = 4 this.update = function() { if (0 >= this.x - 20 || this.x + 20 >= 600) { this.xs = -this.xs sound.play(); } if (0 >= this.y - 20) { this.ys = -this.ys sound.play(); } if (this.y + 20 >= 600) { cancelAnimationFrame = true } paddle.hitDetection(this.x, this.y); for (var i = 0; i < blocks.length; i++) { blocks[i].hitDetection(this.x, this.y, i); } this.x += this.xs; this.y += this.ys; } this.draw = function() { circle.update(); c.beginPath(); var g = c.createRadialGradient(this.x - 5, this.y - 5, 1, this.x, this.y, this.r) g.addColorStop(0, 'yellow'); g.addColorStop(0.3, 'orange'); g.addColorStop(1, 'black'); c.fillStyle = g; c.arc(this.x, this.y, this.r, 0, Math.PI * 2, false); c.fill(); } } //////////// Column, Row for blocks //////////// var column = 8; var row = 3; var bSpaceY = 30; var bY = 10; var bH = 20; var bSpaceX = (canvasWidth - 10) / column var bW = bSpaceX - 10; var bX = 10; blocks = [] for (var a = 0; a < row; a++) { for (var b = 0; b < column; b++) { blocks.push(new Block(bX, bY, bW, bH)); bX += bSpaceX; } bY += bSpaceY; bX = 10 }; win = false; paddle = new Paddle(250, 580, 100, 10); circle = new Circle(Math.random() * 500 + 50, Math.random() * 200 + 50, 20); cancelAnimationFrame = false; function anim() { requestAnimationFrame(anim) if (blocks.length === 0) { c.font = "50px Arial"; c.textBaseline = 'hanging'; c.fillStyle = 'Black'; c.fillText('You Win!', 200, 300, 180); restart = new Restart(250, 360, 100, 40); restart.draw(); } else if (cancelAnimationFrame === false) { c.clearRect(0, 0, 600, 600); paddle.draw(); circle.draw(); for (var i = 0; i < (blocks.length); i++) { blocks[i].draw(); } } else { c.font = "50px Arial"; c.textBaseline = 'hanging'; c.fillStyle = 'Black'; c.fillText('Game Over!', 200, 300, 200); restart = new Restart(250, 360, 100, 40); restart.draw(); } } anim() </script> </body> </html>
MLG369/MLG369.github.io
Old_Stuff/JS/JS_Core/Homework/BrickBreaker.html
HTML
apache-2.0
8,342
package org.nbone.core.util; /** * * @author thinking * @version 1.0 * @since 2019-07-20 * org.elasticsearch.common.unit.ByteSizeUnit */ public enum ByteSizeUnit { BYTES { @Override public long toBytes(long size) { return size; } @Override public long toKB(long size) { return size / (C1 / C0); } @Override public long toMB(long size) { return size / (C2 / C0); } @Override public long toGB(long size) { return size / (C3 / C0); } @Override public long toTB(long size) { return size / (C4 / C0); } @Override public long toPB(long size) { return size / (C5 / C0); } }, KB { @Override public long toBytes(long size) { return x(size, C1 / C0, MAX / (C1 / C0)); } @Override public long toKB(long size) { return size; } @Override public long toMB(long size) { return size / (C2 / C1); } @Override public long toGB(long size) { return size / (C3 / C1); } @Override public long toTB(long size) { return size / (C4 / C1); } @Override public long toPB(long size) { return size / (C5 / C1); } }, MB { @Override public long toBytes(long size) { return x(size, C2 / C0, MAX / (C2 / C0)); } @Override public long toKB(long size) { return x(size, C2 / C1, MAX / (C2 / C1)); } @Override public long toMB(long size) { return size; } @Override public long toGB(long size) { return size / (C3 / C2); } @Override public long toTB(long size) { return size / (C4 / C2); } @Override public long toPB(long size) { return size / (C5 / C2); } }, GB { @Override public long toBytes(long size) { return x(size, C3 / C0, MAX / (C3 / C0)); } @Override public long toKB(long size) { return x(size, C3 / C1, MAX / (C3 / C1)); } @Override public long toMB(long size) { return x(size, C3 / C2, MAX / (C3 / C2)); } @Override public long toGB(long size) { return size; } @Override public long toTB(long size) { return size / (C4 / C3); } @Override public long toPB(long size) { return size / (C5 / C3); } }, TB { @Override public long toBytes(long size) { return x(size, C4 / C0, MAX / (C4 / C0)); } @Override public long toKB(long size) { return x(size, C4 / C1, MAX / (C4 / C1)); } @Override public long toMB(long size) { return x(size, C4 / C2, MAX / (C4 / C2)); } @Override public long toGB(long size) { return x(size, C4 / C3, MAX / (C4 / C3)); } @Override public long toTB(long size) { return size; } @Override public long toPB(long size) { return size / (C5 / C4); } }, PB { @Override public long toBytes(long size) { return x(size, C5 / C0, MAX / (C5 / C0)); } @Override public long toKB(long size) { return x(size, C5 / C1, MAX / (C5 / C1)); } @Override public long toMB(long size) { return x(size, C5 / C2, MAX / (C5 / C2)); } @Override public long toGB(long size) { return x(size, C5 / C3, MAX / (C5 / C3)); } @Override public long toTB(long size) { return x(size, C5 / C4, MAX / (C5 / C4)); } @Override public long toPB(long size) { return size; } }; static final long C0 = 1L; static final long C1 = C0 * 1024L; static final long C2 = C1 * 1024L; static final long C3 = C2 * 1024L; static final long C4 = C3 * 1024L; static final long C5 = C4 * 1024L; static final long MAX = Long.MAX_VALUE; /** * Scale d by m, checking for overflow. * This has a short name to make above code more readable. */ static long x(long d, long m, long over) { if (d > over) return Long.MAX_VALUE; if (d < -over) return Long.MIN_VALUE; return d * m; } public abstract long toBytes(long size); public abstract long toKB(long size); public abstract long toMB(long size); public abstract long toGB(long size); public abstract long toTB(long size); public abstract long toPB(long size); }
thinking-github/nbone
nbone/nbone-core/src/main/java/org/nbone/core/util/ByteSizeUnit.java
Java
apache-2.0
5,035
def emptyLayout(layout): for i in reversed(range(layout.count())): layout.itemAt(i).widget().setParent(None)
fireeye/flare-wmi
python-cim/samples/ui/uicommon.py
Python
apache-2.0
121
package scalacookbook.chapter03 /** * Created by liguodong on 2016/6/28. */ object UseMatchInsteadIsInstanceOf { // use the isInstanceOf method to test the type of an object // if (x.isInstanceOf[Foo]) { do something ... def isPerson(x: Any): Boolean = x match { case p: Person => true case _ => false } trait SentientBeing trait Animal extends SentientBeing case class Dog(name: String) extends Animal case class Person(name: String, age: Int) extends SentientBeing // later in the code ... def printInfo(x: SentientBeing) = x match { case Person(name, age) => // handle the Person case Dog(name) => // handle the Dog } //with more complex needs, a match expression is more readable // than an if/else statement. }
liguodongIOT/java-scala-mix-sbt
src/main/scala/scalacookbook/chapter03/UseMatchInsteadIsInstanceOf.scala
Scala
apache-2.0
769
// Copyright (c) 2009 Carl Barron // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <iostream> #include <sstream> #include <boost/detail/lightweight_test.hpp> #include <boost/spirit/include/lex.hpp> #include <boost/spirit/include/lex_lexertl.hpp> #include <boost/spirit/include/phoenix.hpp> namespace lex = boost::spirit::lex; namespace phoenix = boost::phoenix; /////////////////////////////////////////////////////////////////////////////// template <typename Lexer> struct multi_tokens : lex::lexer<Lexer> { int level; multi_tokens() : level(0) { using lex::_state; using lex::_start; using lex::_end; using lex::_pass; using lex::pass_flags; a = "A"; b = "B"; c = "C"; this->self = a [ ++phoenix::ref(level) ] | b | c [ _state = "in_dedenting", _end = _start, _pass = pass_flags::pass_ignore ] ; d = "."; this->self("in_dedenting") = d [ if_(--phoenix::ref(level)) [ _end = _start ] .else_ [ _state = "INITIAL" ] ] ; } lex::token_def<> a, b, c, d; }; struct dumper { typedef bool result_type; dumper(std::stringstream& strm) : strm(strm) {} template <typename Token> bool operator () (Token const &t) { strm << (char)(t.id() - lex::min_token_id + 'a'); return true; } std::stringstream& strm; private: // silence MSVC warning C4512: assignment operator could not be generated dumper& operator= (dumper const&); }; /////////////////////////////////////////////////////////////////////////////// int main() { typedef lex::lexertl::token<std::string::iterator> token_type; typedef lex::lexertl::actor_lexer<token_type> base_lexer_type; typedef multi_tokens<base_lexer_type> lexer_type; std::string in("AAABBC"); std::string::iterator first(in.begin()); std::stringstream strm; lexer_type the_lexer; BOOST_TEST(lex::tokenize(first, in.end(), the_lexer, dumper(strm))); BOOST_TEST(strm.str() == "aaabbddd"); return boost::report_errors(); }
Im-dex/xray-162
code/3rd-party/boost/libs/spirit/test/lex/dedent_handling_phoenix.cpp
C++
apache-2.0
2,510
/* * Copyright 2020 Google LLC * * 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 * * https://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. */ /** * Generates paragraph text style for a text element. * * @param {Object} props Props. * @param {function(number):any} dataToStyleX Converts a x-unit to CSS. * @param {function(number):any} dataToStyleY Converts a y-unit to CSS. * @param {function(number):any} dataToFontSizeY Converts a font-size metric to * y-unit CSS. * @param {Object<*>} element Text element properties. * @param {function(number):any} dataToPaddingY Falls back to dataToStyleX if not provided. * @return {Object} The map of text style properties and values. */ export function generateParagraphTextStyle( props, dataToStyleX, dataToStyleY, dataToFontSizeY = dataToStyleY, element, dataToPaddingY = dataToStyleY ) { const { font, fontSize, lineHeight, padding, textAlign } = props; const { marginOffset } = calcFontMetrics(element); const verticalPadding = padding?.vertical || 0; const horizontalPadding = padding?.horizontal || 0; const hasPadding = verticalPadding || horizontalPadding; const paddingStyle = hasPadding ? `${dataToStyleY(verticalPadding)} ${dataToStyleX(horizontalPadding)}` : 0; return { dataToEditorY: dataToStyleY, whiteSpace: 'pre-wrap', overflowWrap: 'break-word', wordBreak: 'break-word', margin: `${dataToPaddingY(-marginOffset / 2)} 0`, fontFamily: generateFontFamily(font), fontSize: dataToFontSizeY(fontSize), font, lineHeight, textAlign, padding: paddingStyle, }; } export const generateFontFamily = ({ family, fallbacks } = {}) => { const genericFamilyKeywords = [ 'cursive', 'fantasy', 'monospace', 'serif', 'sans-serif', ]; // Wrap into " since some fonts won't work without it. let fontFamilyDisplay = family ? `"${family}"` : ''; if (fallbacks && fallbacks.length) { fontFamilyDisplay += family ? `,` : ``; fontFamilyDisplay += fallbacks .map((fallback) => genericFamilyKeywords.includes(fallback) ? fallback : `"${fallback}"` ) .join(`,`); } return fontFamilyDisplay; }; export const getHighlightLineheight = function ( lineHeight, verticalPadding = 0, unit = 'px' ) { if (verticalPadding === 0) { return `${lineHeight}em`; } return `calc(${lineHeight}em ${verticalPadding > 0 ? '+' : '-'} ${ 2 * Math.abs(verticalPadding) }${unit})`; }; export function calcFontMetrics(element) { if (!element.font.metrics) { return { contentAreaPx: 0, lineBoxPx: 0, marginOffset: 0, }; } const { fontSize, lineHeight, font: { metrics: { upm, asc, des }, }, } = element; // We cant to cut some of the "virtual-area" // More info: https://iamvdo.me/en/blog/css-font-metrics-line-height-and-vertical-align const contentAreaPx = ((asc - des) / upm) * fontSize; const lineBoxPx = lineHeight * fontSize; const marginOffset = lineBoxPx - contentAreaPx; return { marginOffset, contentAreaPx, lineBoxPx, }; }
GoogleForCreators/web-stories-wp
packages/story-editor/src/elements/text/util.js
JavaScript
apache-2.0
3,563
<?php echo "This is success.php"; ?>
pari/rand0m
paypalipn/success.php
PHP
apache-2.0
38
/* * %CopyrightBegin% * * Copyright Ericsson AB 2006-2020. 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. * * %CopyrightEnd% */ /* * Description: Check I/O * * Author: Rickard Green */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #define ERL_CHECK_IO_C__ #ifndef WANT_NONBLOCKING # define WANT_NONBLOCKING #endif #include "sys.h" #include "global.h" #include "erl_port.h" #include "erl_check_io.h" #include "erl_thr_progress.h" #include "erl_bif_unique.h" #include "dtrace-wrapper.h" #include "lttng-wrapper.h" #define ERTS_WANT_TIMER_WHEEL_API #include "erl_time.h" #if 0 #define DEBUG_PRINT(FMT, ...) do { erts_printf(FMT "\r\n", ##__VA_ARGS__); fflush(stdout); } while(0) #define DEBUG_PRINT_FD(FMT, STATE, ...) \ DEBUG_PRINT("%d: " FMT " (ev=%s, ac=%s, flg=%s)", \ (STATE) ? (STATE)->fd : (ErtsSysFdType)-1, ##__VA_ARGS__, \ ev2str((STATE) ? (STATE)->events : ERTS_POLL_EV_NONE), \ ev2str((STATE) ? (STATE)->active_events : ERTS_POLL_EV_NONE), \ (STATE) ? flag2str((STATE)->flags) : ERTS_EV_FLAG_CLEAR) #define DEBUG_PRINT_MODE #else #define DEBUG_PRINT(...) #endif #ifndef DEBUG_PRINT_FD #define DEBUG_PRINT_FD(...) #endif #ifndef ERTS_SYS_CONTINOUS_FD_NUMBERS # include "safe_hash.h" # define DRV_EV_STATE_HTAB_SIZE 1024 #endif typedef enum { ERTS_EV_TYPE_NONE = 0, ERTS_EV_TYPE_DRV_SEL = 1, /* driver_select */ ERTS_EV_TYPE_STOP_USE = 2, /* pending stop_select */ ERTS_EV_TYPE_NIF = 3, /* enif_select */ ERTS_EV_TYPE_STOP_NIF = 4 /* pending nif stop */ } EventStateType; typedef enum { ERTS_EV_FLAG_CLEAR = 0, ERTS_EV_FLAG_USED = 1, /* ERL_DRV_USE has been turned on */ #if ERTS_POLL_USE_SCHEDULER_POLLING ERTS_EV_FLAG_SCHEDULER = 2, /* Set when the fd has been migrated to scheduler pollset */ ERTS_EV_FLAG_IN_SCHEDULER = 4, /* Set when the fd is currently in scheduler pollset */ #else ERTS_EV_FLAG_SCHEDULER = ERTS_EV_FLAG_CLEAR, ERTS_EV_FLAG_IN_SCHEDULER = ERTS_EV_FLAG_CLEAR, #endif #ifdef ERTS_POLL_USE_FALLBACK ERTS_EV_FLAG_FALLBACK = 8, /* Set when kernel poll rejected fd and it was put in the nkp version */ #else ERTS_EV_FLAG_FALLBACK = ERTS_EV_FLAG_CLEAR, #endif /* Combinations */ ERTS_EV_FLAG_USED_FALLBACK = ERTS_EV_FLAG_USED | ERTS_EV_FLAG_FALLBACK, ERTS_EV_FLAG_USED_SCHEDULER = ERTS_EV_FLAG_USED | ERTS_EV_FLAG_SCHEDULER, ERTS_EV_FLAG_USED_IN_SCHEDULER = ERTS_EV_FLAG_USED | ERTS_EV_FLAG_SCHEDULER | ERTS_EV_FLAG_IN_SCHEDULER, ERTS_EV_FLAG_UNUSED_SCHEDULER = ERTS_EV_FLAG_SCHEDULER, ERTS_EV_FLAG_UNUSED_IN_SCHEDULER = ERTS_EV_FLAG_SCHEDULER | ERTS_EV_FLAG_IN_SCHEDULER } EventStateFlags; #define flag2str(flags) \ ((flags) == ERTS_EV_FLAG_CLEAR ? "CLEAR" : \ ((flags) == ERTS_EV_FLAG_USED ? "USED" : \ ((flags) == ERTS_EV_FLAG_FALLBACK ? "FLBK" : \ ((flags) == ERTS_EV_FLAG_USED_FALLBACK ? "USED|FLBK" : \ ((flags) == ERTS_EV_FLAG_USED_SCHEDULER ? "USED|SCHD" : \ ((flags) == ERTS_EV_FLAG_UNUSED_SCHEDULER ? "SCHD" : \ ((flags) == ERTS_EV_FLAG_USED_IN_SCHEDULER ? "USED|IN_SCHD" : \ ((flags) == ERTS_EV_FLAG_UNUSED_IN_SCHEDULER ? "IN_SCHD" : \ "ERROR")))))))) /* How many events that can be handled at once by one erts_poll_wait call */ #define ERTS_CHECK_IO_POLL_RES_LEN 512 /* Each I/O Poll Thread has one ErtsPollThread each. The ps field can point to either a private ErtsPollSet or a shared one. At the moment only kqueue and epoll pollsets can be shared across threads. */ typedef struct erts_poll_thread { ErtsPollSet *ps; ErtsPollResFd *pollres; ErtsThrPrgrData *tpd; int pollres_len; } ErtsPollThread; /* pollsetv contains pointers to the ErtsPollSets that are in use. * Which pollset to use is determined by hashing the fd. */ static ErtsPollSet **pollsetv; static ErtsPollThread *psiv; #if ERTS_POLL_USE_FALLBACK static ErtsPollSet *flbk_pollset; #endif #if ERTS_POLL_USE_SCHEDULER_POLLING static ErtsPollSet *sched_pollset; #endif typedef struct { #ifndef ERTS_SYS_CONTINOUS_FD_NUMBERS SafeHashBucket hb; #endif ErtsSysFdType fd; struct { ErtsDrvSelectDataState *select; /* ERTS_EV_TYPE_DRV_SEL */ ErtsNifSelectDataState *nif; /* ERTS_EV_TYPE_NIF */ union { erts_driver_t* drv_ptr; /* ERTS_EV_TYPE_STOP_USE */ ErtsResource* resource; /* ERTS_EV_TYPE_STOP_NIF */ } stop; } driver; ErtsPollEvents events; /* The events that have been selected upon */ ErtsPollEvents active_events; /* The events currently active in the pollset */ EventStateType type; EventStateFlags flags; int count; /* Number of times this fd has triggered without being deselected. */ } ErtsDrvEventState; struct drv_ev_state_shared { union { erts_mtx_t lck; byte _cache_line_alignment[ERTS_ALC_CACHE_LINE_ALIGN_SIZE(sizeof(erts_mtx_t))]; } locks[ERTS_CHECK_IO_DRV_EV_STATE_LOCK_CNT]; #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS int max_fds; erts_atomic_t len; ErtsDrvEventState *v; erts_mtx_t grow_lock; /* prevent lock-hogging of racing growers */ #else SafeHash tab; int num_prealloc; ErtsDrvEventState *prealloc_first; erts_spinlock_t prealloc_lock; #endif }; int ERTS_WRITE_UNLIKELY(erts_no_pollsets) = 1; int ERTS_WRITE_UNLIKELY(erts_no_poll_threads) = 1; struct drv_ev_state_shared drv_ev_state; static ERTS_INLINE int fd_hash(ErtsSysFdType fd) { #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS int hash = (int)fd; #else int hash = (int)(SWord)fd; hash ^= (hash >> 9); #endif return hash; } static ERTS_INLINE erts_mtx_t* fd_mtx(ErtsSysFdType fd) { return &drv_ev_state.locks[fd_hash(fd) % ERTS_CHECK_IO_DRV_EV_STATE_LOCK_CNT].lck; } #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS static ERTS_INLINE ErtsDrvEventState *get_drv_ev_state(ErtsSysFdType fd) { return &drv_ev_state.v[(int) fd]; } #define new_drv_ev_state(State, fd) (State) #define erase_drv_ev_state(State) static ERTS_INLINE int grow_drv_ev_state(ErtsSysFdType fd) { int i; int old_len; int new_len; if ((unsigned)fd >= (unsigned)erts_atomic_read_nob(&drv_ev_state.len)) { if (fd < 0 || fd >= drv_ev_state.max_fds) return 0; erts_mtx_lock(&drv_ev_state.grow_lock); old_len = erts_atomic_read_nob(&drv_ev_state.len); if (fd >= old_len) { new_len = erts_poll_new_table_len(old_len, fd + 1); if (new_len > drv_ev_state.max_fds) new_len = drv_ev_state.max_fds; for (i=0; i<ERTS_CHECK_IO_DRV_EV_STATE_LOCK_CNT; i++) { /* lock all fd's */ erts_mtx_lock(&drv_ev_state.locks[i].lck); } drv_ev_state.v = (drv_ev_state.v ? erts_realloc(ERTS_ALC_T_DRV_EV_STATE, drv_ev_state.v, sizeof(ErtsDrvEventState)*new_len) : erts_alloc(ERTS_ALC_T_DRV_EV_STATE, sizeof(ErtsDrvEventState)*new_len)); ERTS_CT_ASSERT(ERTS_EV_TYPE_NONE == 0); sys_memzero(drv_ev_state.v+old_len, sizeof(ErtsDrvEventState) * (new_len - old_len)); for (i = old_len; i < new_len; i++) { drv_ev_state.v[i].fd = (ErtsSysFdType) i; } erts_atomic_set_nob(&drv_ev_state.len, new_len); for (i=0; i<ERTS_CHECK_IO_DRV_EV_STATE_LOCK_CNT; i++) { erts_mtx_unlock(&drv_ev_state.locks[i].lck); } } /*else already grown by racing thread */ erts_mtx_unlock(&drv_ev_state.grow_lock); } return 1; } static int drv_ev_state_len(void) { return erts_atomic_read_nob(&drv_ev_state.len); } #else /* !ERTS_SYS_CONTINOUS_FD_NUMBERS */ static ERTS_INLINE ErtsDrvEventState *get_drv_ev_state(ErtsSysFdType fd) { ErtsDrvEventState tmpl; tmpl.fd = fd; return (ErtsDrvEventState *) safe_hash_get(&drv_ev_state.tab, (void *) &tmpl); } static ERTS_INLINE ErtsDrvEventState* new_drv_ev_state(ErtsDrvEventState *state, ErtsSysFdType fd) { ErtsDrvEventState tmpl; if (state) return state; tmpl.fd = fd; tmpl.driver.select = NULL; tmpl.driver.nif = NULL; tmpl.driver.stop.drv_ptr = NULL; tmpl.events = 0; tmpl.active_events = 0; tmpl.type = ERTS_EV_TYPE_NONE; tmpl.flags = 0; return (ErtsDrvEventState *) safe_hash_put(&drv_ev_state.tab, (void *) &tmpl); } static ERTS_INLINE void erase_drv_ev_state(ErtsDrvEventState *state) { safe_hash_erase(&drv_ev_state.tab, (void *) state); } static int drv_ev_state_len(void) { return erts_atomic_read_nob(&drv_ev_state.tab.nitems); } #endif /* !ERTS_SYS_CONTINOUS_FD_NUMBERS */ static void stale_drv_select(Eterm id, ErtsDrvEventState *state, int mode); static void drv_select_steal(ErlDrvPort ix, ErtsDrvEventState *state, int mode, int on); static void nif_select_steal(ErtsDrvEventState *state, int mode, ErtsResource* resource, Eterm ref); static void print_drv_select_op(erts_dsprintf_buf_t *dsbufp, ErlDrvPort ix, ErtsSysFdType fd, int mode, int on); static void print_nif_select_op(erts_dsprintf_buf_t*, ErtsSysFdType, int mode, ErtsResource*, Eterm ref); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS static void drv_select_large_fd_error(ErlDrvPort, ErtsSysFdType, int, int); static void nif_select_large_fd_error(ErtsSysFdType, int, ErtsResource*,Eterm ref); #endif static void steal_pending_stop_use(erts_dsprintf_buf_t*, ErlDrvPort, ErtsDrvEventState*, int mode, int on); static void steal_pending_stop_nif(erts_dsprintf_buf_t *dsbufp, ErtsResource*, ErtsDrvEventState *state, int mode, int on); static ERTS_INLINE void check_fd_cleanup(ErtsDrvEventState *state, ErtsDrvSelectDataState **free_select, ErtsNifSelectDataState **free_nif); static ERTS_INLINE void iready(Eterm id, ErtsDrvEventState *state); static ERTS_INLINE void oready(Eterm id, ErtsDrvEventState *state); #ifdef DEBUG_PRINT_MODE static char *drvmode2str(int mode); static char *nifmode2str(enum ErlNifSelectFlags mode); #endif static ERTS_INLINE void init_iotask(ErtsIoTask *io_task, ErtsSysFdType fd) { erts_port_task_handle_init(&io_task->task); io_task->fd = fd; } static ERTS_INLINE int is_iotask_active(ErtsIoTask *io_task) { if (erts_port_task_is_scheduled(&io_task->task)) return 1; return 0; } static ERTS_INLINE ErtsDrvSelectDataState * alloc_drv_select_data(ErtsSysFdType fd) { ErtsDrvSelectDataState *dsp = erts_alloc(ERTS_ALC_T_DRV_SEL_D_STATE, sizeof(ErtsDrvSelectDataState)); dsp->inport = NIL; dsp->outport = NIL; init_iotask(&dsp->iniotask, fd); init_iotask(&dsp->outiotask, fd); return dsp; } static ERTS_INLINE ErtsNifSelectDataState * alloc_nif_select_data(void) { ErtsNifSelectDataState *dsp = erts_alloc(ERTS_ALC_T_NIF_SEL_D_STATE, sizeof(ErtsNifSelectDataState)); dsp->in.pid = NIL; dsp->out.pid = NIL; return dsp; } static ERTS_INLINE void free_drv_select_data(ErtsDrvSelectDataState *dsp) { ASSERT(!erts_port_task_is_scheduled(&dsp->iniotask.task)); ASSERT(!erts_port_task_is_scheduled(&dsp->outiotask.task)); erts_free(ERTS_ALC_T_DRV_SEL_D_STATE, dsp); } static ERTS_INLINE void free_nif_select_data(ErtsNifSelectDataState *dsp) { erts_free(ERTS_ALC_T_NIF_SEL_D_STATE, dsp); } static ERTS_INLINE int get_pollset_id(ErtsSysFdType fd) { return fd_hash(fd) % erts_no_pollsets; } static ERTS_INLINE ErtsPollSet * get_pollset(ErtsSysFdType fd) { return pollsetv[get_pollset_id(fd)]; } #if ERTS_POLL_USE_FALLBACK static ERTS_INLINE ErtsPollSet * get_fallback_pollset(void) { return flbk_pollset; } #endif static ERTS_INLINE ErtsPollSet * get_scheduler_pollset(ErtsSysFdType fd) { #if ERTS_POLL_USE_SCHEDULER_POLLING return sched_pollset; #else return get_pollset(fd); #endif } /* * Place a fd within a pollset. This will automatically use * the fallback ps if needed. */ static ERTS_INLINE ErtsPollEvents erts_io_control_wakeup(ErtsDrvEventState *state, ErtsPollOp op, ErtsPollEvents pe, int *wake_poller) { ErtsSysFdType fd = state->fd; ErtsPollEvents res = 0; EventStateFlags flags = state->flags; ERTS_LC_ASSERT(erts_lc_mtx_is_locked(fd_mtx(state->fd))); if (!(flags & ERTS_EV_FLAG_FALLBACK)) { if (op == ERTS_POLL_OP_DEL && (flags & ERTS_EV_FLAG_SCHEDULER)) { erts_poll_control(get_scheduler_pollset(fd), fd, op, pe, wake_poller); flags &= ~ERTS_EV_FLAG_IN_SCHEDULER; } if (!(flags & ERTS_EV_FLAG_IN_SCHEDULER) || (pe & ERTS_POLL_EV_OUT)) { res = erts_poll_control(get_pollset(fd), fd, op, pe, wake_poller); } else { res = erts_poll_control(get_scheduler_pollset(fd), fd, op, pe, wake_poller); } #if ERTS_POLL_USE_FALLBACK if (op == ERTS_POLL_OP_ADD && res == ERTS_POLL_EV_NVAL) { /* When an add fails with NVAL, the poll/kevent operation could not put that fd in the pollset, so we instead put it into a fallback pollset */ state->flags |= ERTS_EV_FLAG_FALLBACK; res = erts_poll_control_flbk(get_fallback_pollset(), fd, op, pe, wake_poller); } } else { ASSERT(op != ERTS_POLL_OP_ADD); res = erts_poll_control_flbk(get_fallback_pollset(), fd, op, pe, wake_poller); #endif } return res; } static ERTS_INLINE ErtsPollEvents erts_io_control(ErtsDrvEventState *state, ErtsPollOp op, ErtsPollEvents pe) { int wake_poller = 0; return erts_io_control_wakeup(state, op, pe, &wake_poller); } /* ToDo: Was inline in erl_check_io.h but now need struct erts_poll_thread */ void erts_io_notify_port_task_executed(ErtsPortTaskType type, ErtsPortTaskHandle *pthp, void (*reset_handle)(ErtsPortTaskHandle *)) { ErtsIoTask *itp = ErtsContainerStruct(pthp, ErtsIoTask, task); ErtsSysFdType fd = itp->fd; erts_mtx_t *mtx = fd_mtx(fd); ErtsPollOp op = ERTS_POLL_OP_MOD; int active_events, new_events = 0; ErtsDrvEventState *state; ErtsDrvSelectDataState *free_select = NULL; ErtsNifSelectDataState *free_nif = NULL; ERTS_MSACC_PUSH_AND_SET_STATE_M_X(ERTS_MSACC_STATE_CHECK_IO); erts_mtx_lock(mtx); state = get_drv_ev_state(fd); reset_handle(pthp); active_events = state->active_events; if (!(state->flags & ERTS_EV_FLAG_IN_SCHEDULER) || type == ERTS_PORT_TASK_OUTPUT) { switch (type) { case ERTS_PORT_TASK_INPUT: DEBUG_PRINT_FD("executed ready_input", state); ASSERT(!(state->active_events & ERTS_POLL_EV_IN)); if (state->events & ERTS_POLL_EV_IN) { active_events |= ERTS_POLL_EV_IN; if (state->count > 10 && ERTS_POLL_USE_SCHEDULER_POLLING) { if (!(state->flags & ERTS_EV_FLAG_SCHEDULER)) op = ERTS_POLL_OP_ADD; state->flags |= ERTS_EV_FLAG_IN_SCHEDULER|ERTS_EV_FLAG_SCHEDULER; new_events = ERTS_POLL_EV_IN; DEBUG_PRINT_FD("moving to scheduler ps", state); } else new_events = active_events; if (!(state->flags & ERTS_EV_FLAG_FALLBACK) && ERTS_POLL_USE_SCHEDULER_POLLING) state->count++; } break; case ERTS_PORT_TASK_OUTPUT: DEBUG_PRINT_FD("executed ready_output", state); ASSERT(!(state->active_events & ERTS_POLL_EV_OUT)); if (state->events & ERTS_POLL_EV_OUT) { active_events |= ERTS_POLL_EV_OUT; if (state->flags & ERTS_EV_FLAG_IN_SCHEDULER && active_events & ERTS_POLL_EV_IN) new_events = ERTS_POLL_EV_OUT; else new_events = active_events; } break; default: erts_exit(ERTS_ABORT_EXIT, "Invalid IO port task type"); break; } if (state->active_events != active_events && new_events) { state->active_events = active_events; new_events = erts_io_control(state, op, new_events); } /* We were unable to re-insert the fd into the pollset, signal the callback. */ if (new_events & (ERTS_POLL_EV_ERR|ERTS_POLL_EV_NVAL)) { if (state->active_events & ERTS_POLL_EV_IN) iready(state->driver.select->inport, state); if (state->active_events & ERTS_POLL_EV_OUT) oready(state->driver.select->outport, state); state->active_events = 0; active_events = 0; } } if (!active_events) check_fd_cleanup(state, &free_select, &free_nif); erts_mtx_unlock(mtx); if (free_select) free_drv_select_data(free_select); if (free_nif) free_nif_select_data(free_nif); ERTS_MSACC_POP_STATE_M_X(); } static ERTS_INLINE void abort_task(Eterm id, ErtsPortTaskHandle *pthp, EventStateType type) { if (is_not_nil(id) && erts_port_task_is_scheduled(pthp)) { erts_port_task_abort(pthp); ASSERT(erts_is_port_alive(id)); } } static ERTS_INLINE void abort_tasks(ErtsDrvEventState *state, int mode) { switch (mode) { case 0: check_type: switch (state->type) { case ERTS_EV_TYPE_NIF: case ERTS_EV_TYPE_NONE: return; default: ASSERT(state->type == ERTS_EV_TYPE_DRV_SEL); /* Fall through */ } case ERL_DRV_READ|ERL_DRV_WRITE: case ERL_DRV_WRITE: ASSERT(state->type == ERTS_EV_TYPE_DRV_SEL); abort_task(state->driver.select->outport, &state->driver.select->outiotask.task, state->type); if (mode == ERL_DRV_WRITE) break; case ERL_DRV_READ: ASSERT(state->type == ERTS_EV_TYPE_DRV_SEL); abort_task(state->driver.select->inport, &state->driver.select->iniotask.task, state->type); break; default: goto check_type; } } static void prepare_select_msg(struct erts_nif_select_event* e, enum ErlNifSelectFlags mode, Eterm recipient, ErtsResource* resource, Eterm msg, ErlNifEnv* msg_env, Eterm event_atom) { ErtsMessage* mp; Eterm* hp; Uint hsz; if (is_not_nil(e->pid)) { ASSERT(e->mp); erts_cleanup_messages(e->mp); } if (mode & ERL_NIF_SELECT_CUSTOM_MSG) { if (msg_env) { mp = erts_create_message_from_nif_env(msg_env); ERL_MESSAGE_TERM(mp) = msg; } else { hsz = size_object(msg); mp = erts_alloc_message(hsz, &hp); ERL_MESSAGE_TERM(mp) = copy_struct(msg, hsz, &hp, &mp->hfrag.off_heap); } } else { ErtsBinary* bin; Eterm resource_term, ref_term, tuple; Eterm* hp_start; /* {select, Resource, Ref, EventAtom} */ hsz = 5 + ERTS_MAGIC_REF_THING_SIZE; if (is_internal_ref(msg)) hsz += ERTS_REF_THING_SIZE; else ASSERT(is_immed(msg)); mp = erts_alloc_message(hsz, &hp); hp_start = hp; bin = ERTS_MAGIC_BIN_FROM_UNALIGNED_DATA(resource); resource_term = erts_mk_magic_ref(&hp, &mp->hfrag.off_heap, &bin->binary); if (is_internal_ref(msg)) { Uint32* refn = internal_ref_numbers(msg); write_ref_thing(hp, refn[0], refn[1], refn[2]); ref_term = make_internal_ref(hp); hp += ERTS_REF_THING_SIZE; } else { ASSERT(is_immed(msg)); ref_term = msg; } tuple = TUPLE4(hp, am_select, resource_term, ref_term, event_atom); hp += 5; ERL_MESSAGE_TERM(mp) = tuple; ASSERT(hp == hp_start + hsz); (void)hp_start; } ASSERT(is_not_nil(recipient)); e->pid = recipient; e->mp = mp; } static ERTS_INLINE void send_select_msg(struct erts_nif_select_event* e) { Process* rp = erts_proc_lookup(e->pid); ASSERT(is_internal_pid(e->pid)); if (!rp) { erts_cleanup_messages(e->mp); return; } erts_queue_message(rp, 0, e->mp, ERL_MESSAGE_TERM(e->mp), am_system); } static void clear_select_event(struct erts_nif_select_event* e) { if (is_not_nil(e->pid)) { /* Discard unsent message */ ASSERT(e->mp); erts_cleanup_messages(e->mp); e->mp = NULL; e->pid = NIL; } } static void deselect(ErtsDrvEventState *state, int mode) { ErtsPollEvents rm_events; ERTS_LC_ASSERT(erts_lc_mtx_is_locked(fd_mtx(state->fd))); abort_tasks(state, mode); if (!mode) { rm_events = state->events; } else { rm_events = 0; ASSERT(state->type == ERTS_EV_TYPE_DRV_SEL); if (mode & ERL_DRV_READ) { state->driver.select->inport = NIL; rm_events |= ERTS_POLL_EV_IN; } if (mode & ERL_DRV_WRITE) { state->driver.select->outport = NIL; rm_events |= ERTS_POLL_EV_OUT; } } state->events &= ~rm_events; state->active_events &= ~rm_events; if (!(state->events)) { erts_io_control(state, ERTS_POLL_OP_DEL, 0); switch (state->type) { case ERTS_EV_TYPE_NIF: clear_select_event(&state->driver.nif->in); clear_select_event(&state->driver.nif->out); enif_release_resource(state->driver.stop.resource->data); state->driver.stop.resource = NULL; break; case ERTS_EV_TYPE_DRV_SEL: state->driver.select->inport = NIL; state->driver.select->outport = NIL; break; case ERTS_EV_TYPE_NONE: break; default: ASSERT(0); break; } state->type = ERTS_EV_TYPE_NONE; state->flags = 0; } else { ErtsPollEvents new_events = erts_io_control(state, ERTS_POLL_OP_MOD, state->active_events); /* We were unable to re-insert the fd into the pollset, signal the callback. */ if (new_events & (ERTS_POLL_EV_ERR|ERTS_POLL_EV_NVAL)) { if (state->active_events & ERTS_POLL_EV_IN) iready(state->driver.select->inport, state); if (state->active_events & ERTS_POLL_EV_OUT) oready(state->driver.select->outport, state); state->active_events = 0; } } } #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS # define IS_FD_UNKNOWN(state) ((state)->type == ERTS_EV_TYPE_NONE) #else # define IS_FD_UNKNOWN(state) ((state) == NULL) #endif static ERTS_INLINE void check_fd_cleanup(ErtsDrvEventState *state, ErtsDrvSelectDataState **free_select, ErtsNifSelectDataState **free_nif) { ERTS_LC_ASSERT(erts_lc_mtx_is_locked(fd_mtx(state->fd))); *free_select = NULL; if (state->driver.select && (state->type != ERTS_EV_TYPE_DRV_SEL) && !is_iotask_active(&state->driver.select->iniotask) && !is_iotask_active(&state->driver.select->outiotask)) { *free_select = state->driver.select; state->driver.select = NULL; } *free_nif = NULL; if (state->driver.nif && (state->type != ERTS_EV_TYPE_NIF)) { *free_nif = state->driver.nif; state->driver.nif = NULL; } if (((state->type != ERTS_EV_TYPE_NONE) | (state->driver.nif != NULL) | (state->driver.select != NULL)) == 0) { erase_drv_ev_state(state); } } #ifdef __WIN32__ # define MUST_DEFER(MAY_SLEEP) 1 #else # define MUST_DEFER(MAY_SLEEP) (MAY_SLEEP) #endif int driver_select(ErlDrvPort ix, ErlDrvEvent e, int mode, int on) { void (*stop_select_fn)(ErlDrvEvent, void*) = NULL; Port *prt = erts_drvport2port(ix); Eterm id = erts_drvport2id(ix); ErtsSysFdType fd = (ErtsSysFdType) e; ErtsPollEvents ctl_events = (ErtsPollEvents) 0; ErtsPollEvents old_events; ErtsPollEvents new_events; ErtsPollOp ctl_op = ERTS_POLL_OP_MOD; ErtsDrvEventState *state; int wake_poller = 0; int ret; ErtsDrvSelectDataState *free_select = NULL; ErtsNifSelectDataState *free_nif = NULL; #ifdef USE_VM_PROBES DTRACE_CHARBUF(name, 64); #endif ERTS_MSACC_PUSH_AND_SET_STATE(ERTS_MSACC_STATE_CHECK_IO); if (prt == ERTS_INVALID_ERL_DRV_PORT) { ERTS_MSACC_POP_STATE(); return -1; } ERTS_LC_ASSERT(erts_lc_is_port_locked(prt)); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS if (!grow_drv_ev_state(fd)) { if (fd > 0) drv_select_large_fd_error(ix, fd, mode, on); ERTS_MSACC_POP_STATE(); return -1; } #endif erts_mtx_lock(fd_mtx(fd)); state = get_drv_ev_state(fd); /* may be NULL! */ DEBUG_PRINT_FD("driver_select(%T, %p, %s, %d)", state, id, fd, drvmode2str(mode), on); if (!on) { if (IS_FD_UNKNOWN(state)) { if ((mode&ERL_DRV_USE_NO_CALLBACK) == ERL_DRV_USE) { /* fast track to stop_select callback */ stop_select_fn = prt->drv_ptr->stop_select; #ifdef USE_VM_PROBES strncpy(name, prt->drv_ptr->name, sizeof(DTRACE_CHARBUF_NAME(name))-1); name[sizeof(name)-1] = '\0'; #endif } ret = 0; goto done_unknown; } /* For some reason (don't know why), we do not clean all events when doing ERL_DRV_USE_NO_CALLBACK. */ else if ((mode&ERL_DRV_USE_NO_CALLBACK) == ERL_DRV_USE) { mode |= (ERL_DRV_READ | ERL_DRV_WRITE); } } state = new_drv_ev_state(state, fd); switch (state->type) { case ERTS_EV_TYPE_NIF: drv_select_steal(ix, state, mode, on); break; case ERTS_EV_TYPE_STOP_USE: { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); print_drv_select_op(dsbufp, ix, state->fd, mode, on); steal_pending_stop_use(dsbufp, ix, state, mode, on); if (state->type == ERTS_EV_TYPE_STOP_USE) { ret = 0; goto done; /* stop_select still pending */ } ASSERT(state->type == ERTS_EV_TYPE_NONE); break; } case ERTS_EV_TYPE_STOP_NIF: { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); print_drv_select_op(dsbufp, ix, state->fd, mode, on); steal_pending_stop_nif(dsbufp, NULL, state, mode, on); ASSERT(state->type == ERTS_EV_TYPE_NONE); break; } default: break; } if (mode & ERL_DRV_READ) { if (state->type == ERTS_EV_TYPE_DRV_SEL) { Eterm owner = state->driver.select->inport; if (owner != id && is_not_nil(owner)) drv_select_steal(ix, state, mode, on); } ctl_events = ERTS_POLL_EV_IN; } if (mode & ERL_DRV_WRITE) { if (state->type == ERTS_EV_TYPE_DRV_SEL) { Eterm owner = state->driver.select->outport; if (owner != id && is_not_nil(owner)) drv_select_steal(ix, state, mode, on); } ctl_events |= ERTS_POLL_EV_OUT; } ASSERT((state->type == ERTS_EV_TYPE_DRV_SEL) || (state->type == ERTS_EV_TYPE_NONE && !state->events)); old_events = state->events; if (on) { ctl_events &= ~old_events; state->events |= ctl_events; if (ctl_events & ERTS_POLL_EV_IN && (!state->driver.select || !is_iotask_active(&state->driver.select->iniotask))) state->active_events |= ERTS_POLL_EV_IN; if (ctl_events & ERTS_POLL_EV_OUT && (!state->driver.select || !is_iotask_active(&state->driver.select->outiotask))) state->active_events |= ERTS_POLL_EV_OUT; if (old_events == 0 && !(state->flags & ERTS_EV_FLAG_USED)) { ctl_op = ERTS_POLL_OP_ADD; } new_events = state->active_events; if (state->flags & ERTS_EV_FLAG_IN_SCHEDULER) new_events &= ~ERTS_POLL_EV_IN; } else { ctl_events &= old_events; state->events &= ~ctl_events; state->active_events &= ~ctl_events; new_events = state->active_events; if (ctl_events & ERTS_POLL_EV_IN) { state->count = 0; if (state->flags & ERTS_EV_FLAG_IN_SCHEDULER) { new_events = 0; } } if (!state->events) { if (!(state->flags & ERTS_EV_FLAG_USED) || mode & ERL_DRV_USE) ctl_op = ERTS_POLL_OP_DEL; } } if (ctl_events || ctl_op == ERTS_POLL_OP_DEL) { new_events = erts_io_control_wakeup(state, ctl_op, new_events, &wake_poller); ASSERT(state->type == ERTS_EV_TYPE_DRV_SEL || state->type == ERTS_EV_TYPE_NONE); } if (on) { if (ctl_events) { if (!state->driver.select) state->driver.select = alloc_drv_select_data(state->fd); if (state->type == ERTS_EV_TYPE_NONE) state->type = ERTS_EV_TYPE_DRV_SEL; ASSERT(state->type == ERTS_EV_TYPE_DRV_SEL); if (ctl_events & ERTS_POLL_EV_IN) { state->driver.select->inport = id; if (new_events & (ERTS_POLL_EV_ERR|ERTS_POLL_EV_NVAL)) iready(id, state); } if (ctl_events & ERTS_POLL_EV_OUT) { state->driver.select->outport = id; if (new_events & (ERTS_POLL_EV_ERR|ERTS_POLL_EV_NVAL)) oready(id, state); } if (mode & ERL_DRV_USE) state->flags |= ERTS_EV_FLAG_USED; } } else { /* off */ if (state->type == ERTS_EV_TYPE_DRV_SEL) { if (ctl_events & ERTS_POLL_EV_IN) { abort_tasks(state, ERL_DRV_READ); state->driver.select->inport = NIL; state->flags &= ~ERTS_EV_FLAG_IN_SCHEDULER; } if (ctl_events & ERTS_POLL_EV_OUT) { abort_tasks(state, ERL_DRV_WRITE); state->driver.select->outport = NIL; } if (state->events == 0) { if ((mode & ERL_DRV_USE) || !(state->flags & ERTS_EV_FLAG_USED)) { state->type = ERTS_EV_TYPE_NONE; if (state->flags & ERTS_EV_FLAG_SCHEDULER) erts_atomic32_read_bor_nob(&prt->state, ERTS_PORT_SFLG_CHECK_FD_CLEANUP); state->flags = 0; } /*else keep it, as fd will probably be selected upon again */ } } if ((mode & ERL_DRV_USE_NO_CALLBACK) == ERL_DRV_USE) { erts_driver_t* drv_ptr = prt->drv_ptr; ASSERT(state->events==0); if (!wake_poller) { /* Safe to close fd now as it is not in pollset or there was no need to eject fd (kernel poll) */ stop_select_fn = drv_ptr->stop_select; #ifdef USE_VM_PROBES strncpy(name, prt->drv_ptr->name, sizeof(name)-1); name[sizeof(name)-1] = '\0'; #endif } else { /* Not safe to close fd, postpone stop_select callback. */ state->type = ERTS_EV_TYPE_STOP_USE; state->driver.stop.drv_ptr = drv_ptr; if (drv_ptr->handle) { erts_ddll_reference_referenced_driver(drv_ptr->handle); } } } } ret = 0; done: check_fd_cleanup(state, &free_select, &free_nif); done_unknown: erts_mtx_unlock(fd_mtx(fd)); if (stop_select_fn) { int was_unmasked = erts_block_fpe(); DTRACE1(driver_stop_select, name); LTTNG1(driver_stop_select, "unknown"); (*stop_select_fn)(e, NULL); erts_unblock_fpe(was_unmasked); } if (free_select) free_drv_select_data(free_select); if (free_nif) free_nif_select_data(free_nif); ERTS_MSACC_POP_STATE(); return ret; } int enif_select(ErlNifEnv* env, ErlNifEvent e, enum ErlNifSelectFlags mode, void* obj, const ErlNifPid* pid, Eterm msg) { return enif_select_x(env, e, mode, obj, pid, msg, NULL); } int enif_select_x(ErlNifEnv* env, ErlNifEvent e, enum ErlNifSelectFlags mode, void* obj, const ErlNifPid* pid, Eterm msg, ErlNifEnv* msg_env) { int on; ErtsResource* resource = DATA_TO_RESOURCE(obj); ErtsSysFdType fd = (ErtsSysFdType) e; ErtsPollEvents ctl_events = (ErtsPollEvents) 0; ErtsPollEvents old_events; ErtsPollOp ctl_op = ERTS_POLL_OP_MOD; ErtsDrvEventState *state; int ret, wake_poller = 0; enum { NO_STOP=0, CALL_STOP, CALL_STOP_AND_RELEASE } call_stop = NO_STOP; ErtsDrvSelectDataState *free_select = NULL; ErtsNifSelectDataState *free_nif = NULL; ASSERT(!erts_dbg_is_resource_dying(resource)); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS if (!grow_drv_ev_state(fd)) { if (fd > 0) nif_select_large_fd_error(fd, mode, resource, msg); return INT_MIN | ERL_NIF_SELECT_INVALID_EVENT; } #endif erts_mtx_lock(fd_mtx(fd)); state = get_drv_ev_state(fd); /* may be NULL! */ DEBUG_PRINT_FD("enif_select(%T, %d, %s, %p, %T, %T)", state, env->proc->common.id, fd, nifmode2str(mode), resource, pid ? pid->pid : THE_NON_VALUE, THE_NON_VALUE); if (mode & ERL_NIF_SELECT_STOP) { ASSERT(resource->type->fn.stop); if (IS_FD_UNKNOWN(state)) { /* fast track to stop callback */ call_stop = CALL_STOP; ret = ERL_NIF_SELECT_STOP_CALLED; goto done_unknown; } on = 0; mode = ERL_DRV_READ | ERL_DRV_WRITE | ERL_DRV_USE; ctl_events = ERTS_POLL_EV_IN | ERTS_POLL_EV_OUT; ctl_op = ERTS_POLL_OP_DEL; } else { on = !(mode & ERL_NIF_SELECT_CANCEL); ASSERT(mode); if (mode & ERL_DRV_READ) { ctl_events |= ERTS_POLL_EV_IN; } if (mode & ERL_DRV_WRITE) { ctl_events |= ERTS_POLL_EV_OUT; } } state = new_drv_ev_state(state,fd); switch (state->type) { case ERTS_EV_TYPE_NIF: /* * Changing resource is considered stealing. * Changing process and/or ref is ok (I think?). */ if (state->driver.stop.resource != resource) nif_select_steal(state, ERL_DRV_READ | ERL_DRV_WRITE, resource, msg); break; case ERTS_EV_TYPE_DRV_SEL: nif_select_steal(state, mode, resource, msg); break; case ERTS_EV_TYPE_STOP_USE: { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); print_nif_select_op(dsbufp, fd, mode, resource, msg); steal_pending_stop_use(dsbufp, ERTS_INVALID_ERL_DRV_PORT, state, mode, on); ASSERT(state->type == ERTS_EV_TYPE_NONE); break; } case ERTS_EV_TYPE_STOP_NIF: { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); print_nif_select_op(dsbufp, fd, mode, resource, msg); steal_pending_stop_nif(dsbufp, resource, state, mode, on); if (state->type == ERTS_EV_TYPE_STOP_NIF) { ret = ERL_NIF_SELECT_STOP_SCHEDULED; /* ?? */ goto done; } ASSERT(state->type == ERTS_EV_TYPE_NONE); break; } default: break; } ASSERT((state->type == ERTS_EV_TYPE_NIF) || (state->type == ERTS_EV_TYPE_NONE && !state->events)); old_events = state->events; if (on) { ctl_events &= ~old_events; state->events |= ctl_events; state->active_events |= ctl_events; if (state->type == ERTS_EV_TYPE_NONE) ctl_op = ERTS_POLL_OP_ADD; } else { ctl_events &= old_events; state->events &= ~ctl_events; state->active_events &= ~ctl_events; } if (ctl_events || ctl_op == ERTS_POLL_OP_DEL) { ErtsPollEvents new_events; new_events = erts_io_control_wakeup(state, ctl_op, state->active_events, &wake_poller); if (new_events & (ERTS_POLL_EV_ERR|ERTS_POLL_EV_NVAL)) { if (state->type == ERTS_EV_TYPE_NIF && !old_events) { state->type = ERTS_EV_TYPE_NONE; state->flags = 0; state->driver.nif->in.pid = NIL; state->driver.nif->out.pid = NIL; state->driver.stop.resource = NULL; } ret = INT_MIN | ERL_NIF_SELECT_FAILED; goto done; } ASSERT(new_events == state->events); } ASSERT(state->type == ERTS_EV_TYPE_NIF || state->type == ERTS_EV_TYPE_NONE); if (on) { const Eterm recipient = pid ? pid->pid : env->proc->common.id; ASSERT(is_internal_pid(recipient)); if (!state->driver.nif) state->driver.nif = alloc_nif_select_data(); if (state->type == ERTS_EV_TYPE_NONE) { state->type = ERTS_EV_TYPE_NIF; state->driver.stop.resource = resource; enif_keep_resource(resource->data); } ASSERT(state->type == ERTS_EV_TYPE_NIF); ASSERT(state->driver.stop.resource == resource); if (mode & ERL_DRV_READ) { prepare_select_msg(&state->driver.nif->in, mode, recipient, resource, msg, msg_env, am_ready_input); msg_env = NULL; } if (mode & ERL_DRV_WRITE) { prepare_select_msg(&state->driver.nif->out, mode, recipient, resource, msg, msg_env, am_ready_output); } ret = 0; } else { /* off */ ret = 0; if (state->type == ERTS_EV_TYPE_NIF) { if (mode & ERL_NIF_SELECT_READ && is_not_nil(state->driver.nif->in.pid)) { clear_select_event(&state->driver.nif->in); ret |= ERL_NIF_SELECT_READ_CANCELLED; } if (mode & ERL_NIF_SELECT_WRITE && is_not_nil(state->driver.nif->out.pid)) { clear_select_event(&state->driver.nif->out); ret |= ERL_NIF_SELECT_WRITE_CANCELLED; } } if (mode & ERL_NIF_SELECT_STOP) { ASSERT(state->events==0); if (!wake_poller) { /* * Safe to close fd now as it is not in pollset * or there was no need to eject fd (kernel poll) */ if (state->type == ERTS_EV_TYPE_NIF) { ASSERT(state->driver.stop.resource == resource); call_stop = CALL_STOP_AND_RELEASE; state->driver.stop.resource = NULL; } else { ASSERT(!state->driver.stop.resource); call_stop = CALL_STOP; } state->type = ERTS_EV_TYPE_NONE; ret |= ERL_NIF_SELECT_STOP_CALLED; } else { /* Not safe to close fd, postpone stop_select callback. */ if (state->type == ERTS_EV_TYPE_NONE) { ASSERT(!state->driver.stop.resource); state->driver.stop.resource = resource; enif_keep_resource(resource); } state->type = ERTS_EV_TYPE_STOP_NIF; ret |= ERL_NIF_SELECT_STOP_SCHEDULED; } } else ASSERT(mode & ERL_NIF_SELECT_CANCEL); } done: check_fd_cleanup(state, &free_select, &free_nif); done_unknown: erts_mtx_unlock(fd_mtx(fd)); if (call_stop) { erts_resource_stop(resource, (ErlNifEvent)fd, 1); if (call_stop == CALL_STOP_AND_RELEASE) { enif_release_resource(resource->data); } } if (free_select) free_drv_select_data(free_select); if (free_nif) free_nif_select_data(free_nif); return ret; } static ERTS_INLINE int chk_stale(Eterm id, ErtsDrvEventState *state, int mode) { if (is_nil(id)) return 0; if (erts_is_port_alive(id)) return 1; /* Steal */ stale_drv_select(id, state, mode); return 0; } static int need2steal(ErtsDrvEventState *state, int mode) { int do_steal = 0; switch (state->type) { case ERTS_EV_TYPE_DRV_SEL: if (mode & ERL_DRV_READ) do_steal |= chk_stale(state->driver.select->inport, state, ERL_DRV_READ); if (mode & ERL_DRV_WRITE) do_steal |= chk_stale(state->driver.select->outport, state, ERL_DRV_WRITE); break; case ERTS_EV_TYPE_NIF: ASSERT(state->driver.stop.resource); do_steal = 1; break; case ERTS_EV_TYPE_STOP_USE: case ERTS_EV_TYPE_STOP_NIF: ASSERT(0); break; default: break; } return do_steal; } static void print_driver_name(erts_dsprintf_buf_t *dsbufp, Eterm id) { ErtsPortNames *pnp = erts_get_port_names(id, ERTS_INVALID_ERL_DRV_PORT); if (!pnp->name && !pnp->driver_name) erts_dsprintf(dsbufp, "%s ", "<unknown>"); else { if (pnp->name) { if (!pnp->driver_name || strcmp(pnp->driver_name, pnp->name) == 0) erts_dsprintf(dsbufp, "%s ", pnp->name); else erts_dsprintf(dsbufp, "%s (%s) ", pnp->driver_name, pnp->name); } else if (pnp->driver_name) { erts_dsprintf(dsbufp, "%s ", pnp->driver_name); } } erts_free_port_names(pnp); } static void steal(erts_dsprintf_buf_t *dsbufp, ErtsDrvEventState *state, int mode) { erts_dsprintf(dsbufp, "stealing control of fd=%bpd from ", (SWord) state->fd); switch (state->type) { case ERTS_EV_TYPE_DRV_SEL: { int deselect_mode = 0; Eterm iid = state->driver.select->inport; Eterm oid = state->driver.select->outport; if ((mode & ERL_DRV_READ) && (is_not_nil(iid))) { erts_dsprintf(dsbufp, "input driver "); print_driver_name(dsbufp, iid); erts_dsprintf(dsbufp, "%T ", iid); deselect_mode |= ERL_DRV_READ; } if ((mode & ERL_DRV_WRITE) && is_not_nil(oid)) { if (deselect_mode) { erts_dsprintf(dsbufp, "and "); } erts_dsprintf(dsbufp, "output driver "); print_driver_name(dsbufp, oid); erts_dsprintf(dsbufp, "%T ", oid); deselect_mode |= ERL_DRV_WRITE; } if (deselect_mode) deselect(state, deselect_mode); else { erts_dsprintf(dsbufp, "no one"); ASSERT(0); } erts_dsprintf(dsbufp, "\n"); break; } case ERTS_EV_TYPE_NIF: { Eterm iid = state->driver.nif->in.pid; Eterm oid = state->driver.nif->out.pid; const char* with = "with"; ErlNifResourceType* rt = state->driver.stop.resource->type; erts_dsprintf(dsbufp, "resource %T:%T", rt->module, rt->name); if (is_not_nil(iid)) { erts_dsprintf(dsbufp, " %s in-pid %T", with, iid); with = "and"; } if (is_not_nil(oid)) { erts_dsprintf(dsbufp, " %s out-pid %T", with, oid); } deselect(state, 0); erts_dsprintf(dsbufp, "\n"); break; } case ERTS_EV_TYPE_STOP_USE: case ERTS_EV_TYPE_STOP_NIF: { ASSERT(0); break; } default: erts_dsprintf(dsbufp, "no one\n"); ASSERT(0); } } static void print_drv_select_op(erts_dsprintf_buf_t *dsbufp, ErlDrvPort ix, ErtsSysFdType fd, int mode, int on) { Port *pp = erts_drvport2port(ix); erts_dsprintf(dsbufp, "driver_select(%p, %bpd,%s%s%s%s, %d) " "by ", ix, (SWord) fd, mode & ERL_DRV_READ ? " ERL_DRV_READ" : "", mode & ERL_DRV_WRITE ? " ERL_DRV_WRITE" : "", mode & ERL_DRV_USE ? " ERL_DRV_USE" : "", mode & (ERL_DRV_USE_NO_CALLBACK & ~ERL_DRV_USE) ? "_NO_CALLBACK" : "", on); print_driver_name(dsbufp, pp != ERTS_INVALID_ERL_DRV_PORT ? pp->common.id : NIL); erts_dsprintf(dsbufp, "driver %T ", pp != ERTS_INVALID_ERL_DRV_PORT ? pp->common.id : NIL); } static void print_nif_select_op(erts_dsprintf_buf_t *dsbufp, ErtsSysFdType fd, int mode, ErtsResource* resource, Eterm ref) { erts_dsprintf(dsbufp, "enif_select(_, %bpd,%s%s%s, %T:%T, %T) ", (SWord) fd, mode & ERL_NIF_SELECT_READ ? " READ" : "", mode & ERL_NIF_SELECT_WRITE ? " WRITE" : "", (mode & ERL_NIF_SELECT_STOP ? " STOP" : (mode & ERL_NIF_SELECT_CANCEL ? " CANCEL" : "")), resource->type->module, resource->type->name, ref); } static void drv_select_steal(ErlDrvPort ix, ErtsDrvEventState *state, int mode, int on) { if (need2steal(state, mode)) { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); print_drv_select_op(dsbufp, ix, state->fd, mode, on); steal(dsbufp, state, mode); erts_send_error_to_logger_nogl(dsbufp); } } static void nif_select_steal(ErtsDrvEventState *state, int mode, ErtsResource* resource, Eterm ref) { if (need2steal(state, mode)) { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); print_nif_select_op(dsbufp, state->fd, mode, resource, ref); steal(dsbufp, state, mode); erts_send_error_to_logger_nogl(dsbufp); } } #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS static void large_fd_error_common(erts_dsprintf_buf_t *dsbufp, ErtsSysFdType fd) { erts_dsprintf(dsbufp, "fd=%d is larger than the largest allowed fd=%d\n", (int) fd, drv_ev_state.max_fds - 1); } static void drv_select_large_fd_error(ErlDrvPort ix, ErtsSysFdType fd, int mode, int on) { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); print_drv_select_op(dsbufp, ix, fd, mode, on); erts_dsprintf(dsbufp, "failed: "); large_fd_error_common(dsbufp, fd); erts_send_error_to_logger_nogl(dsbufp); } static void nif_select_large_fd_error(ErtsSysFdType fd, int mode, ErtsResource* resource, Eterm ref) { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); print_nif_select_op(dsbufp, fd, mode, resource, ref); erts_dsprintf(dsbufp, "failed: "); large_fd_error_common(dsbufp, fd); erts_send_error_to_logger_nogl(dsbufp); } #endif /* ERTS_SYS_CONTINOUS_FD_NUMBERS */ static void steal_pending_stop_use(erts_dsprintf_buf_t *dsbufp, ErlDrvPort ix, ErtsDrvEventState *state, int mode, int on) { int cancel = 0; ASSERT(state->type == ERTS_EV_TYPE_STOP_USE); if (on) { /* Either fd-owner changed its mind about closing * or closed fd before stop_select callback and fd is now reused. * In either case stop_select should not be called. */ cancel = 1; } else if ((mode & ERL_DRV_USE_NO_CALLBACK) == ERL_DRV_USE) { Port *prt = erts_drvport2port(ix); if (prt == ERTS_INVALID_ERL_DRV_PORT || prt->drv_ptr != state->driver.stop.drv_ptr) { /* Some other driver or nif wants the stop_select callback */ cancel = 1; } } if (cancel) { erts_dsprintf(dsbufp, "called before stop_select was called for driver '%s'\n", state->driver.stop.drv_ptr->name); if (state->driver.stop.drv_ptr->handle) { erts_ddll_dereference_driver(state->driver.stop.drv_ptr->handle); } state->type = ERTS_EV_TYPE_NONE; state->flags = 0; state->driver.stop.drv_ptr = NULL; } else { erts_dsprintf(dsbufp, "ignored repeated call\n"); } erts_send_error_to_logger_nogl(dsbufp); } static void steal_pending_stop_nif(erts_dsprintf_buf_t *dsbufp, ErtsResource* resource, ErtsDrvEventState *state, int mode, int on) { int cancel = 0; ASSERT(state->type == ERTS_EV_TYPE_STOP_NIF); ASSERT(state->driver.stop.resource); if (on) { ASSERT(mode & (ERL_NIF_SELECT_READ | ERL_NIF_SELECT_WRITE)); /* Either fd-owner changed its mind about closing * or closed fd before stop callback and fd is now reused. * In either case, stop should not be called. */ cancel = 1; } else if ((mode & ERL_DRV_USE_NO_CALLBACK) == ERL_DRV_USE && resource != state->driver.stop.resource) { /* Some driver or other resource wants the stop callback */ cancel = 1; } if (cancel) { ErlNifResourceType* rt = state->driver.stop.resource->type; erts_dsprintf(dsbufp, "called before stop was called for NIF resource %T:%T\n", rt->module, rt->name); enif_release_resource(state->driver.stop.resource->data); state->type = ERTS_EV_TYPE_NONE; state->flags = 0; state->driver.stop.resource = NULL; } else { erts_dsprintf(dsbufp, "ignored repeated call\n"); } erts_send_error_to_logger_nogl(dsbufp); } static ERTS_INLINE int io_task_schedule_allowed(ErtsDrvEventState *state, ErtsPortTaskType type) { ErtsIoTask *io_task; switch (type) { case ERTS_PORT_TASK_INPUT: if (!state->driver.select) return 0; io_task = &state->driver.select->iniotask; break; case ERTS_PORT_TASK_OUTPUT: if (!state->driver.select) return 0; io_task = &state->driver.select->outiotask; break; default: ERTS_INTERNAL_ERROR("Invalid I/O-task type"); return 0; } return !is_iotask_active(io_task); } static ERTS_INLINE void iready(Eterm id, ErtsDrvEventState *state) { if (io_task_schedule_allowed(state, ERTS_PORT_TASK_INPUT)) { ErtsIoTask *iotask = &state->driver.select->iniotask; if (erts_port_task_schedule(id, &iotask->task, ERTS_PORT_TASK_INPUT, (ErlDrvEvent) state->fd, state->flags & ERTS_EV_FLAG_IN_SCHEDULER) != 0) { stale_drv_select(id, state, ERL_DRV_READ); } else { DEBUG_PRINT_FD("schedule ready_input(%T, %d)", state, id, state->fd); } } } static ERTS_INLINE void oready(Eterm id, ErtsDrvEventState *state) { if (io_task_schedule_allowed(state, ERTS_PORT_TASK_OUTPUT)) { ErtsIoTask *iotask = &state->driver.select->outiotask; if (erts_port_task_schedule(id, &iotask->task, ERTS_PORT_TASK_OUTPUT, (ErlDrvEvent) state->fd, 0) != 0) { stale_drv_select(id, state, ERL_DRV_WRITE); } else { DEBUG_PRINT_FD("schedule ready_output(%T, %d)", state, id, state->fd); } } } static void bad_fd_in_pollset(ErtsDrvEventState *, Eterm inport, Eterm outport); void erts_check_io_interrupt(ErtsPollThread *psi, int set) { if (psi) { #if ERTS_POLL_USE_FALLBACK if (psi->ps == get_fallback_pollset()) { erts_poll_interrupt_flbk(psi->ps, set); return; } #endif erts_poll_interrupt(psi->ps, set); } } ErtsPollThread * erts_create_pollset_thread(int id, ErtsThrPrgrData *tpd) { psiv[id].tpd = tpd; return psiv+id; } void erts_check_io(ErtsPollThread *psi, ErtsMonotonicTime timeout_time, int poll_only_thread) { int pollres_len; int poll_ret, i; ERTS_MSACC_PUSH_AND_SET_STATE(ERTS_MSACC_STATE_CHECK_IO); restart: #ifdef ERTS_ENABLE_LOCK_CHECK erts_lc_check_exact(NULL, 0); /* No locks should be locked */ #endif pollres_len = psi->pollres_len; if (poll_only_thread) erts_thr_progress_active(psi->tpd, 0); #if ERTS_POLL_USE_FALLBACK if (psi->ps == get_fallback_pollset()) { poll_ret = erts_poll_wait_flbk(psi->ps, psi->pollres, &pollres_len, psi->tpd, timeout_time); } else #endif { poll_ret = erts_poll_wait(psi->ps, psi->pollres, &pollres_len, psi->tpd, timeout_time); } if (poll_only_thread) erts_thr_progress_active(psi->tpd, 1); #ifdef ERTS_ENABLE_LOCK_CHECK erts_lc_check_exact(NULL, 0); /* No locks should be locked */ #endif if (poll_ret != 0) { if (poll_ret == EAGAIN) { goto restart; } if (poll_ret != ETIMEDOUT && poll_ret != EINTR #ifdef ERRNO_BLOCK && poll_ret != ERRNO_BLOCK #endif ) { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); erts_dsprintf(dsbufp, "erts_poll_wait() failed: %s (%d)\n", erl_errno_id(poll_ret), poll_ret); erts_send_error_to_logger_nogl(dsbufp); } ERTS_MSACC_POP_STATE(); return; } for (i = 0; i < pollres_len; i++) { erts_driver_t* drv_ptr = NULL; ErtsResource* resource = NULL; ErtsDrvSelectDataState *free_select = NULL; ErtsNifSelectDataState *free_nif = NULL; ErtsSysFdType fd = (ErtsSysFdType) ERTS_POLL_RES_GET_FD(&psi->pollres[i]); ErtsDrvEventState *state; ErtsPollEvents revents = ERTS_POLL_RES_GET_EVTS(&psi->pollres[i]); /* The fd will be set to INVALID if a pollset internal fd was triggered that was determined to be too expensive to remove from the result. */ if (fd == ERTS_SYS_FD_INVALID) continue; erts_mtx_lock(fd_mtx(fd)); state = get_drv_ev_state(fd); if (!state) { erts_mtx_unlock(fd_mtx(fd)); continue; } DEBUG_PRINT_FD("triggered %s", state, ev2str(revents)); if (revents & ERTS_POLL_EV_ERR) { /* * Handle error events by triggering all in/out events * that has been selected on. * We *do not* want to call a callback that corresponds * to an event not selected. */ revents = state->active_events; state->active_events = 0; if (state->flags & ERTS_EV_FLAG_IN_SCHEDULER) { erts_io_control(state, ERTS_POLL_OP_MOD, 0); state->flags &= ~ERTS_EV_FLAG_IN_SCHEDULER; } } else { /* Disregard any events that are not active at the moment, for instance this could happen if the driver/nif does select/deselect in rapid succession. */ revents &= state->active_events | ERTS_POLL_EV_NVAL; if (psi->ps != get_scheduler_pollset(fd) || !ERTS_POLL_USE_SCHEDULER_POLLING) { ErtsPollEvents reactive_events; state->active_events &= ~revents; reactive_events = state->active_events; if (state->flags & ERTS_EV_FLAG_IN_SCHEDULER) { reactive_events &= ~ERTS_POLL_EV_IN; state->active_events |= ERTS_POLL_EV_IN; } /* Reactivate the poll op if there are still active events */ if (reactive_events) { ErtsPollEvents new_events; DEBUG_PRINT_FD("re-enable %s", state, ev2str(reactive_events)); new_events = erts_io_control(state, ERTS_POLL_OP_MOD, reactive_events); /* Unable to re-enable the fd, signal all callbacks */ if (new_events & (ERTS_POLL_EV_ERR|ERTS_POLL_EV_NVAL)) { revents |= reactive_events; state->active_events &= ~reactive_events; } } } } switch (state->type) { case ERTS_EV_TYPE_DRV_SEL: { /* Requested via driver_select()... */ if (revents & (ERTS_POLL_EV_IN|ERTS_POLL_EV_OUT)) { if (revents & ERTS_POLL_EV_OUT) { oready(state->driver.select->outport, state); } /* Someone might have deselected input since revents was read (true also on the non-smp emulator since oready() may have been called); therefore, update revents... */ revents &= state->events; if (revents & ERTS_POLL_EV_IN) { iready(state->driver.select->inport, state); } } else if (revents & ERTS_POLL_EV_NVAL) { bad_fd_in_pollset(state, state->driver.select->inport, state->driver.select->outport); check_fd_cleanup(state, &free_select, &free_nif); } break; } case ERTS_EV_TYPE_NIF: { /* Requested via enif_select()... */ struct erts_nif_select_event in = {NIL}; struct erts_nif_select_event out = {NIL}; if (revents & (ERTS_POLL_EV_IN|ERTS_POLL_EV_OUT)) { if (revents & ERTS_POLL_EV_OUT) { if (is_not_nil(state->driver.nif->out.pid)) { out = state->driver.nif->out; resource = state->driver.stop.resource; state->driver.nif->out.pid = NIL; state->driver.nif->out.mp = NULL; } } if (revents & ERTS_POLL_EV_IN) { if (is_not_nil(state->driver.nif->in.pid)) { in = state->driver.nif->in; resource = state->driver.stop.resource; state->driver.nif->in.pid = NIL; state->driver.nif->in.mp = NULL; } } state->events &= ~revents; } else if (revents & ERTS_POLL_EV_NVAL) { bad_fd_in_pollset(state, NIL, NIL); check_fd_cleanup(state, &free_select, &free_nif); } erts_mtx_unlock(fd_mtx(fd)); if (is_not_nil(in.pid)) { send_select_msg(&in); } if (is_not_nil(out.pid)) { send_select_msg(&out); } continue; } case ERTS_EV_TYPE_STOP_NIF: { resource = state->driver.stop.resource; state->type = ERTS_EV_TYPE_NONE; goto case_ERTS_EV_TYPE_NONE; } case ERTS_EV_TYPE_STOP_USE: { #if ERTS_POLL_USE_FALLBACK ASSERT(psi->ps == get_fallback_pollset()); #endif drv_ptr = state->driver.stop.drv_ptr; state->type = ERTS_EV_TYPE_NONE; /* fallthrough */ case ERTS_EV_TYPE_NONE: /* Deselected ... */ case_ERTS_EV_TYPE_NONE: ASSERT(!state->events && !state->active_events && !state->flags); check_fd_cleanup(state, &free_select, &free_nif); break; } default: { /* Error */ erts_dsprintf_buf_t *dsbufp; dsbufp = erts_create_logger_dsbuf(); erts_dsprintf(dsbufp, "Invalid event request type for fd in erts_poll()! " "fd=%bpd, event request type=%d\n", (SWord) state->fd, (int) state->type); ASSERT(0); deselect(state, 0); break; } } erts_mtx_unlock(fd_mtx(fd)); if (drv_ptr) { int was_unmasked = erts_block_fpe(); DTRACE1(driver_stop_select, drv_ptr->name); LTTNG1(driver_stop_select, drv_ptr->name); (*drv_ptr->stop_select)((ErlDrvEvent) fd, NULL); erts_unblock_fpe(was_unmasked); if (drv_ptr->handle) { erts_ddll_dereference_driver(drv_ptr->handle); } } if (resource) { erts_resource_stop(resource, (ErlNifEvent)fd, 0); enif_release_resource(resource->data); } if (free_select) free_drv_select_data(free_select); if (free_nif) free_nif_select_data(free_nif); } /* The entire pollres array was filled with events, * grow it for the next call. We do this for two reasons: * 1. Pulling out more events in on go will increase throughput * 2. If the polling implementation is not fair, this will make * sure that we get all fds that we can. i.e. if 12 fds are * constantly active, but we only have a pollres_len of 10, * two of the fds may never be triggered depending on what the * kernel decides to do. **/ if (pollres_len == psi->pollres_len) { int ev_state_len = drv_ev_state_len(); erts_free(ERTS_ALC_T_POLLSET, psi->pollres); psi->pollres_len *= 2; /* Never grow it larger than the current drv_ev_state.len size */ if (psi->pollres_len > ev_state_len) psi->pollres_len = ev_state_len; psi->pollres = erts_alloc(ERTS_ALC_T_POLLSET, sizeof(ErtsPollResFd) * psi->pollres_len); } ERTS_MSACC_POP_STATE(); } static void bad_fd_in_pollset(ErtsDrvEventState *state, Eterm inport, Eterm outport) { ErtsPollEvents events = state->events; erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); if (events & (ERTS_POLL_EV_IN|ERTS_POLL_EV_OUT)) { char *io_str; Eterm port = NIL; if ((events & ERTS_POLL_EV_IN) && (events & ERTS_POLL_EV_OUT)) { io_str = "input/output"; if (inport == outport) port = inport; } else { if (events & ERTS_POLL_EV_IN) { io_str = "input"; port = inport; } else { io_str = "output"; port = outport; } } erts_dsprintf(dsbufp, "Bad %s fd in erts_poll()! fd=%bpd, ", io_str, (SWord) state->fd); if (state->type == ERTS_EV_TYPE_DRV_SEL) { if (is_nil(port)) { ErtsPortNames *ipnp = erts_get_port_names(inport, ERTS_INVALID_ERL_DRV_PORT); ErtsPortNames *opnp = erts_get_port_names(outport, ERTS_INVALID_ERL_DRV_PORT); erts_dsprintf(dsbufp, "ports=%T/%T, drivers=%s/%s, names=%s/%s\n", is_nil(inport) ? am_undefined : inport, is_nil(outport) ? am_undefined : outport, ipnp->driver_name ? ipnp->driver_name : "<unknown>", opnp->driver_name ? opnp->driver_name : "<unknown>", ipnp->name ? ipnp->name : "<unknown>", opnp->name ? opnp->name : "<unknown>"); erts_free_port_names(ipnp); erts_free_port_names(opnp); } else { ErtsPortNames *pnp = erts_get_port_names(port, ERTS_INVALID_ERL_DRV_PORT); erts_dsprintf(dsbufp, "port=%T, driver=%s, name=%s\n", is_nil(port) ? am_undefined : port, pnp->driver_name ? pnp->driver_name : "<unknown>", pnp->name ? pnp->name : "<unknown>"); erts_free_port_names(pnp); } } else { ErlNifResourceType* rt; ASSERT(state->type == ERTS_EV_TYPE_NIF); ASSERT(state->driver.stop.resource); rt = state->driver.stop.resource->type; erts_dsprintf(dsbufp, "resource={%T,%T}\n", rt->module, rt->name); } } else { erts_dsprintf(dsbufp, "Bad fd in erts_poll()! fd=%bpd\n", (SWord) state->fd); } erts_send_error_to_logger_nogl(dsbufp); /* unmap entry */ deselect(state, 0); } static void stale_drv_select(Eterm id, ErtsDrvEventState *state, int mode) { erts_stale_drv_select(id, ERTS_INVALID_ERL_DRV_PORT, (ErlDrvEvent) state->fd, mode, 0); deselect(state, mode); } #ifndef ERTS_SYS_CONTINOUS_FD_NUMBERS static SafeHashValue drv_ev_state_hash(void *des) { SafeHashValue val = (SafeHashValue)(SWord) ((ErtsDrvEventState *) des)->fd; return val ^ (val >> 8); /* Good enough for aligned pointer values? */ } static int drv_ev_state_cmp(void *des1, void *des2) { return ( ((ErtsDrvEventState *) des1)->fd == ((ErtsDrvEventState *) des2)->fd ? 0 : 1); } static void *drv_ev_state_alloc(void *des_tmpl) { ErtsDrvEventState *evstate; erts_spin_lock(&drv_ev_state.prealloc_lock); if (drv_ev_state.prealloc_first == NULL) { erts_spin_unlock(&drv_ev_state.prealloc_lock); evstate = (ErtsDrvEventState *) erts_alloc(ERTS_ALC_T_DRV_EV_STATE, sizeof(ErtsDrvEventState)); } else { evstate = drv_ev_state.prealloc_first; drv_ev_state.prealloc_first = (ErtsDrvEventState *) evstate->hb.next; --drv_ev_state.num_prealloc; erts_spin_unlock(&drv_ev_state.prealloc_lock); } /* XXX: Already valid data if prealloced, could ignore template! */ *evstate = *((ErtsDrvEventState *) des_tmpl); return (void *) evstate; } static void drv_ev_state_free(void *des) { erts_spin_lock(&drv_ev_state.prealloc_lock); ((ErtsDrvEventState *) des)->hb.next = &drv_ev_state.prealloc_first->hb; drv_ev_state.prealloc_first = (ErtsDrvEventState *) des; ++drv_ev_state.num_prealloc; erts_spin_unlock(&drv_ev_state.prealloc_lock); } #endif #define ERTS_MAX_NO_OF_POLL_THREADS ERTS_MAX_NO_OF_SCHEDULERS static char * get_arg(char* rest, char** argv, int* ip) { int i = *ip; if (*rest == '\0') { if (argv[i+1] == NULL) { erts_fprintf(stderr, "too few arguments\n"); erts_usage(); } argv[i++] = NULL; rest = argv[i]; } argv[i] = NULL; *ip = i; return rest; } static void parse_args(int *argc, char **argv, int concurrent_waiters) { int i = 0, j; int no_pollsets = 0, no_poll_threads = 0, no_pollsets_percentage = 0, no_poll_threads_percentage = 0; ASSERT(argc && argv); while (i < *argc) { if(argv[i][0] == '-') { switch (argv[i][1]) { case 'I': { if (strncmp(argv[i]+2, "Ot", 2) == 0) { char *arg = get_arg(argv[i]+4, argv, &i); if (sscanf(arg, "%d", &no_poll_threads) != 1 || no_poll_threads < 1 || ERTS_MAX_NO_OF_POLL_THREADS < no_poll_threads) { erts_fprintf(stderr,"bad I/O poll threads number: %s\n", arg); erts_usage(); } } else if (strncmp(argv[i]+2, "Op", 3) == 0) { char *arg = get_arg(argv[i]+4, argv, &i); if (sscanf(arg, "%d", &no_pollsets) != 1 || no_pollsets < 1) { erts_fprintf(stderr,"bad I/O pollset number: %s\n", arg); erts_usage(); } } else if (strncmp(argv[i]+2, "OPt", 4) == 0) { char *arg = get_arg(argv[i]+5, argv, &i); if (sscanf(arg, "%d", &no_poll_threads_percentage) != 1 || no_poll_threads_percentage < 0 || no_poll_threads_percentage > 100) { erts_fprintf(stderr,"bad I/O poll thread percentage number: %s\n", arg); erts_usage(); } } else if (strncmp(argv[i]+2, "OPp", 4) == 0) { char *arg = get_arg(argv[i]+5, argv, &i); if (sscanf(arg, "%d", &no_pollsets_percentage) != 1 || no_pollsets_percentage < 0 || no_pollsets_percentage > 100) { erts_fprintf(stderr,"bad I/O pollset percentage number: %s\n", arg); erts_usage(); } } else { break; } break; } case 'K': (void)get_arg(argv[i]+2, argv, &i); break; case '-': goto args_parsed; default: break; } } i++; } args_parsed: if (!concurrent_waiters) { no_pollsets = no_poll_threads; no_pollsets_percentage = 100; } if (no_poll_threads == 0) { if (no_poll_threads_percentage == 0) no_poll_threads = 1; /* This is the default */ else { no_poll_threads = erts_no_schedulers * no_poll_threads_percentage / 100; if (no_poll_threads < 1) no_poll_threads = 1; } } if (no_pollsets == 0) { if (no_pollsets_percentage == 0) no_pollsets = 1; /* This is the default */ else { no_pollsets = no_poll_threads * no_pollsets_percentage / 100; if (no_pollsets < 1) no_pollsets = 1; } } if (no_poll_threads < no_pollsets) { erts_fprintf(stderr, "number of IO poll threads has to be greater or equal to " "the number of \nIO pollsets. Current values are set to: \n" " -IOt %d -IOp %d\n", no_poll_threads, no_pollsets); erts_usage(); } /* Handled arguments have been marked with NULL. Slide arguments not handled towards the beginning of argv. */ for (i = 0, j = 0; i < *argc; i++) { if (argv[i]) argv[j++] = argv[i]; } *argc = j; erts_no_pollsets = no_pollsets; erts_no_poll_threads = no_poll_threads; } void erts_init_check_io(int *argc, char **argv) { int j, concurrent_waiters, no_poll_threads; ERTS_CT_ASSERT((INT_MIN & (ERL_NIF_SELECT_STOP_CALLED | ERL_NIF_SELECT_STOP_SCHEDULED | ERL_NIF_SELECT_INVALID_EVENT | ERL_NIF_SELECT_FAILED)) == 0); erts_poll_init(&concurrent_waiters); #if ERTS_POLL_USE_FALLBACK erts_poll_init_flbk(NULL); #endif parse_args(argc, argv, concurrent_waiters); /* Create the actual pollsets */ pollsetv = erts_alloc(ERTS_ALC_T_POLLSET,sizeof(ErtsPollSet *) * erts_no_pollsets); for (j=0; j < erts_no_pollsets; j++) pollsetv[j] = erts_poll_create_pollset(j); no_poll_threads = erts_no_poll_threads; j = -1; #if ERTS_POLL_USE_SCHEDULER_POLLING sched_pollset = erts_poll_create_pollset(j--); no_poll_threads++; #endif #if ERTS_POLL_USE_FALLBACK flbk_pollset = erts_poll_create_pollset_flbk(j--); no_poll_threads++; #endif psiv = erts_alloc(ERTS_ALC_T_POLLSET, sizeof(ErtsPollThread) * no_poll_threads); #if ERTS_POLL_USE_FALLBACK psiv[0].pollres_len = ERTS_CHECK_IO_POLL_RES_LEN; psiv[0].pollres = erts_alloc(ERTS_ALC_T_POLLSET, sizeof(ErtsPollResFd) * ERTS_CHECK_IO_POLL_RES_LEN); psiv[0].ps = get_fallback_pollset(); psiv++; #endif #if ERTS_POLL_USE_SCHEDULER_POLLING psiv[0].pollres_len = ERTS_CHECK_IO_POLL_RES_LEN; psiv[0].pollres = erts_alloc(ERTS_ALC_T_POLLSET, sizeof(ErtsPollResFd) * ERTS_CHECK_IO_POLL_RES_LEN); psiv[0].ps = get_scheduler_pollset(0); psiv++; #endif for (j = 0; j < erts_no_poll_threads; j++) { psiv[j].pollres_len = ERTS_CHECK_IO_POLL_RES_LEN; psiv[j].pollres = erts_alloc(ERTS_ALC_T_POLLSET, sizeof(ErtsPollResFd) * ERTS_CHECK_IO_POLL_RES_LEN); psiv[j].ps = pollsetv[j % erts_no_pollsets]; } for (j=0; j < ERTS_CHECK_IO_DRV_EV_STATE_LOCK_CNT; j++) { erts_mtx_init(&drv_ev_state.locks[j].lck, "drv_ev_state", make_small(j), ERTS_LOCK_FLAGS_PROPERTY_STATIC | ERTS_LOCK_FLAGS_CATEGORY_IO); } #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS drv_ev_state.max_fds = erts_poll_max_fds(); erts_atomic_init_nob(&drv_ev_state.len, 0); drv_ev_state.v = NULL; erts_mtx_init(&drv_ev_state.grow_lock, "drv_ev_state_grow", NIL, ERTS_LOCK_FLAGS_PROPERTY_STATIC | ERTS_LOCK_FLAGS_CATEGORY_IO); #else { SafeHashFunctions hf; hf.hash = &drv_ev_state_hash; hf.cmp = &drv_ev_state_cmp; hf.alloc = &drv_ev_state_alloc; hf.free = &drv_ev_state_free; drv_ev_state.num_prealloc = 0; drv_ev_state.prealloc_first = NULL; erts_spinlock_init(&drv_ev_state.prealloc_lock, "state_prealloc", NIL, ERTS_LOCK_FLAGS_PROPERTY_STATIC | ERTS_LOCK_FLAGS_CATEGORY_IO); safe_hash_init(ERTS_ALC_T_DRV_EV_STATE, &drv_ev_state.tab, "drv_ev_state_tab", ERTS_LOCK_FLAGS_CATEGORY_IO, DRV_EV_STATE_HTAB_SIZE, hf); } #endif } int erts_check_io_max_files(void) { #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS return drv_ev_state.max_fds; #else return erts_poll_max_fds(); #endif } Uint erts_check_io_size(void) { Uint res = 0; ErtsPollInfo pi; int i; #if ERTS_POLL_USE_FALLBACK erts_poll_info(get_fallback_pollset(), &pi); res += pi.memory_size; #endif #if ERTS_POLL_USE_SCHEDULER_POLLING erts_poll_info(get_scheduler_pollset(0), &pi); res += pi.memory_size; #endif for (i = 0; i < erts_no_pollsets; i++) { erts_poll_info(pollsetv[i], &pi); res += pi.memory_size; } #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS res += sizeof(ErtsDrvEventState) * erts_atomic_read_nob(&drv_ev_state.len); #else res += safe_hash_table_sz(&drv_ev_state.tab); { SafeHashInfo hi; safe_hash_get_info(&hi, &drv_ev_state.tab); res += hi.objs * sizeof(ErtsDrvEventState); } erts_spin_lock(&drv_ev_state.prealloc_lock); res += drv_ev_state.num_prealloc * sizeof(ErtsDrvEventState); erts_spin_unlock(&drv_ev_state.prealloc_lock); #endif return res; } Eterm erts_check_io_info(void *proc) { Process *p = (Process *) proc; Eterm tags[16], values[16], res, list = NIL; Uint sz, *szp, *hp, **hpp; ErtsPollInfo *piv; Sint i, j = 0, len; int no_pollsets = erts_no_pollsets + ERTS_POLL_USE_FALLBACK + ERTS_POLL_USE_SCHEDULER_POLLING; ERTS_CT_ASSERT(ERTS_POLL_USE_FALLBACK == 0 || ERTS_POLL_USE_FALLBACK == 1); ERTS_CT_ASSERT(ERTS_POLL_USE_SCHEDULER_POLLING == 0 || ERTS_POLL_USE_SCHEDULER_POLLING == 1); piv = erts_alloc(ERTS_ALC_T_TMP, sizeof(ErtsPollInfo) * no_pollsets); #if ERTS_POLL_USE_FALLBACK erts_poll_info_flbk(get_fallback_pollset(), &piv[0]); piv[0].poll_threads = 0; piv[0].active_fds = 0; piv++; #endif #if ERTS_POLL_USE_SCHEDULER_POLLING erts_poll_info(get_scheduler_pollset(0), &piv[0]); piv[0].poll_threads = 0; piv[0].active_fds = 0; piv++; #endif for (j = 0; j < erts_no_pollsets; j++) { erts_poll_info(pollsetv[j], &piv[j]); piv[j].active_fds = 0; piv[j].poll_threads = erts_no_poll_threads / erts_no_pollsets; if (erts_no_poll_threads % erts_no_pollsets > j) piv[j].poll_threads++; } #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS i = 0; erts_mtx_lock(&drv_ev_state.grow_lock); len = erts_atomic_read_nob(&drv_ev_state.len); for (i = 0; i < ERTS_CHECK_IO_DRV_EV_STATE_LOCK_CNT; i++) { erts_mtx_lock(&drv_ev_state.locks[i].lck); for (j = i; j < len; j+=ERTS_CHECK_IO_DRV_EV_STATE_LOCK_CNT) { ErtsDrvEventState *state = get_drv_ev_state(j); int pollsetid = get_pollset_id(j); ASSERT(fd_mtx(j) == &drv_ev_state.locks[i].lck); if (state->flags & ERTS_EV_FLAG_FALLBACK) pollsetid = -1; if (state->driver.select && (state->type == ERTS_EV_TYPE_DRV_SEL) && (is_iotask_active(&state->driver.select->iniotask) || is_iotask_active(&state->driver.select->outiotask))) piv[pollsetid].active_fds++; } erts_mtx_unlock(&drv_ev_state.locks[i].lck); } erts_mtx_unlock(&drv_ev_state.grow_lock); piv[0].memory_size += sizeof(ErtsDrvEventState) * erts_atomic_read_nob(&drv_ev_state.len); #else piv[0].memory_size += safe_hash_table_sz(&drv_ev_state.tab); { SafeHashInfo hi; safe_hash_get_info(&hi, &drv_ev_state.tab); piv[0].memory_size += hi.objs * sizeof(ErtsDrvEventState); } erts_spin_lock(&drv_ev_state.prealloc_lock); piv[0].memory_size += drv_ev_state.num_prealloc * sizeof(ErtsDrvEventState); erts_spin_unlock(&drv_ev_state.prealloc_lock); #endif hpp = NULL; szp = &sz; sz = 0; piv -= ERTS_POLL_USE_FALLBACK; piv -= ERTS_POLL_USE_SCHEDULER_POLLING; bld_it: for (j = no_pollsets-1; j >= 0; j--) { i = 0; tags[i] = erts_bld_atom(hpp, szp, "name"); values[i++] = erts_bld_atom(hpp, szp, "erts_poll"); tags[i] = erts_bld_atom(hpp, szp, "primary"); values[i++] = erts_bld_atom(hpp, szp, piv[j].primary); tags[i] = erts_bld_atom(hpp, szp, "kernel_poll"); values[i++] = erts_bld_atom(hpp, szp, piv[j].kernel_poll ? piv[j].kernel_poll : "false"); tags[i] = erts_bld_atom(hpp, szp, "memory_size"); values[i++] = erts_bld_uint(hpp, szp, piv[j].memory_size); tags[i] = erts_bld_atom(hpp, szp, "total_poll_set_size"); values[i++] = erts_bld_uint(hpp, szp, piv[j].poll_set_size); tags[i] = erts_bld_atom(hpp, szp, "lazy_updates"); values[i++] = piv[j].lazy_updates ? am_true : am_false; tags[i] = erts_bld_atom(hpp, szp, "pending_updates"); values[i++] = erts_bld_uint(hpp, szp, piv[j].pending_updates); tags[i] = erts_bld_atom(hpp, szp, "batch_updates"); values[i++] = piv[j].batch_updates ? am_true : am_false; tags[i] = erts_bld_atom(hpp, szp, "concurrent_updates"); values[i++] = piv[j].concurrent_updates ? am_true : am_false; tags[i] = erts_bld_atom(hpp, szp, "fallback"); values[i++] = piv[j].is_fallback ? am_true : am_false; tags[i] = erts_bld_atom(hpp, szp, "max_fds"); values[i++] = erts_bld_uint(hpp, szp, piv[j].max_fds); tags[i] = erts_bld_atom(hpp, szp, "active_fds"); values[i++] = erts_bld_uint(hpp, szp, piv[j].active_fds); tags[i] = erts_bld_atom(hpp, szp, "poll_threads"); values[i++] = erts_bld_uint(hpp, szp, piv[j].poll_threads); res = erts_bld_2tup_list(hpp, szp, i, tags, values); if (!hpp) { *szp += 2; } else { list = CONS(*hpp, res, list); *hpp += 2; } } if (!hpp) { hp = HAlloc(p, sz); hpp = &hp; szp = NULL; goto bld_it; } erts_free(ERTS_ALC_T_TMP, piv); return list; } static ERTS_INLINE ErtsPollEvents print_events(erts_dsprintf_buf_t *dsbufp, ErtsPollEvents ev) { int first = 1; if(ev == ERTS_POLL_EV_NONE) { erts_dsprintf(dsbufp, "N/A"); return 0; } if(ev & ERTS_POLL_EV_IN) { ev &= ~ERTS_POLL_EV_IN; erts_dsprintf(dsbufp, "%s%s", first ? "" : "|", "IN"); first = 0; } if(ev & ERTS_POLL_EV_OUT) { ev &= ~ERTS_POLL_EV_OUT; erts_dsprintf(dsbufp, "%s%s", first ? "" : "|", "OUT"); first = 0; } /* The following should not appear... */ if(ev & ERTS_POLL_EV_NVAL) { erts_dsprintf(dsbufp, "%s%s", first ? "" : "|", "NVAL"); first = 0; } if(ev & ERTS_POLL_EV_ERR) { erts_dsprintf(dsbufp, "%s%s", first ? "" : "|", "ERR"); first = 0; } if (ev) erts_dsprintf(dsbufp, "%s0x%b32x", first ? "" : "|", (Uint32) ev); return ev; } static ERTS_INLINE void print_flags(erts_dsprintf_buf_t *dsbufp, EventStateFlags f) { erts_dsprintf(dsbufp, "%s", flag2str(f)); } #ifdef DEBUG_PRINT_MODE static ERTS_INLINE char * drvmode2str(int mode) { switch (mode) { case ERL_DRV_READ|ERL_DRV_USE: return "READ|USE"; case ERL_DRV_WRITE|ERL_DRV_USE: return "WRITE|USE"; case ERL_DRV_READ|ERL_DRV_WRITE|ERL_DRV_USE: return "READ|WRITE|USE"; case ERL_DRV_USE: return "USE"; case ERL_DRV_READ|ERL_DRV_USE_NO_CALLBACK: return "READ|USE_NO_CB"; case ERL_DRV_WRITE|ERL_DRV_USE_NO_CALLBACK: return "WRITE|USE_NO_CB"; case ERL_DRV_READ|ERL_DRV_WRITE|ERL_DRV_USE_NO_CALLBACK: return "READ|WRITE|USE_NO_CB"; case ERL_DRV_USE_NO_CALLBACK: return "USE_NO_CB"; case ERL_DRV_READ: return "READ"; case ERL_DRV_WRITE: return "WRITE"; case ERL_DRV_READ|ERL_DRV_WRITE: return "READ|WRITE"; default: return "UNKNOWN"; } } static ERTS_INLINE char * nifmode2str(enum ErlNifSelectFlags mode) { if (mode & ERL_NIF_SELECT_STOP) return "STOP"; switch (mode) { case ERL_NIF_SELECT_READ: return "READ"; case ERL_NIF_SELECT_WRITE: return "WRITE"; case ERL_NIF_SELECT_READ|ERL_NIF_SELECT_WRITE: return "READ|WRITE"; case ERL_NIF_SELECT_CANCEL|ERL_NIF_SELECT_READ: return "CANCEL|READ"; case ERL_NIF_SELECT_CANCEL|ERL_NIF_SELECT_WRITE: return "CANCEL|WRITE"; case ERL_NIF_SELECT_CANCEL|ERL_NIF_SELECT_READ|ERL_NIF_SELECT_WRITE: return "CANCEL|READ|WRITE"; default: return "UNKNOWN"; } } #endif typedef struct { int used_fds; int num_errors; int no_driver_select_structs; int no_enif_select_structs; #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS int internal_fds; ErtsPollEvents *epep; #endif } IterDebugCounters; static int erts_debug_print_checkio_state(erts_dsprintf_buf_t *dsbufp, ErtsDrvEventState *state, ErtsPollEvents ep_events, int internal) { #if defined(HAVE_FSTAT) && !defined(NO_FSTAT_ON_SYS_FD_TYPE) struct stat stat_buf; #endif ErtsSysFdType fd = state->fd; ErtsPollEvents cio_events = state->events; int err = 0; #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS ErtsPollEvents aio_events = state->active_events; #endif erts_dsprintf(dsbufp, "pollset=%d fd=%bpd ", state->flags & ERTS_EV_FLAG_FALLBACK ? -1 : get_pollset_id(fd), (SWord) fd); #if defined(HAVE_FSTAT) && !defined(NO_FSTAT_ON_SYS_FD_TYPE) if (fstat((int) fd, &stat_buf) < 0) erts_dsprintf(dsbufp, "type=unknown "); else { erts_dsprintf(dsbufp, "type="); #ifdef S_ISSOCK if (S_ISSOCK(stat_buf.st_mode)) erts_dsprintf(dsbufp, "sock "); else #endif #ifdef S_ISFIFO if (S_ISFIFO(stat_buf.st_mode)) erts_dsprintf(dsbufp, "fifo "); else #endif #ifdef S_ISCHR if (S_ISCHR(stat_buf.st_mode)) erts_dsprintf(dsbufp, "chr "); else #endif #ifdef S_ISDIR if (S_ISDIR(stat_buf.st_mode)) erts_dsprintf(dsbufp, "dir "); else #endif #ifdef S_ISBLK if (S_ISBLK(stat_buf.st_mode)) erts_dsprintf(dsbufp, "blk "); else #endif #ifdef S_ISREG if (S_ISREG(stat_buf.st_mode)) erts_dsprintf(dsbufp, "reg "); else #endif #ifdef S_ISLNK if (S_ISLNK(stat_buf.st_mode)) erts_dsprintf(dsbufp, "lnk "); else #endif #ifdef S_ISDOOR if (S_ISDOOR(stat_buf.st_mode)) erts_dsprintf(dsbufp, "door "); else #endif #ifdef S_ISWHT if (S_ISWHT(stat_buf.st_mode)) erts_dsprintf(dsbufp, "wht "); else #endif #ifdef S_ISXATTR if (S_ISXATTR(stat_buf.st_mode)) erts_dsprintf(dsbufp, "xattr "); else #endif erts_dsprintf(dsbufp, "unknown "); } #else erts_dsprintf(dsbufp, "type=unknown "); #endif if (state->type == ERTS_EV_TYPE_DRV_SEL) { erts_dsprintf(dsbufp, "driver_select "); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS if (internal) { erts_dsprintf(dsbufp, "internal "); err = 1; } if (aio_events == cio_events) { if (cio_events == ep_events) { erts_dsprintf(dsbufp, "ev="); if (print_events(dsbufp, cio_events) != 0) err = 1; } else { ErtsPollEvents ev = cio_events; if (ev != ep_events && ep_events != ERTS_POLL_EV_NONE) err = 1; erts_dsprintf(dsbufp, "cio_ev="); print_events(dsbufp, cio_events); erts_dsprintf(dsbufp, " ep_ev="); print_events(dsbufp, ep_events); } } else { erts_dsprintf(dsbufp, "cio_ev="); print_events(dsbufp, cio_events); erts_dsprintf(dsbufp, " aio_ev="); print_events(dsbufp, aio_events); if ((aio_events != ep_events && ep_events != ERTS_POLL_EV_NONE) || (aio_events != 0 && ep_events == ERTS_POLL_EV_NONE)) { erts_dsprintf(dsbufp, " ep_ev="); print_events(dsbufp, ep_events); err = 1; } } #else if (print_events(dsbufp, cio_events) != 0) err = 1; #endif erts_dsprintf(dsbufp, " "); if (cio_events & ERTS_POLL_EV_IN) { Eterm id = state->driver.select->inport; if (is_nil(id)) { erts_dsprintf(dsbufp, "inport=none inname=none indrv=none "); err = 1; } else { ErtsPortNames *pnp = erts_get_port_names(id, ERTS_INVALID_ERL_DRV_PORT); erts_dsprintf(dsbufp, " inport=%T inname=%s indrv=%s ", id, pnp->name ? pnp->name : "unknown", (pnp->driver_name ? pnp->driver_name : "unknown")); erts_free_port_names(pnp); } } if (cio_events & ERTS_POLL_EV_OUT) { Eterm id = state->driver.select->outport; if (is_nil(id)) { erts_dsprintf(dsbufp, "outport=none outname=none outdrv=none "); err = 1; } else { ErtsPortNames *pnp = erts_get_port_names(id, ERTS_INVALID_ERL_DRV_PORT); erts_dsprintf(dsbufp, " outport=%T outname=%s outdrv=%s ", id, pnp->name ? pnp->name : "unknown", (pnp->driver_name ? pnp->driver_name : "unknown")); erts_free_port_names(pnp); } } } else if (state->type == ERTS_EV_TYPE_NIF) { ErtsResource* r; erts_dsprintf(dsbufp, "enif_select "); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS if (internal) { erts_dsprintf(dsbufp, "internal "); err = 1; } if (cio_events == ep_events) { erts_dsprintf(dsbufp, "ev="); if (print_events(dsbufp, cio_events) != 0) err = 1; } else { err = 1; erts_dsprintf(dsbufp, "cio_ev="); print_events(dsbufp, cio_events); erts_dsprintf(dsbufp, " ep_ev="); print_events(dsbufp, ep_events); } #else if (print_events(dsbufp, cio_events) != 0) err = 1; #endif erts_dsprintf(dsbufp, " inpid=%T", state->driver.nif->in.pid); erts_dsprintf(dsbufp, " outpid=%T", state->driver.nif->out.pid); r = state->driver.stop.resource; erts_dsprintf(dsbufp, " resource=%p(%T:%T)", r, r->type->module, r->type->name); } #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS else if (internal) { erts_dsprintf(dsbufp, "internal "); if (cio_events) { err = 1; erts_dsprintf(dsbufp, "cio_ev="); print_events(dsbufp, cio_events); } if (ep_events) { erts_dsprintf(dsbufp, "ep_ev="); print_events(dsbufp, ep_events); } } #endif else { err = 1; erts_dsprintf(dsbufp, "control_type=%d ", (int)state->type); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS if (cio_events == ep_events) { erts_dsprintf(dsbufp, "ev="); print_events(dsbufp, cio_events); } else { erts_dsprintf(dsbufp, "cio_ev="); print_events(dsbufp, cio_events); erts_dsprintf(dsbufp, " ep_ev="); print_events(dsbufp, ep_events); } #else erts_dsprintf(dsbufp, "ev=0x%b32x", (Uint32) cio_events); #endif } erts_dsprintf(dsbufp, " flags="); print_flags(dsbufp, state->flags); if (err) { erts_dsprintf(dsbufp, " ERROR"); } erts_dsprintf(dsbufp, "\r\n"); return err; } static void doit_erts_check_io_debug(void *vstate, void *vcounters, erts_dsprintf_buf_t *dsbufp) { ErtsDrvEventState *state = (ErtsDrvEventState *) vstate; IterDebugCounters *counters = (IterDebugCounters *) vcounters; int internal = 0; #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS ErtsSysFdType fd = state->fd; ErtsPollEvents ep_events = counters->epep[(int) fd]; #else ErtsPollEvents ep_events = ERTS_POLL_EV_NONE; #endif if (state->driver.select) { counters->no_driver_select_structs++; ASSERT(state->events || (ep_events != 0 && ep_events != ERTS_POLL_EV_NONE)); } if (state->driver.nif) { counters->no_enif_select_structs++; ASSERT(state->events || (ep_events != 0 && ep_events != ERTS_POLL_EV_NONE)); } #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS if (state->events || (ep_events != 0 && ep_events != ERTS_POLL_EV_NONE)) { if (ep_events & ERTS_POLL_EV_NVAL) { ep_events &= ~ERTS_POLL_EV_NVAL; internal = 1; counters->internal_fds++; } else counters->used_fds++; #else if (state->events) { counters->used_fds++; #endif if (erts_debug_print_checkio_state(dsbufp, state, ep_events, internal)) { counters->num_errors++; } } } /* ciodpi can be NULL when called from etp-commands */ int erts_check_io_debug(ErtsCheckIoDebugInfo *ciodip) { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS int fd, len, i; #endif IterDebugCounters counters = {0}; #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS ErtsDrvEventState null_des; null_des.driver.select = NULL; null_des.driver.nif = NULL; null_des.driver.stop.drv_ptr = NULL; null_des.events = 0; null_des.type = ERTS_EV_TYPE_NONE; null_des.flags = 0; counters.epep = erts_alloc(ERTS_ALC_T_TMP, sizeof(ErtsPollEvents)*drv_ev_state.max_fds); #endif #if defined(ERTS_ENABLE_LOCK_CHECK) erts_lc_check_exact(NULL, 0); /* No locks should be locked */ #endif if (ciodip) erts_thr_progress_block(); /* stop the world to avoid messy locking */ #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS len = erts_atomic_read_nob(&drv_ev_state.len); #if ERTS_POLL_USE_FALLBACK erts_dsprintf(dsbufp, "--- fds in flbk pollset ---------------------------------\n"); erts_poll_get_selected_events_flbk(get_fallback_pollset(), counters.epep, drv_ev_state.max_fds); for (fd = 0; fd < len; fd++) { if (drv_ev_state.v[fd].flags & ERTS_EV_FLAG_FALLBACK) doit_erts_check_io_debug(&drv_ev_state.v[fd], &counters, dsbufp); } #endif #if ERTS_POLL_USE_SCHEDULER_POLLING erts_dsprintf(dsbufp, "--- fds in scheduler pollset ----------------------------\n"); erts_poll_get_selected_events(get_scheduler_pollset(0), counters.epep, drv_ev_state.max_fds); for (fd = 0; fd < len; fd++) { if (drv_ev_state.v[fd].flags & ERTS_EV_FLAG_SCHEDULER) { if (drv_ev_state.v[fd].events && drv_ev_state.v[fd].events != ERTS_POLL_EV_NONE) counters.epep[fd] &= ~ERTS_POLL_EV_OUT; doit_erts_check_io_debug(&drv_ev_state.v[fd], &counters, dsbufp); } } #endif erts_dsprintf(dsbufp, "--- fds in pollset --------------------------------------\n"); for (i = 0; i < erts_no_pollsets; i++) { erts_poll_get_selected_events(pollsetv[i], counters.epep, drv_ev_state.max_fds); for (fd = 0; fd < len; fd++) { if (!(drv_ev_state.v[fd].flags & ERTS_EV_FLAG_FALLBACK) && get_pollset_id(fd) == i) { if (counters.epep[fd] != ERTS_POLL_EV_NONE && drv_ev_state.v[fd].flags & ERTS_EV_FLAG_IN_SCHEDULER) { /* We add the in flag if it is enabled in the scheduler pollset and get_selected_events works on the platform */ counters.epep[fd] |= ERTS_POLL_EV_IN; } doit_erts_check_io_debug(&drv_ev_state.v[fd], &counters, dsbufp); } } } for (fd = len ; fd < drv_ev_state.max_fds; fd++) { null_des.fd = fd; doit_erts_check_io_debug(&null_des, &counters, dsbufp); } #else safe_hash_for_each(&drv_ev_state.tab, &doit_erts_check_io_debug, &counters, dsbufp); #endif if (ciodip) erts_thr_progress_unblock(); if (ciodip) { ciodip->no_used_fds = counters.used_fds; ciodip->no_driver_select_structs = counters.no_driver_select_structs; ciodip->no_enif_select_structs = counters.no_enif_select_structs; } erts_dsprintf(dsbufp, "\n"); erts_dsprintf(dsbufp, "used fds=%d\n", counters.used_fds); erts_dsprintf(dsbufp, "Number of driver_select() structures=%d\n", counters.no_driver_select_structs); erts_dsprintf(dsbufp, "Number of enif_select() structures=%d\n", counters.no_enif_select_structs); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS erts_dsprintf(dsbufp, "internal fds=%d\n", counters.internal_fds); #endif erts_dsprintf(dsbufp, "---------------------------------------------------------\n"); erts_send_error_to_logger_nogl(dsbufp); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS erts_free(ERTS_ALC_T_TMP, (void *) counters.epep); #endif return counters.num_errors; } #ifdef ERTS_ENABLE_LOCK_COUNT void erts_lcnt_update_cio_locks(int enable) { int i; #ifndef ERTS_SYS_CONTINOUS_FD_NUMBERS erts_lcnt_enable_hash_lock_count(&drv_ev_state.tab, ERTS_LOCK_FLAGS_CATEGORY_IO, enable); #else (void)enable; #endif #if ERTS_POLL_USE_FALLBACK erts_lcnt_enable_pollset_lock_count_flbk(get_fallback_pollset(), enable); #endif for (i = 0; i < erts_no_pollsets; i++) erts_lcnt_enable_pollset_lock_count(pollsetv[i], enable); } #endif /* ERTS_ENABLE_LOCK_COUNT */
lrascao/otp
erts/emulator/sys/common/erl_check_io.c
C
apache-2.0
95,170
--- title: ICompletionProposal.attributes - aesi-java --- [aesi-java](../../index.html) / [com.virtlink.editorservices.codecompletion](../index.html) / [ICompletionProposal](index.html) / [attributes](.) # attributes `abstract val attributes: `[`EnumSet`](http://docs.oracle.com/javase/6/docs/api/java/util/EnumSet.html)`<`[`Attribute`](../-attribute/index.html)`>`
Virtlink/aesi
docs/aesi-java/com.virtlink.editorservices.codecompletion/-i-completion-proposal/attributes.md
Markdown
apache-2.0
368
package org.zentaur.core.http; /* * Copyright 2012 The Zentaur Server 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. */ import org.zentaur.http.Response; /** * Factory delegated to {@link Response} instances creation. */ public final class ResponseFactory { /** * Creates a new {@link Response} instance. * * @return a new {@link Response} instance. */ public static Response newResponse() { return new DefaultResponse(); } /** * Hidden constructor, this class cannot be instantiated. */ private ResponseFactory() { // do nothing } }
zentaur/core
src/main/java/org/zentaur/core/http/ResponseFactory.java
Java
apache-2.0
1,161
<?xml version="1.0" encoding="utf-8"?> <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"><ShortName>National Water Supply and Drainage Board</ShortName><Description>National Water Supply and Drainage Board</Description><InputEncoding>UTF-8</InputEncoding><Image type="image/vnd.microsoft.icon" width="16" height="16">http://waterboard.lk/web/templates/poora_temp/favicon.ico</Image><Url type="application/opensearchdescription+xml" rel="self" template="http://waterboard.lk/web/index.php?option=com_search&amp;view=article&amp;id=218&amp;Itemid=325&amp;lang=si&amp;format=opensearch"/><Url type="text/html" template="http://waterboard.lk/web/index.php?option=com_search&amp;searchword={searchTerms}&amp;Itemid=188"/></OpenSearchDescription>
cmaere/lwb
templates/protostar/index8fa5.php
PHP
apache-2.0
759
// Copyright 2016 PingCAP, 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, // See the License for the specific language governing permissions and // limitations under the License. package tikv import ( "github.com/juju/errors" "github.com/pingcap/tidb/mysql" "github.com/pingcap/tidb/terror" ) var ( // ErrBodyMissing response body is missing error ErrBodyMissing = errors.New("response body is missing") ) // TiDB decides whether to retry transaction by checking if error message contains // string "try again later" literally. // In TiClient we use `errors.Annotate(err, txnRetryableMark)` to direct TiDB to // restart a transaction. // Note that it should be only used if i) the error occurs inside a transaction // and ii) the error is not totally unexpected and hopefully will recover soon. const txnRetryableMark = "[try again later]" // MySQL error instances. var ( ErrTiKVServerTimeout = terror.ClassTiKV.New(mysql.ErrTiKVServerTimeout, mysql.MySQLErrName[mysql.ErrTiKVServerTimeout]+txnRetryableMark) ErrResolveLockTimeout = terror.ClassTiKV.New(mysql.ErrResolveLockTimeout, mysql.MySQLErrName[mysql.ErrResolveLockTimeout]+txnRetryableMark) ErrPDServerTimeout = terror.ClassTiKV.New(mysql.ErrPDServerTimeout, mysql.MySQLErrName[mysql.ErrPDServerTimeout]+"%v") ErrRegionUnavailable = terror.ClassTiKV.New(mysql.ErrRegionUnavailable, mysql.MySQLErrName[mysql.ErrRegionUnavailable]+txnRetryableMark) ErrTiKVServerBusy = terror.ClassTiKV.New(mysql.ErrTiKVServerBusy, mysql.MySQLErrName[mysql.ErrTiKVServerBusy]+txnRetryableMark) ErrGCTooEarly = terror.ClassTiKV.New(mysql.ErrGCTooEarly, mysql.MySQLErrName[mysql.ErrGCTooEarly]) ) func init() { tikvMySQLErrCodes := map[terror.ErrCode]uint16{ mysql.ErrTiKVServerTimeout: mysql.ErrTiKVServerTimeout, mysql.ErrResolveLockTimeout: mysql.ErrResolveLockTimeout, mysql.ErrPDServerTimeout: mysql.ErrPDServerTimeout, mysql.ErrRegionUnavailable: mysql.ErrRegionUnavailable, mysql.ErrTiKVServerBusy: mysql.ErrTiKVServerBusy, mysql.ErrGCTooEarly: mysql.ErrGCTooEarly, } terror.ErrClassToMySQLCodes[terror.ClassTiKV] = tikvMySQLErrCodes }
spongedu/tidb
store/tikv/error.go
GO
apache-2.0
2,481
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mermaid.Loft.Infrastructure.DomainBase { public class EntityBase { } }
mengxinjinglong/Mermaid.Loft
Mermaid.Loft.Infrastructure/DomainBase/EntityBase.cs
C#
apache-2.0
214
package pl.wavesoftware.examples.wildflyswarm.service.api; import pl.wavesoftware.examples.wildflyswarm.domain.User; import java.util.Collection; /** * @author Krzysztof Suszynski <[email protected]> * @since 04.03.16 */ public interface UserService { /** * Retrieves a collection of active users * @return a collection with only active users */ Collection<User> fetchActiveUsers(); }
cardil/cdi-inheritance-wildfly-swarm
src/main/java/pl/wavesoftware/examples/wildflyswarm/service/api/UserService.java
Java
apache-2.0
427
#!/bin/bash # Copyright 2016 - 2020 Crunchy Data Solutions, 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. DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" CONTAINER_NAME='custom-config-ssl' PGDATA_VOL="${CONTAINER_NAME?}-pgdata" BACKUP_VOL="${CONTAINER_NAME?}-backup" ${DIR?}/cleanup.sh ${DIR?}/../../ssl-creator.sh "[email protected]" "${CONTAINER_NAME?}" "$(pwd)" if [[ $? -ne 0 ]] then echo "Failed to create certs, exiting.." exit 1 fi cp ${DIR?}/certs/server.* ${DIR?}/configs cp ${DIR?}/certs/ca.* ${DIR?}/configs echo "Starting the ${CONTAINER_NAME} example..." docker volume create --driver local --name=${PGDATA_VOL?} docker volume create --driver local --name=${BACKUP_VOL?} docker run \ --name=${CONTAINER_NAME?} \ --hostname=${CONTAINER_NAME?} \ --publish=5432:5432 \ --volume=${DIR?}/configs:/pgconf \ --volume=${PGDATA_VOL?}:/pgdata \ --volume=${BACKUP_VOL?}:/backrestrepo \ --env=PG_MODE=primary \ --env=PG_PRIMARY_USER=primaryuser \ --env=PG_PRIMARY_PASSWORD=password \ --env=PG_PRIMARY_HOST=localhost \ --env=PG_PRIMARY_PORT=5432 \ --env=PG_DATABASE=userdb \ --env=PG_USER=testuser \ --env=PG_PASSWORD=password \ --env=PG_ROOT_PASSWORD=password \ --env=PGHOST=/tmp \ --env=XLOGDIR=true \ --env=PGBACKREST=true \ --detach ${CCP_IMAGE_PREFIX?}/crunchy-postgres:${CCP_IMAGE_TAG?} echo "" echo "To connect via SSL, run the following once the DB is ready: " echo "psql \"postgresql://testuser@${CONTAINER_NAME?}:5432/userdb?\ sslmode=verify-full&\ sslrootcert=$CCPROOT/examples/docker/custom-config-ssl/certs/ca.crt&\ sslcrl=$CCPROOT/examples/docker/custom-config-ssl/certs/ca.crl&\ sslcert=$CCPROOT/examples/docker/custom-config-ssl/certs/client.crt&\ sslkey=$CCPROOT/examples/docker/custom-config-ssl/certs/client.key\"" echo ""
the1forte/crunchy-containers
examples/docker/custom-config-ssl/run.sh
Shell
apache-2.0
2,347
<?php /** * Copyright (c) <2016> Protobile contributors and Addvilz <[email protected]>. * * 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. */ namespace Protobile\Framework\CompilerPass; use Symfony\Component\Console\Output\ConsoleOutput; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class RegisterOutputPass implements CompilerPassInterface { /** * @param ContainerBuilder $container */ public function process(ContainerBuilder $container) { $container->register('app.output', ConsoleOutput::class); } }
protobile/framework
src/Protobile/Framework/CompilerPass/RegisterOutputPass.php
PHP
apache-2.0
1,123
/* * #%L * ===================================================== * _____ _ ____ _ _ _ _ * |_ _|_ __ _ _ ___| |_ / __ \| | | | ___ | | | | * | | | '__| | | / __| __|/ / _` | |_| |/ __|| |_| | * | | | | | |_| \__ \ |_| | (_| | _ |\__ \| _ | * |_| |_| \__,_|___/\__|\ \__,_|_| |_||___/|_| |_| * \____/ * * ===================================================== * * Hochschule Hannover * (University of Applied Sciences and Arts, Hannover) * Faculty IV, Dept. of Computer Science * Ricklinger Stadtweg 118, 30459 Hannover, Germany * * Email: [email protected] * Website: http://trust.f4.hs-hannover.de/ * * This file is part of ifmapj, version 2.3.2, implemented by the Trust@HsH * research group at the Hochschule Hannover. * %% * Copyright (C) 2010 - 2016 Trust@HsH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package de.hshannover.f4.trust.ifmapj.messages; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import de.hshannover.f4.trust.ifmapj.exception.IfmapErrorResult; import de.hshannover.f4.trust.ifmapj.messages.SearchResult.Type; /** * Implementation of {@link PollResult} * * @author aw * */ class PollResultImpl implements PollResult { private final List<SearchResult> mResults; private final Collection<IfmapErrorResult> mErrorResults; PollResultImpl(List<SearchResult> results, Collection<IfmapErrorResult> eres) { if (results == null || eres == null) { throw new NullPointerException("result list is null"); } mResults = new ArrayList<SearchResult>(results); mErrorResults = new ArrayList<IfmapErrorResult>(eres); } @Override public List<SearchResult> getResults() { return Collections.unmodifiableList(mResults); } @Override public Collection<SearchResult> getSearchResults() { return resultsOfType(SearchResult.Type.searchResult); } @Override public Collection<SearchResult> getUpdateResults() { return resultsOfType(SearchResult.Type.updateResult); } @Override public Collection<SearchResult> getDeleteResults() { return resultsOfType(SearchResult.Type.deleteResult); } @Override public Collection<SearchResult> getNotifyResults() { return resultsOfType(SearchResult.Type.notifyResult); } @Override public Collection<IfmapErrorResult> getErrorResults() { return Collections.unmodifiableCollection(mErrorResults); } private Collection<SearchResult> resultsOfType(Type type) { List<SearchResult> ret = new ArrayList<SearchResult>(); for (SearchResult sr : mResults) { if (sr.getType() == type) { ret.add(sr); } } return Collections.unmodifiableCollection(ret); } }
trustathsh/ifmapj
src/main/java/de/hshannover/f4/trust/ifmapj/messages/PollResultImpl.java
Java
apache-2.0
3,270
--- layout: default --- What’s wrong with SOAP ====================== Many things. Brittle ------- Pretty much every change you might make to an interface is a breaking change for a SOAP client. Want to add a new parameter to a returned object - breaking change. Want to add a new optional parameter to a call - breaking change. Want to change the type of a request parameter from int32 to int64 - breaking change. You get the message. Some of these could be resolved by diverging from the spec on the server side, but we can’t do anything about the myriad of SOAP clients available. Essentially, almost every minor release of an interface would have to be a major release if SOAP is to be supported. We don’t want to hobble Cougar like this, so we choose to quietly ignore this fact and suggest you don’t use SOAP unless you can control the clients or afford to run many parallel versions of your interface (Cougar can run parallel major versions but can’t run parallel minor versions - a conscious choice and fine since minor versions should be backwards compatible). If you have to use XML, at least use XML with Rescript. Big --- Serialised requests / responses are much larger in SOAP than in other formats such as JSON. This is due both to the SOAP envelope which is a large overhead for small object trees and also due to the expressiveness of XML, compare: <SomeObject> <SomeParameter>SomeValue</SomeParameter> </SomeObject> {“SomeParameter”:”SomeValue”} Granted, using tiny names would ameliorate this, but that’s gonna be a pain to debug. Slow ---- Related to the previous - SOAP is far slower to serialise/deserialise than the alternatives, it’s CPU intensive. Cougar is intended to be high performance, SOAP serialisation costs could far outweigh the processing costs for the operation.
betfair/cougar-documentation
whats-wrong-with-soap.md
Markdown
apache-2.0
1,853
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorator="fragments/layout"> <body> <form method="post" enctype="multipart/form-data" class="form-horizontal"> <fieldset> <legend th:text="#{nav.role}">File</legend> <div class="form-group" th:classappend="${#fields.hasErrors('name')}? 'has-error has-feedback'"> <label for="name" class="col-sm-2 control-label" th:text="#{name}">Name</label> <div class="col-xs-3"> <input type="text" id="name" name="name" th:field="*{name}" class="form-control" value="ee"/> <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="help-block">error!</span> </div> </div> <div class="form-group" th:classappend="${#fields.hasErrors('file')}? 'has-error has-feedback'"> <label for="file" class="col-sm-2 control-label" th:text="#{file}">File</label> <div class="col-xs-3"> <input type="file" id="file" name="file" th:field="*{file}" class="form-control" value="ee"/> <span th:if="${#fields.hasErrors('file')}" th:errors="*{file}" class="help-block">error!</span> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-primary">save</button> </div> </div> </fieldset> </form> </div> </body> </html>
przodownikR1/imageMicroService
src/main/resources/templates/upload/upload.html
HTML
apache-2.0
1,566
/* * Copyright 2020 Google LLC * * 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 * * https://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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/resourcemanager/v3/folders.proto package com.google.cloud.resourcemanager.v3; /** * * * <pre> * The request sent to the * [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder] * method. * Only the `display_name` field can be changed. All other fields will be * ignored. Use the * [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] method to * change the `parent` field. * </pre> * * Protobuf type {@code google.cloud.resourcemanager.v3.UpdateFolderRequest} */ public final class UpdateFolderRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.resourcemanager.v3.UpdateFolderRequest) UpdateFolderRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateFolderRequest.newBuilder() to construct. private UpdateFolderRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateFolderRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateFolderRequest(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private UpdateFolderRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.resourcemanager.v3.Folder.Builder subBuilder = null; if (folder_ != null) { subBuilder = folder_.toBuilder(); } folder_ = input.readMessage( com.google.cloud.resourcemanager.v3.Folder.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(folder_); folder_ = subBuilder.buildPartial(); } break; } case 18: { com.google.protobuf.FieldMask.Builder subBuilder = null; if (updateMask_ != null) { subBuilder = updateMask_.toBuilder(); } updateMask_ = input.readMessage(com.google.protobuf.FieldMask.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(updateMask_); updateMask_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.resourcemanager.v3.FoldersProto .internal_static_google_cloud_resourcemanager_v3_UpdateFolderRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.resourcemanager.v3.FoldersProto .internal_static_google_cloud_resourcemanager_v3_UpdateFolderRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.resourcemanager.v3.UpdateFolderRequest.class, com.google.cloud.resourcemanager.v3.UpdateFolderRequest.Builder.class); } public static final int FOLDER_FIELD_NUMBER = 1; private com.google.cloud.resourcemanager.v3.Folder folder_; /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the folder field is set. */ @java.lang.Override public boolean hasFolder() { return folder_ != null; } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The folder. */ @java.lang.Override public com.google.cloud.resourcemanager.v3.Folder getFolder() { return folder_ == null ? com.google.cloud.resourcemanager.v3.Folder.getDefaultInstance() : folder_; } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.resourcemanager.v3.FolderOrBuilder getFolderOrBuilder() { return getFolder(); } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return updateMask_ != null; } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return getUpdateMask(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (folder_ != null) { output.writeMessage(1, getFolder()); } if (updateMask_ != null) { output.writeMessage(2, getUpdateMask()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (folder_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getFolder()); } if (updateMask_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.resourcemanager.v3.UpdateFolderRequest)) { return super.equals(obj); } com.google.cloud.resourcemanager.v3.UpdateFolderRequest other = (com.google.cloud.resourcemanager.v3.UpdateFolderRequest) obj; if (hasFolder() != other.hasFolder()) return false; if (hasFolder()) { if (!getFolder().equals(other.getFolder())) return false; } if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask().equals(other.getUpdateMask())) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasFolder()) { hash = (37 * hash) + FOLDER_FIELD_NUMBER; hash = (53 * hash) + getFolder().hashCode(); } if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.resourcemanager.v3.UpdateFolderRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The request sent to the * [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder] * method. * Only the `display_name` field can be changed. All other fields will be * ignored. Use the * [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] method to * change the `parent` field. * </pre> * * Protobuf type {@code google.cloud.resourcemanager.v3.UpdateFolderRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.resourcemanager.v3.UpdateFolderRequest) com.google.cloud.resourcemanager.v3.UpdateFolderRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.resourcemanager.v3.FoldersProto .internal_static_google_cloud_resourcemanager_v3_UpdateFolderRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.resourcemanager.v3.FoldersProto .internal_static_google_cloud_resourcemanager_v3_UpdateFolderRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.resourcemanager.v3.UpdateFolderRequest.class, com.google.cloud.resourcemanager.v3.UpdateFolderRequest.Builder.class); } // Construct using com.google.cloud.resourcemanager.v3.UpdateFolderRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); if (folderBuilder_ == null) { folder_ = null; } else { folder_ = null; folderBuilder_ = null; } if (updateMaskBuilder_ == null) { updateMask_ = null; } else { updateMask_ = null; updateMaskBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.resourcemanager.v3.FoldersProto .internal_static_google_cloud_resourcemanager_v3_UpdateFolderRequest_descriptor; } @java.lang.Override public com.google.cloud.resourcemanager.v3.UpdateFolderRequest getDefaultInstanceForType() { return com.google.cloud.resourcemanager.v3.UpdateFolderRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.resourcemanager.v3.UpdateFolderRequest build() { com.google.cloud.resourcemanager.v3.UpdateFolderRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.resourcemanager.v3.UpdateFolderRequest buildPartial() { com.google.cloud.resourcemanager.v3.UpdateFolderRequest result = new com.google.cloud.resourcemanager.v3.UpdateFolderRequest(this); if (folderBuilder_ == null) { result.folder_ = folder_; } else { result.folder_ = folderBuilder_.build(); } if (updateMaskBuilder_ == null) { result.updateMask_ = updateMask_; } else { result.updateMask_ = updateMaskBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.resourcemanager.v3.UpdateFolderRequest) { return mergeFrom((com.google.cloud.resourcemanager.v3.UpdateFolderRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.resourcemanager.v3.UpdateFolderRequest other) { if (other == com.google.cloud.resourcemanager.v3.UpdateFolderRequest.getDefaultInstance()) return this; if (other.hasFolder()) { mergeFolder(other.getFolder()); } if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.resourcemanager.v3.UpdateFolderRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.resourcemanager.v3.UpdateFolderRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private com.google.cloud.resourcemanager.v3.Folder folder_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.resourcemanager.v3.Folder, com.google.cloud.resourcemanager.v3.Folder.Builder, com.google.cloud.resourcemanager.v3.FolderOrBuilder> folderBuilder_; /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the folder field is set. */ public boolean hasFolder() { return folderBuilder_ != null || folder_ != null; } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The folder. */ public com.google.cloud.resourcemanager.v3.Folder getFolder() { if (folderBuilder_ == null) { return folder_ == null ? com.google.cloud.resourcemanager.v3.Folder.getDefaultInstance() : folder_; } else { return folderBuilder_.getMessage(); } } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setFolder(com.google.cloud.resourcemanager.v3.Folder value) { if (folderBuilder_ == null) { if (value == null) { throw new NullPointerException(); } folder_ = value; onChanged(); } else { folderBuilder_.setMessage(value); } return this; } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setFolder(com.google.cloud.resourcemanager.v3.Folder.Builder builderForValue) { if (folderBuilder_ == null) { folder_ = builderForValue.build(); onChanged(); } else { folderBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeFolder(com.google.cloud.resourcemanager.v3.Folder value) { if (folderBuilder_ == null) { if (folder_ != null) { folder_ = com.google.cloud.resourcemanager.v3.Folder.newBuilder(folder_) .mergeFrom(value) .buildPartial(); } else { folder_ = value; } onChanged(); } else { folderBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearFolder() { if (folderBuilder_ == null) { folder_ = null; onChanged(); } else { folder_ = null; folderBuilder_ = null; } return this; } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.resourcemanager.v3.Folder.Builder getFolderBuilder() { onChanged(); return getFolderFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.resourcemanager.v3.FolderOrBuilder getFolderOrBuilder() { if (folderBuilder_ != null) { return folderBuilder_.getMessageOrBuilder(); } else { return folder_ == null ? com.google.cloud.resourcemanager.v3.Folder.getDefaultInstance() : folder_; } } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.resourcemanager.v3.Folder, com.google.cloud.resourcemanager.v3.Folder.Builder, com.google.cloud.resourcemanager.v3.FolderOrBuilder> getFolderFieldBuilder() { if (folderBuilder_ == null) { folderBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.resourcemanager.v3.Folder, com.google.cloud.resourcemanager.v3.Folder.Builder, com.google.cloud.resourcemanager.v3.FolderOrBuilder>( getFolder(), getParentForChildren(), isClean()); folder_ = null; } return folderBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return updateMaskBuilder_ != null || updateMask_ != null; } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; onChanged(); } else { updateMaskBuilder_.setMessage(value); } return this; } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); onChanged(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (updateMask_ != null) { updateMask_ = com.google.protobuf.FieldMask.newBuilder(updateMask_).mergeFrom(value).buildPartial(); } else { updateMask_ = value; } onChanged(); } else { updateMaskBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearUpdateMask() { if (updateMaskBuilder_ == null) { updateMask_ = null; onChanged(); } else { updateMask_ = null; updateMaskBuilder_ = null; } return this; } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.resourcemanager.v3.UpdateFolderRequest) } // @@protoc_insertion_point(class_scope:google.cloud.resourcemanager.v3.UpdateFolderRequest) private static final com.google.cloud.resourcemanager.v3.UpdateFolderRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.resourcemanager.v3.UpdateFolderRequest(); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateFolderRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateFolderRequest>() { @java.lang.Override public UpdateFolderRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new UpdateFolderRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<UpdateFolderRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateFolderRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.resourcemanager.v3.UpdateFolderRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/java-resourcemanager
proto-google-cloud-resourcemanager-v3/src/main/java/com/google/cloud/resourcemanager/v3/UpdateFolderRequest.java
Java
apache-2.0
34,397
// // XABCheckJobViewController.h // XAnBao // // Created by Minlay on 17/3/29. // Copyright © 2017年 Minlay. All rights reserved. // #import "YBBaseViewController.h" @interface XABCheckJobViewController : YBBaseViewController @property(nonatomic, copy)NSString *classId; @property(nonatomic, assign)NSInteger type; @property(nonatomic, copy)NSString *className; @end
NerveTeam/XAnbao
XAnBao/XAnBao/Controller/Class/XABCheckJobViewController.h
C
apache-2.0
376
package com.lyubenblagoev.postfixrest.service; import com.lyubenblagoev.postfixrest.entity.User; import com.lyubenblagoev.postfixrest.security.JwtTokenProvider; import com.lyubenblagoev.postfixrest.security.RefreshTokenProvider; import com.lyubenblagoev.postfixrest.security.UserPrincipal; import com.lyubenblagoev.postfixrest.service.model.AuthResponse; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityNotFoundException; import java.util.Optional; @Service @Transactional(readOnly = true) public class AuthServiceImpl implements AuthService { private final JwtTokenProvider jwtTokenProvider; private final RefreshTokenProvider refreshTokenProvider; private final UserService userService; public AuthServiceImpl(JwtTokenProvider jwtTokenProvider, RefreshTokenProvider refreshTokenProvider, UserService userService) { this.jwtTokenProvider = jwtTokenProvider; this.refreshTokenProvider = refreshTokenProvider; this.userService = userService; } @Override public AuthResponse createTokens(String email) { Optional<User> userOptional = userService.findByEmail(email); if (userOptional.isEmpty()) { throw new EntityNotFoundException("Failed to find user with email " + email); } UserPrincipal userPrincipal = new UserPrincipal(userOptional.get()); String token = jwtTokenProvider.createToken(userPrincipal.getUsername(), userPrincipal.getAuthorities()); RefreshTokenProvider.RefreshToken refreshToken = refreshTokenProvider.createToken(); return new AuthResponse(token, refreshToken.getToken(), refreshToken.getExpirationDate()); } }
lyubenblagoev/postfix-rest-server
src/main/java/com/lyubenblagoev/postfixrest/service/AuthServiceImpl.java
Java
apache-2.0
1,809
/** * @license * Copyright 2012 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Checkbox field. Checked or not checked. * @author [email protected] (Neil Fraser) */ 'use strict'; goog.provide('Blockly.FieldCheckbox'); /** @suppress {extraRequire} */ goog.require('Blockly.Events.BlockChange'); goog.require('Blockly.Field'); goog.require('Blockly.fieldRegistry'); goog.require('Blockly.utils.dom'); goog.require('Blockly.utils.object'); /** * Class for a checkbox field. * @param {string|boolean=} opt_value The initial value of the field. Should * either be 'TRUE', 'FALSE' or a boolean. Defaults to 'FALSE'. * @param {Function=} opt_validator A function that is called to validate * changes to the field's value. Takes in a value ('TRUE' or 'FALSE') & * returns a validated value ('TRUE' or 'FALSE'), or null to abort the * change. * @param {Object=} opt_config A map of options used to configure the field. * See the [field creation documentation]{@link https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/checkbox#creation} * for a list of properties this parameter supports. * @extends {Blockly.Field} * @constructor */ Blockly.FieldCheckbox = function(opt_value, opt_validator, opt_config) { /** * Character for the check mark. Used to apply a different check mark * character to individual fields. * @type {?string} * @private */ this.checkChar_ = null; Blockly.FieldCheckbox.superClass_.constructor.call( this, opt_value, opt_validator, opt_config); }; Blockly.utils.object.inherits(Blockly.FieldCheckbox, Blockly.Field); /** * The default value for this field. * @type {*} * @protected */ Blockly.FieldCheckbox.prototype.DEFAULT_VALUE = false; /** * Construct a FieldCheckbox from a JSON arg object. * @param {!Object} options A JSON object with options (checked). * @return {!Blockly.FieldCheckbox} The new field instance. * @package * @nocollapse */ Blockly.FieldCheckbox.fromJson = function(options) { return new Blockly.FieldCheckbox(options['checked'], undefined, options); }; /** * Default character for the checkmark. * @type {string} * @const */ Blockly.FieldCheckbox.CHECK_CHAR = '\u2713'; /** * Serializable fields are saved by the XML renderer, non-serializable fields * are not. Editable fields should also be serializable. * @type {boolean} */ Blockly.FieldCheckbox.prototype.SERIALIZABLE = true; /** * Mouse cursor style when over the hotspot that initiates editability. */ Blockly.FieldCheckbox.prototype.CURSOR = 'default'; /** * Configure the field based on the given map of options. * @param {!Object} config A map of options to configure the field based on. * @protected * @override */ Blockly.FieldCheckbox.prototype.configure_ = function(config) { Blockly.FieldCheckbox.superClass_.configure_.call(this, config); if (config['checkCharacter']) { this.checkChar_ = config['checkCharacter']; } }; /** * Create the block UI for this checkbox. * @package */ Blockly.FieldCheckbox.prototype.initView = function() { Blockly.FieldCheckbox.superClass_.initView.call(this); Blockly.utils.dom.addClass( /** @type {!SVGTextElement} **/ (this.textElement_), 'blocklyCheckbox'); this.textElement_.style.display = this.value_ ? 'block' : 'none'; }; /** * @override */ Blockly.FieldCheckbox.prototype.render_ = function() { if (this.textContent_) { this.textContent_.nodeValue = this.getDisplayText_(); } this.updateSize_(this.getConstants().FIELD_CHECKBOX_X_OFFSET); }; /** * @override */ Blockly.FieldCheckbox.prototype.getDisplayText_ = function() { return this.checkChar_ || Blockly.FieldCheckbox.CHECK_CHAR; }; /** * Set the character used for the check mark. * @param {?string} character The character to use for the check mark, or * null to use the default. */ Blockly.FieldCheckbox.prototype.setCheckCharacter = function(character) { this.checkChar_ = character; this.forceRerender(); }; /** * Toggle the state of the checkbox on click. * @protected */ Blockly.FieldCheckbox.prototype.showEditor_ = function() { this.setValue(!this.value_); }; /** * Ensure that the input value is valid ('TRUE' or 'FALSE'). * @param {*=} opt_newValue The input value. * @return {?string} A valid value ('TRUE' or 'FALSE), or null if invalid. * @protected */ Blockly.FieldCheckbox.prototype.doClassValidation_ = function(opt_newValue) { if (opt_newValue === true || opt_newValue === 'TRUE') { return 'TRUE'; } if (opt_newValue === false || opt_newValue === 'FALSE') { return 'FALSE'; } return null; }; /** * Update the value of the field, and update the checkElement. * @param {*} newValue The value to be saved. The default validator guarantees * that this is a either 'TRUE' or 'FALSE'. * @protected */ Blockly.FieldCheckbox.prototype.doValueUpdate_ = function(newValue) { this.value_ = this.convertValueToBool_(newValue); // Update visual. if (this.textElement_) { this.textElement_.style.display = this.value_ ? 'block' : 'none'; } }; /** * Get the value of this field, either 'TRUE' or 'FALSE'. * @return {string} The value of this field. */ Blockly.FieldCheckbox.prototype.getValue = function() { return this.value_ ? 'TRUE' : 'FALSE'; }; /** * Get the boolean value of this field. * @return {boolean} The boolean value of this field. */ Blockly.FieldCheckbox.prototype.getValueBoolean = function() { return /** @type {boolean} */ (this.value_); }; /** * Get the text of this field. Used when the block is collapsed. * @return {string} Text representing the value of this field * ('true' or 'false'). */ Blockly.FieldCheckbox.prototype.getText = function() { return String(this.convertValueToBool_(this.value_)); }; /** * Convert a value into a pure boolean. * * Converts 'TRUE' to true and 'FALSE' to false correctly, everything else * is cast to a boolean. * @param {*} value The value to convert. * @return {boolean} The converted value. * @private */ Blockly.FieldCheckbox.prototype.convertValueToBool_ = function(value) { if (typeof value == 'string') { return value == 'TRUE'; } else { return !!value; } }; Blockly.fieldRegistry.register('field_checkbox', Blockly.FieldCheckbox);
mark-friedman/blockly
core/field_checkbox.js
JavaScript
apache-2.0
6,315
package task03.pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; public class TicketSelectionPage extends Page { public TicketSelectionPage(PageManager pages) { super(pages); } @FindBy(xpath = ".//*[@id='fareRowContainer_0']/tbody/tr[2]/td[2]") private WebElement firstTicket; @FindBy(xpath = ".//*[@id='fareRowContainer_0']/tbody/tr[2]/td[2]") private WebElement secondTicket; @FindBy(id = "tripSummarySubmitBtn") private WebElement submitButton; public void select2Tickets() { wait.until(ExpectedConditions.elementToBeClickable(firstTicket)); firstTicket.click(); wait.until(ExpectedConditions.elementToBeClickable(secondTicket)); secondTicket.click(); wait.until(ExpectedConditions.elementToBeClickable(submitButton)); submitButton.submit(); } }
RihnKornak/TestTasks
src/test/java/task03/pages/TicketSelectionPage.java
Java
apache-2.0
945
using System.Collections; using System.Collections.Generic; namespace Basic.Ast { public class ParameterList : IEnumerable<Parameter> { private readonly List<Parameter> parameters; public ParameterList() { parameters = new List<Parameter>(); } public MethodDef Method { get; private set; } #region IEnumerable<Parameter> Members public IEnumerator<Parameter> GetEnumerator() { return parameters.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return parameters.GetEnumerator(); } #endregion public void SetMethod(MethodDef method) { Method = method; } public void Add(Parameter param) { parameters.Add(param); } public void Define() { foreach (Parameter p in parameters) { p.Define(); } } public void Resolve() { foreach (Parameter p in parameters) { p.Resolve(); } } public void CreateParameterBuilders() { foreach (Parameter p in parameters) { p.DefineParameterBuilder(); } } public Parameter Get(string name) { return parameters.Find(x => x.Name == name); } } }
robertsundstrom/vb-lite-compiler
basc/Ast/ParameterList.cs
C#
apache-2.0
1,481
# at-rule-name-case Specify lowercase or uppercase for at-rules names. <!-- prettier-ignore --> ```css @media (min-width: 10px) {} /** ↑ * This at-rule name */ ``` Only lowercase at-rule names are valid in SCSS. The [`fix` option](../../../docs/user-guide/usage/options.md#fix) can automatically fix some of the problems reported by this rule. ## Options `string`: `"lower"|"upper"` ### `"lower"` The following patterns are considered violations: <!-- prettier-ignore --> ```css @Charset 'UTF-8'; ``` <!-- prettier-ignore --> ```css @cHarSeT 'UTF-8'; ``` <!-- prettier-ignore --> ```css @CHARSET 'UTF-8'; ``` <!-- prettier-ignore --> ```css @Media (min-width: 50em) {} ``` <!-- prettier-ignore --> ```css @mEdIa (min-width: 50em) {} ``` <!-- prettier-ignore --> ```css @MEDIA (min-width: 50em) {} ``` The following patterns are _not_ considered violations: <!-- prettier-ignore --> ```css @charset 'UTF-8'; ``` <!-- prettier-ignore --> ```css @media (min-width: 50em) {} ``` ### `"upper"` The following patterns are considered violations: <!-- prettier-ignore --> ```css @Charset 'UTF-8'; ``` <!-- prettier-ignore --> ```css @cHarSeT 'UTF-8'; ``` <!-- prettier-ignore --> ```css @charset 'UTF-8'; ``` <!-- prettier-ignore --> ```css @Media (min-width: 50em) {} ``` <!-- prettier-ignore --> ```css @mEdIa (min-width: 50em) {} ``` <!-- prettier-ignore --> ```css @media (min-width: 50em) {} ``` The following patterns are _not_ considered violations: <!-- prettier-ignore --> ```css @CHARSET 'UTF-8'; ``` <!-- prettier-ignore --> ```css @MEDIA (min-width: 50em) {} ```
kyleterry/sufr
pkg/ui/node_modules/stylelint/lib/rules/at-rule-name-case/README.md
Markdown
apache-2.0
1,601
/* Copyright [2011] [Prasad Balan] 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.yarsquidy.x12; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Scanner; import java.util.regex.Pattern; /** * The class represents methods used to translate a X12 transaction represented * as a file or string into an X12 object. * * @author Prasad Balan * @version $Id: $Id */ public class X12Parser implements Parser { private static final int SIZE = 106; /** Constant <code>POS_SEGMENT=105</code> */ public static final int POS_SEGMENT = 105; /** Constant <code>POS_ELEMENT=3</code> */ public static final int POS_ELEMENT = 3; /** Constant <code>POS_COMPOSITE_ELEMENT=104</code> */ public static final int POS_COMPOSITE_ELEMENT = 104; /** Constant <code>START_TAG="ISA"</code> */ public static final String START_TAG = "ISA"; private Cf x12Cf; private Cf cfMarker; private Loop loopMarker; /** * <p>Constructor for X12Parser.</p> * * @param cf a {@link Cf} object. */ public X12Parser(Cf cf) { this.x12Cf = cf; } /** * {@inheritDoc} * * The method takes a X12 file and converts it into a X2 object. The X12 * class has methods to convert it into XML format as well as methods to * modify the contents. */ public EDI parse(File fileName) throws FormatException, IOException { final char[] buffer = new char[SIZE]; FileReader fr = new FileReader(fileName); int count = fr.read(buffer); String start = new String(buffer, 0, 3); fr.close(); if (count != SIZE) { throw new FormatException("The Interchange Control Header is not " + "the correct size expected: "+SIZE+" found: "+count); } if (!start.startsWith(START_TAG)){ throw new FormatException("The Interchange Control Header Segment element: "+START_TAG+" is missing"); } Context context = new Context(); context.setSegmentSeparator(buffer[POS_SEGMENT]); context.setElementSeparator(buffer[POS_ELEMENT]); context.setCompositeElementSeparator(buffer[POS_COMPOSITE_ELEMENT]); Scanner scanner = new Scanner(fileName); X12 x12 = scanSource(scanner, context); scanner.close(); return x12; } /** * private helper method * @param scanner - the scanner to use in scanning. * @param context - context for the scanner. * @return X12 object found by the scanner. */ private X12 scanSource(Scanner scanner, Context context) { Character segmentSeparator = context.getSegmentSeparator(); String quotedSegmentSeparator = Pattern.quote(segmentSeparator.toString()); scanner.useDelimiter(quotedSegmentSeparator + "\r\n|" + quotedSegmentSeparator + "\n|" + quotedSegmentSeparator); cfMarker = x12Cf; X12 x12 = new X12(context); loopMarker = x12; Loop loop = x12; while (scanner.hasNext()) { String line = scanner.next(); String[] tokens = line.split("\\" + context.getElementSeparator()); if (doesChildLoopMatch(cfMarker, tokens)) { loop = loop.addChild(cfMarker.getName()); loop.addSegment(line); } else if (doesParentLoopMatch(cfMarker, tokens, loop)) { loop = loopMarker.addChild(cfMarker.getName()); loop.addSegment(line); } else { loop.addSegment(line); } } return x12; } /** * The method takes a InputStream and converts it into a X2 object. The X12 * class has methods to convert it into XML format as well as methods to * modify the contents. * * @param source * InputStream * @return the X12 object * @throws FormatException if any. * @throws java.io.IOException if any. */ public EDI parse(InputStream source) throws FormatException, IOException { StringBuilder strBuffer = new StringBuilder(); char[] cbuf = new char[1024]; int length; Reader reader = new BufferedReader(new InputStreamReader(source)); while ((length = reader.read(cbuf)) != -1) { strBuffer.append(cbuf, 0, length); } String strSource = strBuffer.toString(); return parse(strSource); } /** * The method takes a X12 string and converts it into a X2 object. The X12 * class has methods to convert it into XML format as well as methods to * modify the contents. * * @param source * String * @return the X12 object * @throws FormatException if any. */ public EDI parse(String source) throws FormatException { if (source.length() < SIZE) { throw new FormatException(); } Context context = new Context(); context.setSegmentSeparator(source.charAt(POS_SEGMENT)); context.setElementSeparator(source.charAt(POS_ELEMENT)); context.setCompositeElementSeparator(source.charAt(POS_COMPOSITE_ELEMENT)); Scanner scanner = new Scanner(source); X12 x12 = scanSource(scanner, context); scanner.close(); return x12; } /** * Checks if the segment (or line read) matches to current loop * * @param cf * Cf * @param tokens * String[] represents the segment broken into elements * @return boolean */ private boolean doesLoopMatch(Cf cf, String[] tokens) { if (cf.getSegment().equals(tokens[0])) { if (null == cf.getSegmentQualPos()) { return true; } else { for (String qual : cf.getSegmentQuals()) { if (qual.equals(tokens[cf.getSegmentQualPos()])) { return true; } } } } return false; } /** * Checks if the segment (or line read) matches to any of the child loops * configuration. * * @param parent * Cf * @param tokens * String[] represents the segment broken into elements * @return boolean */ boolean doesChildLoopMatch(Cf parent, String[] tokens) { for (Cf cf : parent.childList()) { if (doesLoopMatch(cf, tokens)) { cfMarker = cf; return true; } } return false; } /** * Checks if the segment (or line read) matches the parent loop * configuration. * * @param child * Cf * @param tokens * String[] represents the segment broken into elements * @param loop * Loop * @return boolean */ private boolean doesParentLoopMatch(Cf child, String[] tokens, Loop loop) { Cf parent = child.getParent(); if (parent == null) return false; loopMarker = loop.getParent(); for (Cf cf : parent.childList()) { if (doesLoopMatch(cf, tokens)) { cfMarker = cf; return true; } } return doesParentLoopMatch(parent, tokens, loopMarker); } }
ryanco/x12-parser
src/main/java/com/yarsquidy/x12/X12Parser.java
Java
apache-2.0
7,028
#!/bin/sh ./fingerprints ethernet-bus-reconnect.csv ethernet-hub-reconnect.csv ethernet-hub.csv ethernet-switch.csv ethernet-twohosts.csv examples.csv multi.csv $*
StarStuffSteve/masters-research-project
Simulation/OMNeT++/inet/tests/fingerprint/runDefaultTests.sh
Shell
apache-2.0
164
package com.chenantao.autolayout.utils; import android.view.ViewGroup; /** * Created by Chenantao_gg on 2016/1/20. */ public class AutoLayoutGenerate { public static <T extends ViewGroup> T generate(Class<T> clazz, Class[] argumentTypes, Object[] arguments) { // Enhancer enhancer = new Enhancer(); // enhancer.setSuperclass(clazz); // CallbackFilter filter = new ConcreteClassCallbackFilter(); // Callback methodInterceptor = new ConcreteClassMethodInterceptor<T>((Context) arguments[0], // (AttributeSet) arguments[1]); // Callback noOp = NoOp.INSTANCE; // Callback[] callbacks = new Callback[]{methodInterceptor, noOp}; // enhancer.setCallbackFilter(filter); // enhancer.setCallbacks(callbacks); // T proxyObj = (T) enhancer.create(argumentTypes, arguments); // //对onMeasure方法以及generateLayoutParams进行拦截,其他方法不进行操作 // return proxyObj; return null; } // static class ConcreteClassMethodInterceptor<T extends ViewGroup> implements MethodInterceptor // { // private AutoLayoutHelper mHelper; // private Context mContext; // private AttributeSet mAttrs; // // public ConcreteClassMethodInterceptor(Context context, AttributeSet attrs) // { // mContext = context; // mAttrs = attrs; // } // // public Object intercept(Object obj, Method method, Object[] arg, MethodProxy proxy) // throws Throwable // { // if (mHelper == null) // { // mHelper = new AutoLayoutHelper((ViewGroup) obj); // } // System.out.println("Before:" + method); // if ("onMeasure".equals(method.getName())) // { // //在onMeasure之前adjustChild // if (!((ViewGroup) obj).isInEditMode()) // { // mHelper.adjustChildren(); // } // // } else if ("generateLayoutParams".equals(method.getName())) // { // ViewGroup parent = (ViewGroup) obj; // final T.LayoutParams layoutParams = (T.LayoutParams) Enhancer.create(T.LayoutParams // .class, new Class[]{ // AutoLayoutHelper.AutoLayoutParams.class}, // new MethodInterceptor() // { // public Object intercept(Object obj, Method method, Object[] args, // MethodProxy proxy) throws Throwable // { // if ("getAutoLayoutInfo".equals(method.getName())) // { // return AutoLayoutHelper.getAutoLayoutInfo(mContext, mAttrs); // } // return proxy.invoke(obj, args); // } // }); // return layoutParams; // } // Object object = proxy.invokeSuper(obj, arg); // System.out.println("After:" + method); // return object; // } // } // // static class ConcreteClassCallbackFilter implements CallbackFilter // { // public int accept(Method method) // { // if ("onMeasure".equals(method.getName())) // { // return 0;//Callback callbacks[0] // } else if ("generateLayoutParams".equals(method.getName())) // { // return 0; // } // return 1; // } // } // static class LayoutParamsGenerate implements FixedValue // { // public LayoutParamsGenerate(Context context, AttributeSet attributeSet) // { // } // // public Object loadObject() throws Exception // { // System.out.println("ConcreteClassFixedValue loadObject ..."); // Object object = 999; // return object; // } // } }
Chenantao/PlayTogether
AutoLayout/src/main/java/com/chenantao/autolayout/utils/AutoLayoutGenerate.java
Java
apache-2.0
3,353
# Copyright 2022 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from django.test.utils import override_settings from sis_provisioner.tests import ( fdao_pws_override, fdao_hrp_override, fdao_bridge_override) from sis_provisioner.tests.account_managers import set_uw_account user_file_name_override = override_settings( BRIDGE_IMPORT_USER_FILENAME="users") def set_db_records(): affiemp = set_uw_account("affiemp") javerage = set_uw_account("javerage") ellen = set_uw_account("ellen") staff = set_uw_account("staff") staff.set_disable() retiree = set_uw_account("retiree") tyler = set_uw_account("faculty") leftuw = set_uw_account("leftuw") leftuw.set_terminate_date() testid = set_uw_account("testid")
uw-it-aca/bridge-sis-provisioner
sis_provisioner/tests/csv/__init__.py
Python
apache-2.0
784
package com.petercipov.mobi.deployer; import com.petercipov.mobi.Instance; import com.petercipov.traces.api.Trace; import java.util.Optional; import rx.Observable; /** * * @author Peter Cipov */ public abstract class RxDeployment { protected Optional<String> name; public RxDeployment() { this.name = Optional.empty(); } public Optional<String> name() { return name; } /** * Sets container name * @since 1.14 * @param name * @return */ public RxDeployment setName(String name) { this.name = Optional.of(name); return this; } /** * Adds volume bindings to container as string in format /host/path:/container/path * @since 1.14 * @param volumeBindings iterable of bindings * @return */ public abstract RxDeployment addVolumes(Iterable<String> volumeBindings); /** * Adds volume binding * @since 1.14 * @param hostPath * @param containerPath * @return */ public abstract RxDeployment addVolume(String hostPath, String containerPath); /** * Adds environment variable to container * @since 1.14 * @param variable variable in a format NAME=VALUE * @return */ public abstract RxDeployment addEnv(String variable); /** * Adds environment variable to container * @since 1.14 * @param name * @param value * @return */ public abstract RxDeployment addEnv(String name, String value); /** * Add port that should be published * @since 1.14 * @param port - container port spect in format [tcp/udp]/port. f.e tcp/8080 * @param customPort - remapping port * @return */ public abstract RxDeployment addPortMapping(String port, int customPort); /** * Publishes all exposed ports if is set to true * @since 1.14 * @param publish * @return */ public abstract RxDeployment setPublishAllPorts(boolean publish); /** * Publishes all exposed ports * @since 1.14 * @return */ public abstract RxDeployment publishAllPorts(); /** * Runs the command when starting the container * @since 1.14 * @param cmd - command in for of single string or multitude of string that * contains parts of command * @return */ public abstract RxDeployment setCmd(String ... cmd); /** * Sets cpu quota * @since 1.19 * @param quota Microseconds of CPU time that the container can get in a CPU period * @return */ public abstract RxDeployment setCpuQuota(long quota); /** * Sets cpu shares * @since 1.14 * @param shares An integer value containing the container’s CPU Shares (ie. the relative weight vs other containers) * @return */ public abstract RxDeployment setCpuShares(long shares); /** * Sets domain name * @since 1.14 * @param name A string value containing the domain name to use for the container. * @return */ public abstract RxDeployment setDomainName(String name); /** * Sets entry point * @since 1.15 * @param entry A command to run inside container. it overrides one specified by container docker file. * @return */ public abstract RxDeployment setEntryPoint(String ... entry); /** * adds container exposed port * @since 1.14 * @param port in format [tcp/udp]/port. f.e tcp/8080 * @return */ public abstract RxDeployment addExposedPort(String port); /** * Sets hostname * @since 1.14 * @param hostName A string value containing the hostname to use for the container. * @return */ public abstract RxDeployment setHostName(String hostName); /** * Adds label * @since 1.18 * @param key * @param value * @return */ public abstract RxDeployment addLabel(String key, String value); /** * Sets MAC address. * @since 1.15 * @param mac * @return */ public abstract RxDeployment setMacAdress(String mac); /** * Sets memory limits * @since 1.14 * @param memory Memory limit in bytes * @return */ public abstract RxDeployment setMemory(long memory); /** * Sets memory limit * @since 1.14 * @param memory Memory limit in bytes * @param swap Memory limit for swap. Set -1 to disable swap. * @return */ public abstract RxDeployment setMemory(long memory, long swap); /** * Disables networking for the container * @since 1.14 * @param disabled * @return */ public abstract RxDeployment setNetworkDisabled(boolean disabled); /** * Opens stdin * @since 1.14 * @param open * @return */ public abstract RxDeployment setOpenStdIn(boolean open); /** * Opens stdin and closes stdin after the 1. attached client disconnects. * @since 1.14 * @param once * @return */ public abstract RxDeployment setStdInOnce(boolean once); /** * Attaches standard streams to a tty, including stdin if it is not closed. * @since 1.14 * @param enabled * @return */ public abstract RxDeployment setTty(boolean enabled); /** * @since 1.14 * @param user A string value specifying the user inside the containe * @return */ public abstract RxDeployment setUser(String user); /** * @since 1.14 * @param workDir A string specifying the working directory for commands to run in. * @return */ public abstract RxDeployment setWorkDir(String workDir); /** * Sets path to cgroup * @since 1.18 * @param parent Path to cgroups under which the cgroup for the container will be created. If the path is not absolute, the path is considered to be relative to the cgroups path of the init process. Cgroups will be created if they do not already exist * @return */ public abstract RxDeployment setCgroupParent(String parent); /** * Adds DNS for fontainer * @since 1.14 * @param dns A list of DNS servers for the container to use * @return */ public abstract RxDeployment addDns(String ... dns); /** * Adds DNS search domains * @since 1.15 * @param dns A list of DNS servers for the container to use. * @return */ public abstract RxDeployment addDnsSearch(String ... dns); /** * Adds extra hosts co container /etc/hosts * @since 1.15 * @param hosts A list of hostnames/IP mappings to add to the container’s /etc/hosts file. Specified in the form ["hostname:IP"] * @return */ public abstract RxDeployment addExtraHosts(String ... hosts); /** * Adds links to other containers * @since 1.14 * @param links A list of links for the container. Each link entry should be in the form of container_name:alias * @return */ public abstract RxDeployment addLinks(String ... links); /** * Sets LXC specific configurations. These configurations only work when using the lxc execution driver. * @since 1.14 * @param key * @param value * @return */ public abstract RxDeployment addLxcParameter(String key, String value); /** * Sets the networking mode for the container * @since 1.15 * @param mode Supported values are: bridge, host, and container:name|id * @return */ public abstract RxDeployment setNetworkMode(String mode); /** * Gives the container full access to the host. * @since 1.14 * @param privileged * @return */ public abstract RxDeployment setPrivileged(boolean privileged); /** * @since 1.15 * @param opts string value to customize labels for MLS systems, such as SELinux. * @return */ public abstract RxDeployment addSecurityOpt(String ... opts); /** * Adds volume from an other container * @since 1.14 * @param volumes volume to inherit from another container. Specified in the form container name:ro|rw * @return */ public abstract RxDeployment addVolumeFrom(String ... volumes); protected abstract Observable<String> createContainer(Trace trace, Instance image); }
petercipov/mobi
deployer/src/main/java/com/petercipov/mobi/deployer/RxDeployment.java
Java
apache-2.0
7,654
// // DFShortVideoMessageContent.h // MongoIM // // Created by Allen Zhong on 16/2/14. // Copyright © 2016年 MongoIM. All rights reserved. // #import "DFMediaMessageContent.h" #import <UIKit/UIKit.h> #import "DFVideoDecoder.h" @interface DFShortVideoMessageContent : DFMediaMessageContent @property (nonatomic, strong) UIImage *cover; @property (nonatomic, strong) NSString *url; @property (nonatomic, strong) NSString *filePath; @property (nonatomic, strong) DFVideoDecoder *decorder; @end
anyunzhong/MongoIM-iOS
MongoIM/MongoIM/Core/Model/Content/Media/DFShortVideoMessageContent.h
C
apache-2.0
504
/* * Copyright 2015 Torridity. * * 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 de.tor.tribes.ui.models; import de.tor.tribes.types.ext.Village; import de.tor.tribes.ui.wiz.ret.types.RETSourceElement; import java.util.LinkedList; import java.util.List; import javax.swing.table.AbstractTableModel; /** * * @author Torridity */ public class RETSourceTableModel extends AbstractTableModel { private String[] columnNames = new String[]{ "Herkunft" }; private Class[] types = new Class[]{ Village.class }; private final List<RETSourceElement> elements = new LinkedList<RETSourceElement>(); public RETSourceTableModel() { super(); } public void clear() { elements.clear(); fireTableDataChanged(); } public void addRow(RETSourceElement pVillage, boolean pValidate) { elements.add(pVillage); if (pValidate) { fireTableDataChanged(); } } @Override public int getRowCount() { if (elements == null) { return 0; } return elements.size(); } @Override public Class getColumnClass(int columnIndex) { return types[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { return false; } @Override public String getColumnName(int column) { return columnNames[column]; } public void removeRow(int row) { elements.remove(row); fireTableDataChanged(); } public RETSourceElement getRow(int row) { return elements.get(row); } @Override public Object getValueAt(int row, int column) { if (elements == null || elements.size() - 1 < row) { return null; } return elements.get(row).getVillage(); } @Override public int getColumnCount() { return columnNames.length; } }
Akeshihiro/dsworkbench
Core/src/main/java/de/tor/tribes/ui/models/RETSourceTableModel.java
Java
apache-2.0
2,442
package com.zk.web.interceptor; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.Ordered; import org.springframework.http.HttpStatus; import org.springframework.validation.BindException; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; public class CustomizedHandlerExceptionResolver implements HandlerExceptionResolver, Ordered { private static final Logger LOGGER = LoggerFactory.getLogger(CustomizedHandlerExceptionResolver.class); public int getOrder() { return Integer.MIN_VALUE; } public ModelAndView resolveException(HttpServletRequest aReq, HttpServletResponse aRes, Object aHandler, Exception exception) { if (aHandler instanceof HandlerMethod) { if (exception instanceof BindException) { return null; } } LOGGER.error(StringUtils.EMPTY, exception); ModelAndView mav = new ModelAndView("common/error"); String errorMsg = exception.getMessage(); aRes.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); if ("XMLHttpRequest".equals(aReq.getHeader("X-Requested-With"))) { try { aRes.setContentType("application/text; charset=utf-8"); PrintWriter writer = aRes.getWriter(); aRes.setStatus(HttpServletResponse.SC_FORBIDDEN); writer.print(errorMsg); writer.flush(); writer.close(); return null; } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } mav.addObject("errorMsg", errorMsg); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); exception.printStackTrace(pw); mav.addObject("stackTrace", sw.getBuffer().toString()); mav.addObject("exception", exception); return mav; } }
wqintel/zookeeper-web
src/main/java/com/zk/web/interceptor/CustomizedHandlerExceptionResolver.java
Java
apache-2.0
2,187
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.intelligentsia.dowsers.core.serializers.jackson; import java.io.IOException; import org.intelligentsia.dowsers.core.reflection.ClassInformation; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; /** * * ClassInformationDeserializer. * * @author <a href="mailto:[email protected]" >Jerome Guibert</a> */ public class ClassInformationDeserializer extends StdDeserializer<ClassInformation> { /** * serialVersionUID:long */ private static final long serialVersionUID = -6052449554113264932L; public ClassInformationDeserializer() { super(ClassInformation.class); } @Override public ClassInformation deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { String description = null; if (jp.hasCurrentToken()) { if (jp.getCurrentToken().equals(JsonToken.START_OBJECT)) { jp.nextValue(); description = jp.getText(); jp.nextToken(); } } return description != null ? ClassInformation.parse(description) : null; } }
geronimo-iia/dowsers
dowsers-core/src/main/java/org/intelligentsia/dowsers/core/serializers/jackson/ClassInformationDeserializer.java
Java
apache-2.0
2,180
package org.jboss.resteasy.reactive.server.vertx.test; import static org.junit.jupiter.api.Assertions.fail; import io.smallrye.common.annotation.Blocking; import io.smallrye.common.annotation.NonBlocking; import java.util.function.Supplier; import javax.enterprise.inject.spi.DeploymentException; import javax.ws.rs.Path; import org.jboss.resteasy.reactive.server.vertx.test.framework.ResteasyReactiveUnitTest; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class BothBlockingAndNonBlockingOnClassTest { @RegisterExtension static ResteasyReactiveUnitTest test = new ResteasyReactiveUnitTest() .setArchiveProducer(new Supplier<>() { @Override public JavaArchive get() { return ShrinkWrap.create(JavaArchive.class) .addClasses(Resource.class); } }).setExpectedException(DeploymentException.class); @Test public void test() { fail("Should never have been called"); } @Path("test") @Blocking @NonBlocking public static class Resource { @Path("hello") public String hello() { return "hello"; } } }
quarkusio/quarkus
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/BothBlockingAndNonBlockingOnClassTest.java
Java
apache-2.0
1,351
#ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double Pods_CommuneUITestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_CommuneUITestsVersionString[];
paulrevere4/commune
ios/Commune/Pods/Target Support Files/Pods-CommuneUITests/Pods-CommuneUITests-umbrella.h
C
apache-2.0
183
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="zh"> <head> <!-- Generated by javadoc (1.8.0_111) on Mon Oct 22 12:02:26 CST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>程序包 com.dtstack.jlogstash.format的使用 (hdfs 1.0.0 API)</title> <meta name="date" content="2018-10-22"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="\u7A0B\u5E8F\u5305 com.dtstack.jlogstash.format\u7684\u4F7F\u7528 (hdfs 1.0.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>您的浏览器已禁用 JavaScript。</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="跳过导航链接">跳过导航链接</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="导航"> <li><a href="../../../../overview-summary.html">概览</a></li> <li><a href="package-summary.html">程序包</a></li> <li>类</li> <li class="navBarCell1Rev">使用</li> <li><a href="package-tree.html">树</a></li> <li><a href="../../../../deprecated-list.html">已过时</a></li> <li><a href="../../../../index-all.html">索引</a></li> <li><a href="../../../../help-doc.html">帮助</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>上一个</li> <li>下一个</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/dtstack/jlogstash/format/package-use.html" target="_top">框架</a></li> <li><a href="package-use.html" target="_top">无框架</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">所有类</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="程序包的使用 com.dtstack.jlogstash.format" class="title">程序包的使用<br>com.dtstack.jlogstash.format</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="使用表, 列表程序包和解释"> <caption><span>使用<a href="../../../../com/dtstack/jlogstash/format/package-summary.html">com.dtstack.jlogstash.format</a>的程序包</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">程序包</th> <th class="colLast" scope="col">说明</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.dtstack.jlogstash.format">com.dtstack.jlogstash.format</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#com.dtstack.jlogstash.format.plugin">com.dtstack.jlogstash.format.plugin</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#com.dtstack.jlogstash.outputs">com.dtstack.jlogstash.outputs</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.dtstack.jlogstash.format"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="使用表, 列表类和解释"> <caption><span><a href="../../../../com/dtstack/jlogstash/format/package-summary.html">com.dtstack.jlogstash.format</a>使用的<a href="../../../../com/dtstack/jlogstash/format/package-summary.html">com.dtstack.jlogstash.format</a>中的类</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">类和说明</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../com/dtstack/jlogstash/format/class-use/CompressEnum.html#com.dtstack.jlogstash.format">CompressEnum</a>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../com/dtstack/jlogstash/format/class-use/ModeEnum.html#com.dtstack.jlogstash.format">ModeEnum</a>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../com/dtstack/jlogstash/format/class-use/OutputFormat.html#com.dtstack.jlogstash.format">OutputFormat</a>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../com/dtstack/jlogstash/format/class-use/StoreEnum.html#com.dtstack.jlogstash.format">StoreEnum</a>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.dtstack.jlogstash.format.plugin"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="使用表, 列表类和解释"> <caption><span><a href="../../../../com/dtstack/jlogstash/format/plugin/package-summary.html">com.dtstack.jlogstash.format.plugin</a>使用的<a href="../../../../com/dtstack/jlogstash/format/package-summary.html">com.dtstack.jlogstash.format</a>中的类</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">类和说明</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../com/dtstack/jlogstash/format/class-use/HdfsOutputFormat.html#com.dtstack.jlogstash.format.plugin">HdfsOutputFormat</a>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../com/dtstack/jlogstash/format/class-use/OutputFormat.html#com.dtstack.jlogstash.format.plugin">OutputFormat</a>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.dtstack.jlogstash.outputs"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="使用表, 列表类和解释"> <caption><span><a href="../../../../com/dtstack/jlogstash/outputs/package-summary.html">com.dtstack.jlogstash.outputs</a>使用的<a href="../../../../com/dtstack/jlogstash/format/package-summary.html">com.dtstack.jlogstash.format</a>中的类</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">类和说明</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../com/dtstack/jlogstash/format/class-use/HdfsOutputFormat.html#com.dtstack.jlogstash.outputs">HdfsOutputFormat</a>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="跳过导航链接">跳过导航链接</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="导航"> <li><a href="../../../../overview-summary.html">概览</a></li> <li><a href="package-summary.html">程序包</a></li> <li>类</li> <li class="navBarCell1Rev">使用</li> <li><a href="package-tree.html">树</a></li> <li><a href="../../../../deprecated-list.html">已过时</a></li> <li><a href="../../../../index-all.html">索引</a></li> <li><a href="../../../../help-doc.html">帮助</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>上一个</li> <li>下一个</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/dtstack/jlogstash/format/package-use.html" target="_top">框架</a></li> <li><a href="package-use.html" target="_top">无框架</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">所有类</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2018. All rights reserved.</small></p> </body> </html>
DTStack/jlogstash
pipeline/outputs/hdfs/jlogstash-java-docs/com/dtstack/jlogstash/format/package-use.html
HTML
apache-2.0
8,214
/* * * * * Copyright (C) 2015 Orange * * 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.orange.servicebroker.staticcreds.stories.support_route_services; import com.orange.servicebroker.staticcreds.domain.PlanProperties; import com.orange.servicebroker.staticcreds.domain.ServiceBrokerProperties; import com.orange.servicebroker.staticcreds.domain.ServiceProperties; import com.tngtech.jgiven.junit.SimpleScenarioTest; import org.junit.Test; import org.springframework.cloud.servicebroker.model.ServiceDefinitionRequires; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * @author Sebastien Bortolussi */ @AddRouteService @Issue_32 public class ConfigureServiceBrokerWithRouteServiceTest extends SimpleScenarioTest<ConfigureServiceBrokerStage> { private static ServiceBrokerProperties service_broker_properties_with_route_service_url_at_service_level_and_requires_field_set() { PlanProperties dev = new PlanProperties("dev"); dev.setId("dev-id"); dev.setCredentials(uriCredentials()); ServiceProperties myServiceProperties = new ServiceProperties(); myServiceProperties.setName("myservice"); myServiceProperties.setId("myservice-id"); myServiceProperties.setRequires(Arrays.asList(ServiceDefinitionRequires.SERVICE_REQUIRES_ROUTE_FORWARDING.toString())); myServiceProperties.setRouteServiceUrl("https://myloggingservice.org/path"); final Map<String, PlanProperties> myServicePlans = new HashMap<>(); myServicePlans.put("dev", dev); myServiceProperties.setPlans(myServicePlans); final Map<String, ServiceProperties> services = new HashMap<>(); services.put("myservice", myServiceProperties); return new ServiceBrokerProperties(services); } private static Map<String, Object> uriCredentials() { Map<String, Object> credentials = new HashMap<>(); credentials.put("URI", "http://my-api.org"); return credentials; } private static ServiceBrokerProperties service_broker_properties_with_route_service_url_at_service_plan_level_and_requires_field_set() { PlanProperties dev = new PlanProperties("dev"); dev.setId("dev-id"); dev.setCredentials(uriCredentials()); dev.setRouteServiceUrl("https://myloggingservice.org/path"); ServiceProperties myServiceProperties = new ServiceProperties(); myServiceProperties.setName("myservice"); myServiceProperties.setId("myservice-id"); myServiceProperties.setRequires(Arrays.asList(ServiceDefinitionRequires.SERVICE_REQUIRES_ROUTE_FORWARDING.toString())); final Map<String, PlanProperties> myServicePlans = new HashMap<>(); myServicePlans.put("dev", dev); myServiceProperties.setPlans(myServicePlans); final Map<String, ServiceProperties> services = new HashMap<>(); services.put("myservice", myServiceProperties); return new ServiceBrokerProperties(services); } private static ServiceBrokerProperties catalog_with_route_service_url_at_service_level_but_without_requires_field_set() { PlanProperties dev = new PlanProperties("dev"); dev.setId("dev-id"); dev.setCredentials(uriCredentials()); ServiceProperties myServiceProperties = new ServiceProperties(); myServiceProperties.setName("myservice"); myServiceProperties.setId("myservice-id"); myServiceProperties.setRouteServiceUrl("https://myloggingservice.org/path"); final Map<String, PlanProperties> myServicePlans = new HashMap<>(); myServicePlans.put("dev", dev); myServiceProperties.setPlans(myServicePlans); final Map<String, ServiceProperties> services = new HashMap<>(); services.put("myservice", myServiceProperties); return new ServiceBrokerProperties(services); } private static ServiceBrokerProperties service_broker_properties_with_route_service_url_at_service_plan_level_but_without_requires_field_set() { PlanProperties dev = new PlanProperties("dev"); dev.setId("dev-id"); dev.setCredentials(uriCredentials()); dev.setRouteServiceUrl("https://myloggingservice.org/path"); ServiceProperties myServiceProperties = new ServiceProperties(); myServiceProperties.setName("myservice"); myServiceProperties.setId("myservice-id"); final Map<String, PlanProperties> myServicePlans = new HashMap<>(); myServicePlans.put("dev", dev); myServiceProperties.setPlans(myServicePlans); final Map<String, ServiceProperties> services = new HashMap<>(); services.put("myservice", myServiceProperties); return new ServiceBrokerProperties(services); } @Test public void configure_service_broker_with_same_route_service_url_for_all_service_plans_and_requires_field_set() throws Exception { when().paas_ops_configures_service_broker_with_following_config(service_broker_properties_with_route_service_url_at_service_level_and_requires_field_set()); then().it_should_succeed(); } @Test public void configure_service_broker_with_same_route_service_url_for_all_service_plans_but_omits_requires_field() throws Exception { when().paas_ops_configures_service_broker_with_following_config(catalog_with_route_service_url_at_service_level_but_without_requires_field_set()); then().it_should_fail(); } @Test public void configure_service_broker_with_route_service_url_set_for_a_service_plan_and_requires_field_set() throws Exception { when().paas_ops_configures_service_broker_with_following_config(service_broker_properties_with_route_service_url_at_service_plan_level_and_requires_field_set()); then().it_should_succeed(); } @Test public void configure_service_broker_with_route_service_url_set_for_a_service_plan_but_omits_requires_field() throws Exception { when().paas_ops_configures_service_broker_with_following_config(service_broker_properties_with_route_service_url_at_service_plan_level_but_without_requires_field_set()); then().it_should_fail(); } }
Orange-OpenSource/static-creds-broker
src/test/java/com/orange/servicebroker/staticcreds/stories/support_route_services/ConfigureServiceBrokerWithRouteServiceTest.java
Java
apache-2.0
6,730
# Parodia elata F.H.Brandt SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Parodia/Parodia elata/README.md
Markdown
apache-2.0
174
/* * Copyright 2018 Sebastien Callier * * 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 sebastien.callier.serialization.codec.extendable.object.field.primitives; import sebastien.callier.serialization.codec.Codec; import sebastien.callier.serialization.codec.extendable.object.field.FieldCodec; import sebastien.callier.serialization.codec.extendable.object.field.LambdaMetaFactoryUtils; import sebastien.callier.serialization.deserializer.InputStreamWrapper; import sebastien.callier.serialization.exceptions.CodecGenerationException; import sebastien.callier.serialization.serializer.OutputStreamWrapper; import java.io.IOException; import java.lang.reflect.Method; /** * @author Sebastien Callier * @since 2018 */ public class ByteFieldCodec implements FieldCodec { private final Getter get; private final Setter set; private final Codec codec; public ByteFieldCodec( Method getter, Method setter, Codec codec) throws CodecGenerationException { super(); get = LambdaMetaFactoryUtils.wrapGetter(Getter.class, getter, byte.class); set = LambdaMetaFactoryUtils.wrapSetter(Setter.class, setter, byte.class); this.codec = codec; } @FunctionalInterface public interface Getter { byte get(Object instance); } @FunctionalInterface public interface Setter { void set(Object instance, byte value); } @Override @SuppressWarnings("unchecked") public void write(OutputStreamWrapper wrapper, Object instance) throws IOException { codec.write(wrapper, get.get(instance)); } @Override @SuppressWarnings("unchecked") public void read(InputStreamWrapper wrapper, Object instance) throws IOException { set.set(instance, (Byte) codec.read(wrapper)); } }
S-Callier/serialization
src/main/java/sebastien/callier/serialization/codec/extendable/object/field/primitives/ByteFieldCodec.java
Java
apache-2.0
2,341
import eventlet import gettext import sys from staccato.common import config import staccato.openstack.common.wsgi as os_wsgi import staccato.openstack.common.pastedeploy as os_pastedeploy # Monkey patch socket and time eventlet.patcher.monkey_patch(all=False, socket=True, time=True) gettext.install('staccato', unicode=1) def fail(returncode, e): sys.stderr.write("ERROR: %s\n" % e) sys.exit(returncode) def main(): try: conf = config.get_config_object() paste_file = conf.find_file(conf.paste_deploy.config_file) wsgi_app = os_pastedeploy.paste_deploy_app(paste_file, 'staccato-api', conf) server = os_wsgi.Service(wsgi_app, conf.bind_port) server.start() server.wait() except RuntimeError as e: fail(1, e) main()
buzztroll/staccato
staccato/cmd/api.py
Python
apache-2.0
899
<?php exec('"' . __DIR__ . '/vendor/bin/phinx" rollback -t=0'); exec('"' . __DIR__ . '/vendor/bin/phinx" migrate'); exec('"' . __DIR__ . '/vendor/bin/phinx" seed:run'); ?>
Manoel-Matias-bls/son-financas
migrate_seed.php
PHP
apache-2.0
172
using System; using System.Drawing; using NetTopologySuite.Geometries; namespace SharpMap { /// <summary> /// Utility class that checks Viewport min/max Zoom and constraint /// </summary> [Serializable] public class MapViewPortGuard { private double _minimumZoom; private double _maximumZoom; private Envelope _maximumExtents; private double _pixelAspectRatio; const double MinMinZoomValue = 2d * Double.Epsilon; /// <summary> /// Gets or sets a value indicating the minimum zoom level. /// </summary> public double MinimumZoom { get { return _minimumZoom; } set { if (value < MinMinZoomValue) value = MinMinZoomValue; _minimumZoom = value; } } /// <summary> /// Gets or sets a value indicating the maximum zoom level. /// </summary> public double MaximumZoom { get { return _maximumZoom; } set { if (value < _minimumZoom) value = _minimumZoom; _maximumZoom = value; } } /// <summary> /// Gets or sets a value indicating the maximum extents /// </summary> public Envelope MaximumExtents { get { return _maximumExtents ?? (_maximumExtents = new Envelope()); } set { _maximumExtents = value; } } /// <summary> /// Gets or sets the size of the Map in device units (Pixel) /// </summary> public Size Size { get; set; } /// <summary> /// Gets or sets the aspect-ratio of the pixel scales. A value less than /// 1 will make the map streach upwards, and larger than 1 will make it smaller. /// </summary> /// <exception cref="ArgumentException">Throws an argument exception when value is 0 or less.</exception> public double PixelAspectRatio { get { return _pixelAspectRatio; } set { if (value <= 0) throw new ArgumentException("Invalid Pixel Aspect Ratio"); _pixelAspectRatio = value; } } /// <summary> /// Creates an instance of this class /// </summary> internal MapViewPortGuard(Size size, double minZoom, double maxZoom) { Size = size; MinimumZoom = minZoom; MaximumZoom = maxZoom; PixelAspectRatio = 1d; } /// <summary> /// Gets or sets a value indicating if <see cref="Map.MaximumExtents"/> should be enforced or not. /// </summary> public bool EnforceMaximumExtents { get; set; } /// <summary> /// Verifies the zoom level and center of the map /// </summary> /// <param name="zoom">The zoom level to test</param> /// <param name="center">The center of the map. This coordinate might change so you <b>must</b> provide a copy if you want to preserve the old value</param> /// <returns>The zoom level, might have changed</returns> public double VerifyZoom(double zoom, Coordinate center) { // Zoom within valid region if (zoom < _minimumZoom) zoom = _minimumZoom; else if (zoom > _maximumZoom) zoom = _maximumZoom; if (EnforceMaximumExtents) { var arWidth = (double) Size.Width/Size.Height; if (zoom > _maximumExtents.Width) zoom = _maximumExtents.Width; if (zoom > arWidth * _maximumExtents.Height) zoom = arWidth * _maximumExtents.Height; zoom = VerifyValidViewport(zoom, center); } return zoom; } /// <summary> /// Verifies the valid viewport, makes adjustments if required /// </summary> /// <param name="zoom">The current zoom</param> /// <param name="center">The </param> /// <returns>The verified zoom level</returns> private double VerifyValidViewport(double zoom, Coordinate center) { var maxExtents = MaximumExtents ?? new Envelope(); if (maxExtents.IsNull) return zoom; var halfWidth = 0.5d * zoom; var halfHeight = halfWidth * PixelAspectRatio * ((double)Size.Height / Size.Width); var maxZoomHeight = _maximumZoom < double.MaxValue ? _maximumZoom : double.MaxValue; if (2 * halfHeight > maxZoomHeight) { halfHeight = 0.5d*maxZoomHeight; halfWidth = halfHeight / (_pixelAspectRatio * ((double)Size.Height / Size.Width)); zoom = 2 * halfWidth; } var testEnvelope = new Envelope(center.X - halfWidth, center.X + halfWidth, center.Y - halfHeight, center.Y + halfHeight); if (maxExtents.Contains(testEnvelope)) return zoom; var dx = testEnvelope.MinX < maxExtents.MinX ? maxExtents.MinX - testEnvelope.MinX : testEnvelope.MaxX > maxExtents.MaxX ? maxExtents.MaxX - testEnvelope.MaxX : 0; var dy = testEnvelope.MinY < maxExtents.MinY ? maxExtents.MinY - testEnvelope.MinY : testEnvelope.MaxY > maxExtents.MaxY ? maxExtents.MaxY - testEnvelope.MaxY : 0; center.X += dx; center.Y += dy; return zoom; } } /// <summary> /// Utility class to lock a map's viewport so it cannot be changed /// </summary> public class MapViewportLock { private readonly Map _map; private double _minimumZoom; private double _maximumZoom; private Envelope _maximumExtents; private bool _enforce; /// <summary> /// Creates an instance of this class /// </summary> /// <param name="map"></param> public MapViewportLock(Map map) { _map = map; } /// <summary> /// Lock the viewport of the map /// </summary> public void Lock() { if (IsLocked) return; // Signal the viewport as locked IsLocked = true; // store the current extent settings _minimumZoom = _map.MinimumZoom; _maximumZoom = _map.MaximumZoom; _maximumExtents = _map.MaximumExtents; _enforce = _map.EnforceMaximumExtents; // Lock the viewport _map.MinimumZoom = _map.MaximumZoom = _map.Zoom; _map.MaximumExtents = _map.Envelope; _map.EnforceMaximumExtents = true; } /// <summary> /// Gets a value indicating that the map's viewport is locked /// </summary> public bool IsLocked { get; private set; } /// <summary> /// Unlock the viewport of the map /// </summary> public void Unlock() { // Unlock the viewport _map.EnforceMaximumExtents = _enforce; _map.MaximumExtents = _maximumExtents; _map.MinimumZoom = _minimumZoom; _map.MaximumZoom = _maximumZoom; // Signal the viewport as unlocked IsLocked = false; } } }
ShammyLevva/FTAnalyzer
SharpMap/Map/MapViewportGuard.cs
C#
apache-2.0
7,759
// // Copyright 2011 ODIN Working Group. 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. // #import <Foundation/Foundation.h> NSString * MCMODIN1();
MyMalcom/malcom-lib-ios
Libraries/source/lib/External/ODIN/MCMODIN.h
C
apache-2.0
683
/* * Copyright 2010-2015 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #include <aws/ec2/model/DescribeNetworkInterfacesResponse.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/logging/LogMacros.h> #include <utility> using namespace Aws::EC2::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils::Logging; using namespace Aws::Utils; using namespace Aws; DescribeNetworkInterfacesResponse::DescribeNetworkInterfacesResponse() { } DescribeNetworkInterfacesResponse::DescribeNetworkInterfacesResponse(const AmazonWebServiceResult<XmlDocument>& result) { *this = result; } DescribeNetworkInterfacesResponse& DescribeNetworkInterfacesResponse::operator =(const AmazonWebServiceResult<XmlDocument>& result) { const XmlDocument& xmlDocument = result.GetPayload(); XmlNode rootNode = xmlDocument.GetRootElement(); XmlNode resultNode = rootNode; if (rootNode.GetName() != "DescribeNetworkInterfacesResponse") { resultNode = rootNode.FirstChild("DescribeNetworkInterfacesResponse"); } if(!resultNode.IsNull()) { XmlNode networkInterfacesNode = resultNode.FirstChild("networkInterfaceSet"); if(!networkInterfacesNode.IsNull()) { XmlNode networkInterfacesMember = networkInterfacesNode.FirstChild("item"); while(!networkInterfacesMember.IsNull()) { m_networkInterfaces.push_back(networkInterfacesMember); networkInterfacesMember = networkInterfacesMember.NextNode("item"); } } } XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); m_responseMetadata = responseMetadataNode; AWS_LOGSTREAM_DEBUG("Aws::EC2::Model::DescribeNetworkInterfacesResponse", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); return *this; }
kahkeng/aws-sdk-cpp
aws-cpp-sdk-ec2/source/model/DescribeNetworkInterfacesResponse.cpp
C++
apache-2.0
2,358
package com.noeasy.money.exception; public class UserErrorMetadata extends BaseErrorMetadata { public static final UserErrorMetadata USER_EXIST = new UserErrorMetadata(101, "User exit"); public static final UserErrorMetadata NULL_USER_BEAN = new UserErrorMetadata(102, "Userbean is null"); protected UserErrorMetadata(int pErrorCode, String pErrorMesage) { super(pErrorCode, pErrorMesage); } }
DormitoryTeam/Dormitory
src/main/java/com/noeasy/money/exception/UserErrorMetadata.java
Java
apache-2.0
428
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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. * */ NamingPeopleContentManager = function() { this.SaveSchema = function(parentCallback) { var schemaId = jq('#namingPeopleSchema').val(); if (schemaId == 'custom') { NamingPeopleContentController.SaveCustomNamingSettings(jq('#usrcaption').val().substring(0, 30), jq('#usrscaption').val().substring(0, 30), jq('#grpcaption').val().substring(0, 30), jq('#grpscaption').val().substring(0, 30), jq('#usrstatuscaption').val().substring(0, 30), jq('#regdatecaption').val().substring(0, 30), jq('#grpheadcaption').val().substring(0, 30), jq('#guestcaption').val().substring(0, 30), jq('#guestscaption').val().substring(0, 30), function(result) { if (parentCallback != null) parentCallback(result.value); }); } else NamingPeopleContentController.SaveNamingSettings(schemaId, function(result) { if (parentCallback != null) parentCallback(result.value); }); } this.SaveSchemaCallback = function(res) { } this.LoadSchemaNames = function(parentCallback) { var schemaId = jq('#namingPeopleSchema').val(); NamingPeopleContentController.GetPeopleNames(schemaId, function(res) { var names = res.value; jq('#usrcaption').val(names.UserCaption); jq('#usrscaption').val(names.UsersCaption); jq('#grpcaption').val(names.GroupCaption); jq('#grpscaption').val(names.GroupsCaption); jq('#usrstatuscaption').val(names.UserPostCaption); jq('#regdatecaption').val(names.RegDateCaption); jq('#grpheadcaption').val(names.GroupHeadCaption); jq('#guestcaption').val(names.GuestCaption); jq('#guestscaption').val(names.GuestsCaption); if (parentCallback != null) parentCallback(res.value); }); } } NamingPeopleContentViewer = new function() { this.ChangeValue = function(event) { jq('#namingPeopleSchema').val('custom'); } }; jq(document).ready(function() { jq('.namingPeopleBox input[type="text"]').each(function(i, el) { jq(el).keypress(function(event) { NamingPeopleContentViewer.ChangeValue(); }); }); var manager = new NamingPeopleContentManager(); jq('#namingPeopleSchema').change(function () { manager.LoadSchemaNames(null); }); manager.LoadSchemaNames(null); });
ONLYOFFICE/CommunityServer
web/studio/ASC.Web.Studio/UserControls/Management/NamingPeopleSettings/js/namingpeoplecontent.js
JavaScript
apache-2.0
3,300
#!/usr/bin/env python # Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx. from netmiko import ConnectHandler def main(): # Definition of routers rtr1 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': 'pyclass', 'password': '88newclass', } rtr2 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': 'pyclass', 'password': '88newclass', 'port': 8022, } srx = { 'device_type': 'juniper', 'ip': '50.76.53.27', 'username': 'pyclass', 'password': '88newclass', 'port': 9822, } # Create a list of all the routers. all_routers = [rtr1, rtr2, srx] # Loop through all the routers and show arp. for a_router in all_routers: net_connect = ConnectHandler(**a_router) output = net_connect.send_command("show arp") print "\n\n>>>>>>>>> Device {0} <<<<<<<<<".format(a_router['device_type']) print output print ">>>>>>>>> End <<<<<<<<<" if __name__ == "__main__": main()
dprzybyla/python-ansible
week4/netmiko_sh_arp.py
Python
apache-2.0
1,128
// Fill out your copyright notice in the Description page of Project Settings. #include "Projectile.h" // Sets default values AProjectile::AProjectile() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; ProjectileMovement = CreateDefaultSubobject<UProjectileMovementComponent>(FName("Projectile Movement")); ProjectileMovement->bAutoActivate = false; } // Called when the game starts or when spawned void AProjectile::BeginPlay() { Super::BeginPlay(); } // Called every frame void AProjectile::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void AProjectile::LaunchProjectile(float Speed) { ProjectileMovement->SetVelocityInLocalSpace(FVector::ForwardVector * Speed); ProjectileMovement->Activate(); }
Tacticalmint/04_BattleTank
BattleTank/Source/BattleTank/Private/Projectile.cpp
C++
apache-2.0
826
""" IO classes for Omnivor input file Copyright (C) 2013 DTU Wind Energy Author: Emmanuel Branlard Email: [email protected] Last revision: 25/11/2013 Namelist IO: badis functions to read and parse a fortran file into python dictonary and write it back to a file The parser was adapted from: fortran-namelist on code.google with the following info: __author__ = 'Stephane Chamberland ([email protected])' __version__ = '$Revision: 1.0 $'[11:-2] __date__ = '$Date: 2006/09/05 21:16:24 $' __copyright__ = 'Copyright (c) 2006 RPN' __license__ = 'LGPL' Recognizes files of the form: &namelistname opt1 = value1 ... / """ from __future__ import print_function from we_file_io import WEFileIO, TestWEFileIO import unittest import numpy as np import os.path as path import sys import re import tempfile import os __author__ = 'E. Branlard ' class FortranNamelistIO(WEFileIO): """ Fortran Namelist IO class Scan a Fortran Namelist file and put Section/Parameters into a dictionary Write the file back if needed. """ def _write(self): """ Write a file (overrided) """ with open(self.filename, 'w') as f: for nml in self.data : f.write('&'+nml+'\n') # Sorting dictionary data (in the same order as it was created, thanks to id) SortedList = sorted(self.data[nml].items(), key=lambda(k, v): v['id']) # for param in self.data[nml]: for param in map(lambda(k,v):k,SortedList): f.write(param+'='+','.join(self.data[nml][param]['val'])) if len(self.data[nml][param]['com']) >0: f.write(' !'+self.data[nml][param]['com']) f.write('\n') f.write('/\n') def _read(self): """ Read the file (overrided) """ with open(self.filename, 'r') as f: data = f.read() varname = r'\b[a-zA-Z][a-zA-Z0-9_]*\b' valueInt = re.compile(r'[+-]?[0-9]+') valueReal = re.compile(r'[+-]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)') valueNumber = re.compile(r'\b(([\+\-]?[0-9]+)?\.)?[0-9]*([eE][-+]?[0-9]+)?') valueBool = re.compile(r"(\.(true|false|t|f)\.)",re.I) valueTrue = re.compile(r"(\.(true|t)\.)",re.I) spaces = r'[\s\t]*' quote = re.compile(r"[\s\t]*[\'\"]") namelistname = re.compile(r"^[\s\t]*&(" + varname + r")[\s\t]*$") paramname = re.compile(r"[\s\t]*(" + varname+r')[\s\t]*=[\s\t]*') namlistend = re.compile(r"^" + spaces + r"/" + spaces + r"$") #split sections/namelists mynmlfile = {} mynmlfileRaw = {} mynmlname = '' for item in FortranNamelistIO.clean(data.split("\n"),cleancomma=1): if re.match(namelistname,item): mynmlname = re.sub(namelistname,r"\1",item) mynmlfile[mynmlname] = {} mynmlfileRaw[mynmlname] = [] elif re.match(namlistend,item): mynmlname = '' else: if mynmlname: mynmlfileRaw[mynmlname].append(item) #parse param in each section/namelist for mynmlname in mynmlfile.keys(): #split strings bb = [] for item in mynmlfileRaw[mynmlname]: if item[0]!='!': # discarding lines that starts with a comment bb.extend(FortranNamelistIO.splitstring(item)) #split comma and = aa = [] for item in bb: if not re.match(quote,item): aa.extend(re.sub(r"[\s\t]*=",r" =\n",re.sub(r",+",r"\n",item)).split("\n")) # aa.extend(re.sub(r"[\s\t]*=",r" =\n",item).split("\n")) else: aa.append(item) del(bb) aa = FortranNamelistIO.clean(aa,cleancomma=1) myparname = '' id_cum=0 for item in aa: if re.search(paramname,item): #myparname = re.sub(paramname,r"\1",item).lower() ! NO MORE LOWER CASE myparname = re.sub(paramname,r"\1",item) id_cum=id_cum+1 mynmlfile[mynmlname][myparname] = { 'val' : [], 'id' : id_cum, 'com' : '' } elif paramname: # Storing comments item2=item.split('!') item=item2[0] if len(item) > 1 : mynmlfile[mynmlname][myparname]['com']=''.join(item2[1:]) if re.match(valueBool,item): if re.match(valueTrue,item): mynmlfile[mynmlname][myparname]['val'].append('.true.') else: mynmlfile[mynmlname][myparname]['val'].append('.false.') else: # item2=re.sub(r"(^[\'\"]|[\'\"]$)",r"",item.strip()) mynmlfile[mynmlname][myparname]['val'].append(item.strip()) self.data=mynmlfile # Accessor and mutator dictionary style def __getitem__(self, key): """ Transform the class instance into a dictionary.""" return self.data[key] def __setitem__(self, key, value): """ Transform the class instance into a dictionary.""" self.data[key] = value #==== Helper functions for Parsing of files @staticmethod def clean(mystringlist,commentexpr=r"^[\s\t]*\#.*$",spacemerge=0,cleancomma=0): """ Remove leading and trailing blanks, comments/empty lines from a list of strings mystringlist = foo.clean(mystringlist,spacemerge=0,commentline=r"^[\s\t]*\#",cleancharlist="") commentline: definition of commentline spacemerge: if <>0, merge/collapse multi space cleancomma: Remove leading and trailing commas """ aa = mystringlist if cleancomma: aa = [re.sub("(^([\s\t]*\,)+)|((\,[\s\t]*)+$)","",item).strip() for item in aa] if commentexpr: aa = [re.sub(commentexpr,"",item).strip() for item in aa] if spacemerge: aa = [re.sub("[\s\t]+"," ",item).strip() for item in aa if len(item.strip()) <> 0] else: aa = [item.strip() for item in aa if len(item.strip()) <> 0] return aa @staticmethod def splitstring(mystr): """ Split a string in a list of strings at quote boundaries Input: String Output: list of strings """ dquote=r'(^[^\"\']*)(\"[^"]*\")(.*)$' squote=r"(^[^\"\']*)(\'[^']*\')(.*$)" mystrarr = re.sub(dquote,r"\1\n\2\n\3",re.sub(squote,r"\1\n\2\n\3",mystr)).split("\n") #remove zerolenght items mystrarr = [item for item in mystrarr if len(item) <> 0] if len(mystrarr) > 1: mystrarr2 = [] for item in mystrarr: mystrarr2.extend(FortranNamelistIO.splitstring(item)) mystrarr = mystrarr2 return mystrarr ## Do Some testing ------------------------------------------------------- class TestFortranNamelist(TestWEFileIO): """ Test class for MyFileType class """ test_file = './test/fortran/fortran_namelist.nml' def test_output_identical(self): InputFile=FortranNamelistIO(self.test_file) test_fileout=tempfile.mkstemp()[1] InputFile.write(test_fileout) with open(self.test_file, 'r') as f: data_expected = f.read() with open(test_fileout, 'r') as f: data_read = f.read() try: self.assertMultiLineEqual(data_read, data_expected) finally: os.remove(test_fileout) def test_duplication(self): self._test_duplication(FortranNamelistIO, self.test_file) ## Main function --------------------------------------------------------- if __name__ == '__main__': """ This is the main fuction that will run the tests automatically """ unittest.main()
DTUWindEnergy/Python4WindEnergy
py4we/fortran_namelist_io.py
Python
apache-2.0
8,294
/*! * Cube Portfolio - Responsive jQuery Grid Plugin * * version: 4.1.1-dev (6 April, 2017) * require: jQuery v1.7+ * * Copyright 2013-2017, Mihai Buricea (http://scriptpie.com/cubeportfolio/live-preview/) * Licensed under CodeCanyon License (http://codecanyon.net/licenses) * */ .cbp, .cbp *, .cbp-l-filters-alignCenter .cbp-filter-counter:after, .cbp-l-filters-alignRight .cbp-filter-counter:after, .cbp-l-filters-button .cbp-filter-counter:after, .cbp-l-filters-buttonCenter .cbp-filter-counter:after, .cbp-l-filters-dropdownHeader:after, .cbp-l-filters-text .cbp-filter-counter:after, .cbp-popup-loadingBox:after, .cbp-popup-wrap, .cbp-popup-wrap *, .cbp-popup-wrap:before, .cbp:after { box-sizing: border-box } .cbp-l-grid-agency-desc, .cbp-l-grid-agency-title, .cbp-l-grid-blog-title, .cbp-l-grid-masonry-projects-desc, .cbp-l-grid-masonry-projects-title, .cbp-l-grid-projects-desc, .cbp-l-grid-projects-title, .cbp-l-grid-work-desc, .cbp-l-grid-work-title { white-space: nowrap; overflow: hidden; text-overflow: ellipsis } .cbp-l-filters-alignCenter, .cbp-l-filters-alignCenter *, .cbp-l-filters-alignLeft, .cbp-l-filters-alignLeft *, .cbp-l-filters-alignRight, .cbp-l-filters-alignRight *, .cbp-l-filters-big, .cbp-l-filters-big *, .cbp-l-filters-button, .cbp-l-filters-button *, .cbp-l-filters-buttonCenter, .cbp-l-filters-buttonCenter *, .cbp-l-filters-dropdown, .cbp-l-filters-dropdown *, .cbp-l-filters-list, .cbp-l-filters-list *, .cbp-l-filters-text, .cbp-l-filters-text *, .cbp-l-filters-underline, .cbp-l-filters-underline *, .cbp-l-filters-work, .cbp-l-filters-work *, .cbp-l-loadMore-bgbutton, .cbp-l-loadMore-bgbutton *, .cbp-l-loadMore-button, .cbp-l-loadMore-button *, .cbp-l-loadMore-text, .cbp-l-loadMore-text *, .cbp-search, .cbp-search * { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-tap-highlight-color: transparent; box-sizing: border-box } .cbp-nav, .cbp-popup-close, .cbp-popup-next, .cbp-popup-prev { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none } .cbp-lazyload:after, .cbp-popup-loadingBox:after, .cbp-popup-singlePageInline:after, .cbp:after { content: ''; position: absolute; width: 34px; height: 34px; left: 0; right: 0; top: 0; bottom: 0; margin: auto; -webkit-animation: cbp-rotation .8s infinite linear; animation: cbp-rotation .8s infinite linear; border-left: 3px solid rgba(114, 144, 182, .15); border-right: 3px solid rgba(114, 144, 182, .15); border-bottom: 3px solid rgba(114, 144, 182, .15); border-top: 3px solid rgba(114, 144, 182, .8); border-radius: 100% } .cbp-l-filters-alignCenter .cbp-filter-item:hover .cbp-filter-counter, .cbp-l-filters-alignRight .cbp-filter-item:hover .cbp-filter-counter, .cbp-l-filters-buttonCenter .cbp-filter-item:hover .cbp-filter-counter, .cbp-l-filters-text .cbp-filter-item:hover .cbp-filter-counter { opacity: 1; -webkit-transform: translateY(-44px); transform: translateY(-44px) } .cbp-l-filters-alignCenter .cbp-filter-counter, .cbp-l-filters-alignRight .cbp-filter-counter, .cbp-l-filters-button .cbp-filter-counter, .cbp-l-filters-buttonCenter .cbp-filter-counter, .cbp-l-filters-text .cbp-filter-counter { font: 400 11px/18px "Open Sans Condensed", sans-serif; border-radius: 3px; color: #FFF; margin: 0 auto; padding: 4px 0; text-align: center; width: 34px; position: absolute; bottom: 0; left: 0; right: 0; opacity: 0; -webkit-transition: -webkit-transform .25s, opacity .25s; transition: transform .25s, opacity .25s } .cbp-l-filters-alignCenter .cbp-filter-counter:after, .cbp-l-filters-alignRight .cbp-filter-counter:after, .cbp-l-filters-button .cbp-filter-counter:after, .cbp-l-filters-buttonCenter .cbp-filter-counter:after, .cbp-l-filters-text .cbp-filter-counter:after { content: ""; position: absolute; bottom: -4px; left: 0; right: 0; margin: 0 auto; width: 0; height: 0; border-left: 4px solid transparent; border-right: 4px solid transparent } .cbp-item { display: inline-block; margin: 0 10px 20px 0 } .cbp { position: relative; margin: 0 auto; z-index: 1; height: 400px } .cbp>* { visibility: hidden } .cbp-popup-ready.cbp-popup-lightbox .cbp-popup-close, .cbp-popup-ready.cbp-popup-lightbox .cbp-popup-next, .cbp-popup-ready.cbp-popup-lightbox .cbp-popup-prev, .cbp-ready>* { visibility: visible } .cbp .cbp-item { list-style-type: none; margin: 0; padding: 0; overflow: hidden } .cbp img { display: block; border: 0; width: 100%; height: auto } .cbp a, .cbp a:active, .cbp a:hover { text-decoration: none; outline: 0 } .cbp-lazyload { position: relative; background: #fff; display: block } .cbp-lazyload img { opacity: 1 } .cbp-lazyload img[data-cbp-src] { opacity: 0 } .cbp-lazyload img:not([data-cbp-src]) { -webkit-transition: opacity .7s ease-in-out; transition: opacity .7s ease-in-out } .cbp-lazyload:after { z-index: 0 } .cbp-wrapper-outer { overflow: hidden; position: relative; margin: 0 auto } .cbp-wrapper, .cbp-wrapper-helper, .cbp-wrapper-outer { list-style-type: none; padding: 0; width: 100%; height: 100%; z-index: 1 } .cbp-wrapper, .cbp-wrapper-helper { margin: 0 } .cbp-item-off, .cbp-popup-lightbox .cbp-popup-close, .cbp-popup-lightbox .cbp-popup-next, .cbp-popup-lightbox .cbp-popup-prev, .cbp-ready:after { visibility: hidden } .cbp-ready:after { display: none } .cbp-ready .cbp-item, .cbp-ready .cbp-wrapper, .cbp-ready .cbp-wrapper-helper { position: absolute; top: 0; left: 0 } .cbp-item-off { z-index: -1; pointer-events: none } .cbp-item-on2off { z-index: 0 } .cbp-item-off2on { z-index: 1 } .cbp-item-on2on { z-index: 2 } .cbp-item-wrapper { width: 100%; height: 100%; position: relative; top: 0; left: 0 } .cbp-l-inline img, .cbp-l-project-related-wrap img { display: block; width: 100%; height: auto; border: 0 } .cbp-updateItems { -webkit-transition: height .5s ease-in-out!important; transition: height .5s ease-in-out!important; will-change: height } .cbp-updateItems .cbp-item { -webkit-transition: top .5s ease-in-out, left .5s ease-in-out; transition: top .5s ease-in-out, left .5s ease-in-out } .cbp-updateItems .cbp-item-loading { -webkit-animation: fadeIn .5s ease-in-out; animation: fadeIn .5s ease-in-out; -webkit-transition: none; transition: none } .cbp-removeItem { -webkit-animation: fadeOut .5s ease-in-out; animation: fadeOut .5s ease-in-out } .cbp-panel { width: 94%; max-width: 1170px; margin: 0 auto } .cbp-misc-video { position: relative; height: 0; padding-bottom: 56.25%; background: #000; text-align: center } .cbp-misc-video iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100% } @-webkit-keyframes cbp-rotation { 0% { -webkit-transform: rotate(0) } 100% { -webkit-transform: rotate(360deg) } } @keyframes cbp-rotation { 0% { transform: rotate(0) } 100% { transform: rotate(360deg) } } @-webkit-keyframes fadeOut { 0% { opacity: 1 } 100% { opacity: 0 } } @keyframes fadeOut { 0% { opacity: 1 } 100% { opacity: 0 } } .clearfix:after { content: " "; display: block; height: 0; clear: both } .cbp-l-filters-left { float: left } .cbp-l-filters-right { float: right } .cbp-caption, .cbp-caption-activeWrap, .cbp-caption-defaultWrap { display: block } .cbp-caption-activeWrap { background-color: #282727 } .cbp-caption-active .cbp-caption, .cbp-caption-active .cbp-caption-activeWrap, .cbp-caption-active .cbp-caption-defaultWrap { overflow: hidden; position: relative; z-index: 1 } .cbp-caption-active .cbp-caption-defaultWrap { top: 0 } .cbp-caption-active .cbp-caption-activeWrap { width: 100%; position: absolute; z-index: 2; height: 100% } .cbp-l-caption-title { color: #fff; font: 400 16px/21px "Open Sans Condensed", sans-serif } .cbp-l-caption-desc { color: #aaa; font: 400 12px/16px "Open Sans Condensed", sans-serif } .cbp-l-caption-text { font: 400 14px/21px "Open Sans Condensed", sans-serif; color: #fff; letter-spacing: 3px; padding: 0 6px } .cbp-l-caption-buttonLeft, .cbp-l-caption-buttonRight { background-color: #547EB1; color: #FFF; display: inline-block; font: 400 12px/30px "Open Sans Condensed", sans-serif; min-width: 90px; text-align: center; margin: 4px; padding: 0 6px } .cbp-l-caption-buttonLeft:hover, .cbp-l-caption-buttonRight:hover { opacity: .9 } .cbp-caption-none .cbp-caption-activeWrap { display: none } .cbp-l-caption-alignLeft .cbp-l-caption-body { padding: 12px 30px } .cbp-caption-fadeIn .cbp-l-caption-alignLeft .cbp-l-caption-body, .cbp-caption-minimal .cbp-l-caption-alignLeft .cbp-l-caption-body, .cbp-caption-moveRight .cbp-l-caption-alignLeft .cbp-l-caption-body, .cbp-caption-opacity .cbp-l-caption-alignLeft .cbp-l-caption-body, .cbp-caption-overlayRightAlong .cbp-l-caption-alignLeft .cbp-l-caption-body, .cbp-caption-pushDown .cbp-l-caption-alignLeft .cbp-l-caption-body, .cbp-caption-pushTop .cbp-l-caption-alignLeft .cbp-l-caption-body, .cbp-caption-revealBottom .cbp-l-caption-alignLeft .cbp-l-caption-body, .cbp-caption-revealLeft .cbp-l-caption-alignLeft .cbp-l-caption-body, .cbp-caption-revealTop .cbp-l-caption-alignLeft .cbp-l-caption-body, .cbp-caption-zoom .cbp-l-caption-alignLeft .cbp-l-caption-body { padding-top: 30px } .cbp-l-caption-alignCenter { display: table; width: 100%; height: 100% } .cbp-l-caption-alignCenter .cbp-l-caption-body { display: table-cell; vertical-align: middle; text-align: center; padding: 0 } .cbp-l-caption-alignCenter .cbp-l-caption-buttonLeft, .cbp-l-caption-alignCenter .cbp-l-caption-buttonRight { position: relative; -webkit-transition: -webkit-transform .25s; transition: transform .25s } .cbp-caption-overlayBottom .cbp-l-caption-alignCenter .cbp-l-caption-buttonLeft, .cbp-caption-overlayBottomAlong .cbp-l-caption-alignCenter .cbp-l-caption-buttonLeft, .cbp-caption-overlayBottomPush .cbp-l-caption-alignCenter .cbp-l-caption-buttonLeft { -webkit-transform: translateX(-20px); transform: translateX(-20px) } .cbp-caption-overlayBottom .cbp-l-caption-alignCenter .cbp-l-caption-buttonRight, .cbp-caption-overlayBottomAlong .cbp-l-caption-alignCenter .cbp-l-caption-buttonRight, .cbp-caption-overlayBottomPush .cbp-l-caption-alignCenter .cbp-l-caption-buttonRight { -webkit-transform: translateX(20px); transform: translateX(20px) } .cbp-caption:hover .cbp-l-caption-alignCenter .cbp-l-caption-buttonLeft, .cbp-caption:hover .cbp-l-caption-alignCenter .cbp-l-caption-buttonRight { -webkit-transform: translateX(0); transform: translateX(0) } @media only screen and (max-width:480px) { .cbp-l-filters-left, .cbp-l-filters-right { width: 100% } .cbp-l-caption-alignLeft .cbp-l-caption-body { padding: 9px 11px } .cbp-l-caption-title { font-size: 14px; line-height: 21px } .cbp-l-caption-desc { font-size: 11px; line-height: 14px } .cbp-l-caption-buttonLeft, .cbp-l-caption-buttonRight { font-size: 11px; line-height: 28px; min-width: 69px; margin: 3px; padding: 0 4px } .cbp-l-caption-text { font-size: 13px; letter-spacing: 1px } .cbp-l-filters-alignLeft { text-align: center } } @media only screen and (max-width:374px) { .cbp-l-caption-alignLeft .cbp-l-caption-body { padding: 8px 10px } .cbp-l-caption-title { font-size: 13px; line-height: 20px } .cbp-l-caption-desc { font-size: 11px; line-height: 14px } .cbp-l-caption-buttonLeft, .cbp-l-caption-buttonRight { font-size: 10px; line-height: 28px; min-width: 62px; margin: 1px; padding: 0 4px } } .cbp-caption-fadeIn .cbp-caption-activeWrap { opacity: 0; top: 0; background-color: rgba(0, 0, 0, .85); -webkit-transition: opacity .5s; transition: opacity .5s } .cbp-caption-fadeIn .cbp-caption:hover .cbp-caption-activeWrap { opacity: 1 } .cbp-caption-minimal .cbp-l-caption-desc, .cbp-caption-minimal .cbp-l-caption-title { position: relative; left: 0; opacity: 0; -webkit-transition: -webkit-transform .35s ease-out; transition: transform .35s ease-out } .cbp-caption-minimal .cbp-l-caption-title { -webkit-transform: translateY(-50%); transform: translateY(-50%) } .cbp-caption-minimal .cbp-l-caption-desc { -webkit-transform: translateY(70%); transform: translateY(70%) } .cbp-caption-minimal .cbp-caption:hover .cbp-l-caption-desc, .cbp-caption-minimal .cbp-caption:hover .cbp-l-caption-title { opacity: 1; -webkit-transform: translateY(0); transform: translateY(0) } .cbp-caption-minimal .cbp-caption-activeWrap { top: 0; background-color: #000; background-color: rgba(0, 0, 0, .8); opacity: 0 } .cbp-caption-minimal .cbp-caption:hover .cbp-caption-activeWrap { opacity: 1 } .cbp-caption-moveRight .cbp-caption-activeWrap { left: -100%; top: 0; -webkit-transition: -webkit-transform .35s; transition: transform .35s } .cbp-caption-moveRight .cbp-caption:hover .cbp-caption-activeWrap { -webkit-transform: translateX(100%); transform: translateX(100%) } .cbp-caption-overlayBottom .cbp-caption-activeWrap { height: 60px; background-color: #181616; background-color: rgba(24, 22, 22, .7); -webkit-transition: -webkit-transform .25s; transition: transform .25s } .cbp-caption-overlayBottom .cbp-caption:hover .cbp-caption-activeWrap { -webkit-transform: translateY(-100%); transform: translateY(-100%) } .cbp-caption-overlayBottomAlong .cbp-l-caption-alignCenter .cbp-l-caption-buttonLeft, .cbp-caption-overlayBottomAlong .cbp-l-caption-alignCenter .cbp-l-caption-buttonRight { -webkit-transition-duration: .35s; transition-duration: .35s } .cbp-caption-overlayBottomAlong .cbp-caption-activeWrap, .cbp-caption-overlayBottomAlong .cbp-caption-defaultWrap { -webkit-transition: -webkit-transform .35s; transition: transform .35s } .cbp-caption-overlayBottomAlong .cbp-caption-activeWrap { height: 60px } .cbp-caption-overlayBottomAlong .cbp-caption:hover .cbp-caption-defaultWrap { -webkit-transform: translateY(-30px); transform: translateY(-30px) } .cbp-caption-overlayBottomAlong .cbp-caption:hover .cbp-caption-activeWrap { -webkit-transform: translateY(-100%); transform: translateY(-100%) } .cbp-caption-overlayBottomPush .cbp-caption-activeWrap, .cbp-caption-overlayBottomPush .cbp-caption-defaultWrap { -webkit-transition: -webkit-transform .25s; transition: transform .25s } .cbp-caption-overlayBottomPush .cbp-caption-activeWrap { height: 61px; -webkit-transform: translateY(0); transform: translateY(0) } .cbp-caption-overlayBottomPush .cbp-caption:hover .cbp-caption-defaultWrap { -webkit-transform: translateY(-60px); transform: translateY(-60px) } .cbp-caption-overlayBottomPush .cbp-caption:hover .cbp-caption-activeWrap { -webkit-transform: translateY(-61px); transform: translateY(-61px) } .cbp-caption-overlayBottomReveal .cbp-caption-defaultWrap { z-index: 2; -webkit-transition: -webkit-transform .25s; transition: transform .25s } .cbp-caption-overlayBottomReveal .cbp-caption-activeWrap { bottom: 0; z-index: 1; height: 47px } .cbp-caption-overlayBottomReveal .cbp-caption:hover .cbp-caption-defaultWrap { -webkit-transform: translateY(-47px); transform: translateY(-47px) } .cbp-caption-overlayRightAlong .cbp-caption-activeWrap, .cbp-caption-overlayRightAlong .cbp-caption-defaultWrap { -webkit-transition: -webkit-transform .4s; transition: transform .4s } .cbp-caption-overlayRightAlong .cbp-caption-activeWrap { top: 0; left: -50%; width: 50% } .cbp-caption-overlayRightAlong .cbp-caption:hover .cbp-caption-defaultWrap { -webkit-transform: translateX(25%); transform: translateX(25%) } .cbp-caption-overlayRightAlong .cbp-caption:hover .cbp-caption-activeWrap { -webkit-transform: translateX(100%); transform: translateX(100%) } .cbp-caption-pushDown .cbp-caption-activeWrap, .cbp-caption-pushDown .cbp-caption-defaultWrap { -webkit-transition: -webkit-transform .4s; transition: transform .4s } .cbp-caption-pushDown .cbp-caption-activeWrap { top: -100% } .cbp-caption-pushDown .cbp-caption:hover .cbp-caption-activeWrap, .cbp-caption-pushDown .cbp-caption:hover .cbp-caption-defaultWrap { -webkit-transform: translateY(100%); transform: translateY(100%) } .cbp-caption-pushTop .cbp-caption-activeWrap, .cbp-caption-pushTop .cbp-caption-defaultWrap { -webkit-transition: -webkit-transform .4s; transition: transform .4s } .cbp-caption-pushTop .cbp-caption-activeWrap { height: 102% } .cbp-caption-pushTop .cbp-caption:hover .cbp-caption-defaultWrap { -webkit-transform: translateY(-100%); transform: translateY(-100%) } .cbp-caption-pushTop .cbp-caption:hover .cbp-caption-activeWrap { -webkit-transform: translateY(-99%); transform: translateY(-99%) } .cbp-caption-revealBottom .cbp-caption-defaultWrap { z-index: 2; -webkit-transition: -webkit-transform .4s; transition: transform .4s } .cbp-caption-revealBottom .cbp-caption-activeWrap { top: 0; z-index: 1 } .cbp-caption-revealBottom .cbp-caption:hover .cbp-caption-defaultWrap { -webkit-transform: translateY(-100%); transform: translateY(-100%) } .cbp-caption-revealLeft .cbp-caption-activeWrap { left: 100%; top: 0; -webkit-transition: -webkit-transform .4s; transition: transform .4s } .cbp-caption-revealLeft .cbp-caption:hover .cbp-caption-activeWrap { -webkit-transform: translateX(-100%); transform: translateX(-100%) } .cbp-caption-revealTop .cbp-caption-defaultWrap { z-index: 2; -webkit-transition: -webkit-transform .4s; transition: transform .4s } .cbp-caption-revealTop .cbp-caption-activeWrap { top: 0; z-index: 1 } .cbp-caption-revealTop .cbp-caption:hover .cbp-caption-defaultWrap { -webkit-transform: translateY(100%); transform: translateY(100%) } .cbp-caption-zoom .cbp-caption-defaultWrap { -webkit-transition: -webkit-transform .35s ease-out; transition: transform .35s ease-out } .cbp-caption-zoom .cbp-caption:hover .cbp-caption-defaultWrap { -webkit-transform: scale(1.25); transform: scale(1.25) } .cbp-caption-zoom .cbp-caption-activeWrap { opacity: 0; top: 0; background-color: rgba(0, 0, 0, .9); -webkit-transition: opacity .4s; transition: opacity .4s } .cbp-caption-zoom .cbp-caption:hover .cbp-caption-activeWrap { opacity: 1 } .cbp-caption-opacity .cbp-item { padding: 1px } .cbp-caption-opacity .cbp-caption, .cbp-caption-opacity .cbp-caption-activeWrap, .cbp-caption-opacity .cbp-caption-defaultWrap { background-color: transparent } .cbp-caption-opacity .cbp-caption { border: 1px solid transparent } .cbp-caption-opacity .cbp-caption:hover { border-color: #EDEDED } .cbp-caption-opacity .cbp-caption-defaultWrap { opacity: 1; -webkit-transition: opacity .4s; transition: opacity .4s } .cbp-caption-opacity .cbp-caption:hover .cbp-caption-defaultWrap { opacity: .8 } .cbp-caption-opacity .cbp-caption:hover .cbp-caption-activeWrap { top: 0 } .cbp-caption-expand .cbp-caption-activeWrap { height: auto; background-color: transparent } .cbp-caption-expand .cbp-caption { border-bottom: 1px dotted #eaeaea } .cbp-caption-expand .cbp-caption-defaultWrap { cursor: pointer; font: 500 16px/23px 'Open Sans Condensed', sans-serif; color: #474747; padding: 12px 0 11px 26px } .cbp-caption-expand .cbp-caption-defaultWrap svg { position: absolute; top: 16px; left: 0 } .cbp-l-caption-body a { font: 400 14px/21px 'Open Sans Condensed', sans-serif } .cbp-caption-expand .cbp-l-caption-body { font: 400 13px/21px 'Open Sans Condensed', sans-serif; color: #888; padding: 0 0 20px 26px } .cbp-caption-expand-active { -webkit-transition: height .4s!important; transition: height .4s!important } .cbp-caption-expand-active .cbp-item { -webkit-transition: left .4s, top .4s!important; transition: left .4s, top .4s!important } .cbp-caption-expand-open .cbp-caption-activeWrap { -webkit-transition: height .4s; transition: height .4s } .cbp-l-filters-alignCenter { margin-bottom: 30px; text-align: center; font: 400 12px/21px sans-serif; color: #DADADA } .cbp-l-filters-alignCenter .cbp-filter-item { color: #949494; cursor: pointer; font: 400 13px/21px 'Open Sans Condensed', sans-serif; padding: 0 12px; position: relative; overflow: visible; margin: 0 0 10px; display: inline-block; -webkit-transition: color .3s ease-in-out; transition: color .3s ease-in-out } .cbp-l-filters-alignCenter .cbp-filter-item:hover { color: #2D2C2C } .cbp-l-filters-alignCenter .cbp-filter-item:hover .cbp-filter-counter { -webkit-transform: translateY(-30px); transform: translateY(-30px) } .cbp-l-filters-alignCenter .cbp-filter-item.cbp-filter-item-active { color: #2D2C2C; cursor: default } .cbp-l-filters-alignCenter .cbp-filter-counter { font: 400 11px/18px 'Open Sans Condensed', sans-serif; background-color: #626161 } .cbp-l-filters-alignCenter .cbp-filter-counter:after { border-top: 4px solid #626161 } .cbp-l-filters-alignLeft { margin-bottom: 30px } .cbp-l-filters-alignLeft .cbp-filter-item { background-color: #fff; border: 1px solid #cdcdcd; cursor: pointer; font: 400 12px/30px 'Open Sans Condensed', sans-serif; padding: 0 13px; position: relative; overflow: visible; margin: 0 4px 10px; display: inline-block; color: #888; -webkit-transition: color .3s ease-in-out, background-color .3s ease-in-out, border .3s ease-in-out; transition: color .3s ease-in-out, background-color .3s ease-in-out, border .3s ease-in-out } .cbp-l-filters-alignLeft .cbp-filter-item:hover { color: #111 } .cbp-l-filters-alignLeft .cbp-filter-item.cbp-filter-item-active { background-color: #6C7A89; border: 1px solid #6C7A89; color: #fff; cursor: default } .cbp-l-filters-alignLeft .cbp-filter-item:first-child { margin-left: 0 } .cbp-l-filters-alignLeft .cbp-filter-item:last-child { margin-right: 0 } .cbp-l-filters-alignLeft .cbp-filter-counter { display: inline } .cbp-l-filters-alignRight { margin-bottom: 30px; text-align: right } .cbp-l-filters-alignRight .cbp-filter-item { background-color: transparent; color: #8B8B8B; cursor: pointer; font: 400 11px/31px "Open Sans Condensed", sans-serif; padding: 0 14px; position: relative; overflow: visible; margin: 0 3px 10px; border: 1px solid #E4E2E2; text-transform: uppercase; display: inline-block; -webkit-transition: color .3s ease-in-out, background-color .3s ease-in-out, border .3s ease-in-out; transition: color .3s ease-in-out, background-color .3s ease-in-out, border .3s ease-in-out } .cbp-l-filters-alignRight .cbp-filter-item:hover { color: #2B3444 } .cbp-l-filters-alignRight .cbp-filter-item.cbp-filter-item-active { color: #FFF; background-color: #049372; border-color: #049372; cursor: default } .cbp-l-filters-alignRight .cbp-filter-item:first-child { margin-left: 0 } .cbp-l-filters-alignRight .cbp-filter-item:last-child { margin-right: 0 } .cbp-l-filters-alignRight .cbp-filter-counter { background-color: #049372 } .cbp-l-filters-alignRight .cbp-filter-counter:after { border-top: 4px solid #049372 } .cbp-l-filters-button { margin-bottom: 30px } .cbp-l-filters-button .cbp-filter-item:hover .cbp-filter-counter:after { display: block } .cbp-l-filters-button .cbp-filter-item:hover .cbp-filter-counter { bottom: 44px; -ms-filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=100); opacity: 1 } .cbp-l-filters-button .cbp-filter-counter { background-color: #545454 } .cbp-l-filters-button .cbp-filter-counter:after { border-top: 4px solid #545454 } @media only screen and (max-width:480px) { .cbp-l-filters-alignRight, .cbp-l-filters-button { text-align: center } } .cbp-l-filters-buttonCenter { margin-bottom: 30px; text-align: center } .cbp-l-filters-buttonCenter .cbp-filter-item { background-color: #FFF; border: 1px solid #ECECEC; color: #888; cursor: pointer; font: 400 12px/32px 'Open Sans Condensed', sans-serif; margin: 0 10px 10px 0; overflow: visible; padding: 0 17px; position: relative; display: inline-block; -webkit-transition: color .3s ease-in-out, border-color .3s ease-in-out; transition: color .3s ease-in-out, border-color .3s ease-in-out } .cbp-l-filters-buttonCenter .cbp-filter-item:hover { color: #5d5d5d } .cbp-l-filters-buttonCenter .cbp-filter-item.cbp-filter-item-active { color: #3B9CB3; border-color: #8CD2E5; cursor: default } .cbp-l-filters-buttonCenter .cbp-filter-item:first-child { margin-left: 0 } .cbp-l-filters-buttonCenter .cbp-filter-item:last-child { margin-right: 0 } .cbp-l-filters-buttonCenter .cbp-filter-counter { font: 400 11px/18px 'Open Sans Condensed', sans-serif; background-color: #68ABBC } .cbp-l-filters-buttonCenter .cbp-filter-counter:after { border-top: 4px solid #68ABBC } .cbp-l-filters-dropdown { margin-bottom: 40px; height: 38px; position: relative; z-index: 5 } .cbp-l-filters-dropdownWrap { width: 200px; position: absolute; right: 0; background: #4d4c4d } .cbp-l-filters-dropdownHeader { font: 400 12px/38px "Open Sans Condensed", sans-serif; margin: 0 17px; color: #FFF; cursor: default; position: relative } .cbp-l-filters-dropdownHeader:after { border-color: #fff transparent; border-style: solid; border-width: 5px 5px 0; content: ""; height: 0; position: absolute; right: 0; top: 50%; width: 0; margin-top: -1px } .cbp-l-filters-dropdownWrap.cbp-l-filters-dropdownWrap-open .cbp-l-filters-dropdownHeader:after { border-width: 0 5px 5px } .cbp-l-filters-dropdownList { display: none; list-style: none; margin: 0; padding: 0 } .cbp-l-filters-dropdownList>li { margin: 0; list-style: none } .cbp-l-filters-dropdownWrap.cbp-l-filters-dropdownWrap-open .cbp-l-filters-dropdownList { display: block; margin: 0 } .cbp-l-filters-dropdownList .cbp-filter-item { background: 0 0; color: #b3b3b3; width: 100%; text-align: left; font: 400 12px/40px "Open Sans Condensed", sans-serif; margin: 0; padding: 0 17px; cursor: pointer; border: none; border-top: 1px solid #595959 } .cbp-l-filters-dropdownList .cbp-filter-item:hover { color: #e6e6e6 } .cbp-l-filters-dropdownList .cbp-filter-item-active { color: #fff; cursor: default } .cbp-l-filters-dropdownWrap .cbp-filter-counter { display: inline } .cbp-l-filters-dropdown-floated { float: right; margin-top: -2px; margin-left: 20px; width: 200px } @media only screen and (max-width:480px) { .cbp-l-filters-dropdown-floated { width: 100%; margin-top: 0; margin-left: 0 } .cbp-l-filters-dropdownWrap { right: 0; left: 0; margin: 0 auto } } .cbp-l-filters-list { margin-bottom: 30px; content: ""; display: table; clear: both } .cbp-l-filters-list .cbp-filter-item { background-color: transparent; color: #585252; cursor: pointer; font: 400 12px/35px "Open Sans Condensed", sans-serif; padding: 0 18px; position: relative; overflow: visible; margin: 0 0 10px; float: left; border: 1px solid #3288C4; border-right-width: 0; -webkit-transition: left .3s ease-in-out; transition: left .3s ease-in-out } .cbp-l-filters-list .cbp-filter-item:hover { color: #000 } .cbp-l-filters-list .cbp-filter-item.cbp-filter-item-active { cursor: default; color: #FFF; background-color: #3288C4 } .cbp-l-filters-list-first { border-radius: 6px 0 0 6px } .cbp-l-filters-list-last { border-radius: 0 6px 6px 0; border-right-width: 1px!important } .cbp-l-filters-list .cbp-filter-counter { display: inline } @media only screen and (max-width:600px) { .cbp-l-filters-list .cbp-filter-item { margin-right: 5px; border-radius: 6px; border-right-width: 1px } } .cbp-l-filters-work { margin-bottom: 30px; text-align: center } .cbp-l-filters-work .cbp-filter-item { background-color: #FFF; color: #888; cursor: pointer; font: 600 11px/37px "Open Sans Condensed", sans-serif; margin: 0 5px 10px 0; overflow: visible; padding: 0 16px; position: relative; display: inline-block; text-transform: uppercase; -webkit-transition: color .3s ease-in-out, background-color .3s ease-in-out; transition: color .3s ease-in-out, background-color .3s ease-in-out } .cbp-l-filters-work .cbp-filter-item:hover { color: #fff; background: #607D8B } .cbp-l-filters-work .cbp-filter-item.cbp-filter-item-active { background-color: #607D8B; color: #fff; cursor: default } .cbp-l-filters-work .cbp-filter-item:first-child { margin-left: 0 } .cbp-l-filters-work .cbp-filter-item:last-child { margin-right: 0 } .cbp-l-filters-work .cbp-filter-counter { font: 600 11px/37px "Open Sans Condensed", sans-serif; text-align: center; display: inline-block; margin-left: 8px } .cbp-l-filters-work .cbp-filter-counter:before { content: '(' } .cbp-l-filters-work .cbp-filter-counter:after { content: ')' } .cbp-l-filters-big { margin-bottom: 30px; text-align: center } .cbp-l-filters-big .cbp-filter-item { color: #444; cursor: pointer; font: 400 15px/22px Roboto, sans-serif; margin: 0 8px 10px; padding: 10px 23px; position: relative; display: inline-block; border: 1px solid transparent; text-transform: uppercase; -webkit-transition: color .3s ease-in-out, border .3s ease-in-out; transition: color .3s ease-in-out, border .3s ease-in-out } .cbp-l-filters-big .cbp-filter-item:hover { color: #888 } .cbp-l-filters-big .cbp-filter-item.cbp-filter-item-active { border-color: #d5d5d5; color: #444; cursor: default } .cbp-l-filters-big .cbp-filter-item:first-child { margin-left: 0 } .cbp-l-filters-big .cbp-filter-item:last-child { margin-right: 0 } .cbp-l-filters-text { margin-bottom: 30px; text-align: center; font: 400 12px/21px Lato, sans-serif; color: #DADADA; padding: 0 15px } .cbp-l-filters-text .cbp-filter-item { color: #949494; cursor: pointer; font: 400 13px/21px Lato, sans-serif; padding: 0 12px; position: relative; overflow: visible; margin: 0 0 10px; display: inline-block; -webkit-transition: color .3s ease-in-out; transition: color .3s ease-in-out } .cbp-l-filters-text .cbp-filter-item:hover { color: #2D2C2C } .cbp-l-filters-text .cbp-filter-item:hover .cbp-filter-counter { -webkit-transform: translateY(-30px); transform: translateY(-30px) } .cbp-l-filters-text .cbp-filter-item.cbp-filter-item-active { color: #2D2C2C; cursor: default } .cbp-l-filters-text .cbp-filter-counter { background-color: #626161; font: 400 11px/18px Lato, sans-serif } .cbp-l-filters-text .cbp-filter-counter:after { border-top: 4px solid #626161 } .cbp-l-filters-text-sort { display: inline-block; font: 400 13px/21px Lato, sans-serif; color: #949494; margin-right: 15px } @media only screen and (max-width:480px) { .cbp-l-filters-text-sort { display: block; margin-bottom: 10px } .cbp-l-filters-underline { text-align: center } } .cbp-l-filters-underline { margin-bottom: 30px } .cbp-l-filters-underline .cbp-filter-item { border-bottom: 3px solid transparent; cursor: pointer; font: 600 14px/21px "Open Sans Condensed", sans-serif; padding: 8px 10px; position: relative; overflow: visible; margin: 0 20px 10px 0; display: inline-block; color: #787878; -webkit-transition: color .25s ease-in-out, border-color .25s ease-in-out; transition: color .25s ease-in-out, border-color .25s ease-in-out } .cbp-l-filters-underline .cbp-filter-item:hover { color: #111 } .cbp-l-filters-underline .cbp-filter-item.cbp-filter-item-active { border-bottom-color: #666; color: #444; cursor: default } .cbp-popup-lightbox-counter, .cbp-popup-lightbox-title { font: 400 12px/18px "Open Sans Condensed", sans-serif; color: #eee } .cbp-l-filters-underline .cbp-filter-item:first-child { margin-left: 0 } .cbp-l-filters-underline .cbp-filter-item:last-child { margin-right: 0 } .cbp-l-filters-underline .cbp-filter-counter { display: inline } .cbp-animation-quicksand { -webkit-transition: height .6s ease-in-out; transition: height .6s ease-in-out; will-change: height } .cbp-animation-quicksand .cbp-item { -webkit-transition: -webkit-transform .6s ease-in-out; transition: transform .6s ease-in-out; -webkit-perspective: 1000px; perspective: 1000px } .cbp-animation-quicksand .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-quicksand .cbp-item-on2off .cbp-item-wrapper { -webkit-animation: quicksand-off .6s ease-out both; animation: quicksand-off .6s ease-out both } .cbp-animation-quicksand .cbp-item-off2on .cbp-item-wrapper { -webkit-animation: quicksand-on .6s ease-out both; animation: quicksand-on .6s ease-out both } @-webkit-keyframes quicksand-off { 100% { opacity: 0; -webkit-transform: scale3d(0, 0, 0) } } @keyframes quicksand-off { 100% { opacity: 0; transform: scale3d(0, 0, 0) } } @-webkit-keyframes quicksand-on { 0% { opacity: 0; -webkit-transform: scale3d(0, 0, 0) } } @keyframes quicksand-on { 0% { opacity: 0; transform: scale3d(0, 0, 0) } } .cbp-animation-boxShadow, .cbp-animation-fadeOut { -webkit-transition: height .6s ease-in-out; transition: height .6s ease-in-out; will-change: height } .cbp-animation-boxShadow .cbp-item, .cbp-animation-fadeOut .cbp-item { -webkit-transition: -webkit-transform .6s ease-in-out; transition: transform .6s ease-in-out; -webkit-perspective: 1000px; perspective: 1000px } .cbp-animation-boxShadow .cbp-item-wrapper, .cbp-animation-fadeOut .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-boxShadow .cbp-item-on2off .cbp-item-wrapper, .cbp-animation-fadeOut .cbp-item-on2off .cbp-item-wrapper { -webkit-animation: fadeOut-off .6s ease-in-out both; animation: fadeOut-off .6s ease-in-out both } .cbp-animation-boxShadow .cbp-item-off2on .cbp-item-wrapper, .cbp-animation-fadeOut .cbp-item-off2on .cbp-item-wrapper { -webkit-animation: fadeOut-on .6s ease-in-out both; animation: fadeOut-on .6s ease-in-out both } @-webkit-keyframes fadeOut-off { 0% { opacity: 1 } 100%, 80% { opacity: 0 } } @keyframes fadeOut-off { 0% { opacity: 1 } 100%, 80% { opacity: 0 } } @-webkit-keyframes fadeOut-on { 0% { opacity: 0 } 100% { opacity: 1 } } @keyframes fadeOut-on { 0% { opacity: 0 } 100% { opacity: 1 } } .cbp-animation-flipOut { -webkit-transition: height .7s ease-in-out; transition: height .7s ease-in-out; will-change: height } .cbp-animation-flipOut .cbp-item { -webkit-transition: -webkit-transform .7s ease-in-out; transition: transform .7s ease-in-out; -webkit-perspective: 1000px; perspective: 1000px } .cbp-animation-flipOut .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-flipOut .cbp-item-on2off .cbp-item-wrapper { -webkit-animation: flipOut-out .7s both ease-in; animation: flipOut-out .7s both ease-in } .cbp-animation-flipOut .cbp-item-off2on .cbp-item-wrapper { -webkit-animation: flipOut-in .7s ease-out both; animation: flipOut-in .7s ease-out both } @-webkit-keyframes flipOut-out { 100%, 50% { -webkit-transform: translateZ(-1000px) rotateY(-90deg); opacity: .2 } } @keyframes flipOut-out { 100%, 50% { transform: translateZ(-1000px) rotateY(-90deg); opacity: .2 } } @-webkit-keyframes flipOut-in { 0%, 50% { -webkit-transform: translateZ(-1000px) rotateY(90deg); opacity: .2 } } @keyframes flipOut-in { 0%, 50% { transform: translateZ(-1000px) rotateY(90deg); opacity: .2 } } .cbp-animation-flipBottom { -webkit-transition: height .7s ease-in-out; transition: height .7s ease-in-out; will-change: height } .cbp-animation-flipBottom .cbp-item { -webkit-transition: -webkit-transform .7s ease-in-out; transition: transform .7s ease-in-out; -webkit-perspective: 1000px; perspective: 1000px } .cbp-animation-flipBottom .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-flipBottom .cbp-item-on2off .cbp-item-wrapper { -webkit-animation: flipBottom-out .7s both ease-in; animation: flipBottom-out .7s both ease-in } .cbp-animation-flipBottom .cbp-item-off2on .cbp-item-wrapper { -webkit-animation: flipBottom-in .7s ease-out both; animation: flipBottom-in .7s ease-out both } @-webkit-keyframes flipBottom-out { 100%, 50% { -webkit-transform: translateZ(-1000px) rotateX(-90deg); opacity: .2 } } @keyframes flipBottom-out { 100%, 50% { transform: translateZ(-1000px) rotateX(-90deg); opacity: .2 } } @-webkit-keyframes flipBottom-in { 0%, 50% { -webkit-transform: translateZ(-1000px) rotateX(90deg); opacity: .2 } } @keyframes flipBottom-in { 0%, 50% { transform: translateZ(-1000px) rotateX(90deg); opacity: .2 } } .cbp-animation-scaleSides { -webkit-transition: height .6s ease-in-out; transition: height .6s ease-in-out; will-change: height } .cbp-animation-scaleSides .cbp-item { -webkit-transition: -webkit-transform .6s ease-in-out; transition: transform .6s ease-in-out; -webkit-perspective: 1000px; perspective: 1000px } .cbp-animation-fadeOutTop, .cbp-animation-skew { -webkit-transition: height .6s ease-in-out; will-change: height } .cbp-animation-scaleSides .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-scaleSides .cbp-item-on2off .cbp-item-wrapper { -webkit-animation: scaleSides-out .9s both; animation: scaleSides-out .9s both } .cbp-animation-scaleSides .cbp-item-off2on .cbp-item-wrapper { -webkit-animation: scaleSides-in .9s both; animation: scaleSides-in .9s both } @-webkit-keyframes scaleSides-out { 100%, 50% { -webkit-transform: scale(.6); opacity: 0 } } @keyframes scaleSides-out { 100%, 50% { transform: scale(.6); opacity: 0 } } @-webkit-keyframes scaleSides-in { 0%, 50% { -webkit-transform: scale(.6); opacity: 0 } } @keyframes scaleSides-in { 0%, 50% { transform: scale(.6); opacity: 0 } } .cbp-animation-skew { transition: height .6s ease-in-out } .cbp-animation-skew .cbp-item { -webkit-transition: -webkit-transform .6s ease-in-out; transition: transform .6s ease-in-out; -webkit-perspective: 1000px; perspective: 1000px } .cbp-animation-skew .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-skew .cbp-item-on2off .cbp-item-wrapper { -webkit-animation: skew-off .6s ease-out both; animation: skew-off .6s ease-out both } .cbp-animation-skew .cbp-item-off2on .cbp-item-wrapper { -webkit-animation: skew-on .6s ease-out both; animation: skew-on .6s ease-out both } @-webkit-keyframes skew-off { 100% { opacity: 0; -webkit-transform: scale3d(0, 0, 0) skew(20deg, 0) } } @keyframes skew-off { 100% { opacity: 0; transform: scale3d(0, 0, 0) skew(20deg, 0) } } @-webkit-keyframes skew-on { 0% { opacity: 0; -webkit-transform: scale3d(0, 0, 0) skew(0, 20deg) } } @keyframes skew-on { 0% { opacity: 0; transform: scale3d(0, 0, 0) skew(0, 20deg) } } .cbp-animation-fadeOutTop { transition: height .6s ease-in-out } .cbp-animation-sequentially, .cbp-animation-slideLeft { -webkit-transition: height .6s ease-in-out; will-change: height; transition: height .6s ease-in-out } .cbp-animation-fadeOutTop .cbp-wrapper-outer { overflow: visible } .cbp-animation-fadeOutTop .cbp-item { -webkit-perspective: 1000px; perspective: 1000px; overflow: visible } .cbp-animation-fadeOutTop .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-fadeOutTop .cbp-wrapper-helper .cbp-item-wrapper { -webkit-animation: fadeOutTop-out .6s both ease-in-out; animation: fadeOutTop-out .6s both ease-in-out } .cbp-animation-fadeOutTop .cbp-wrapper .cbp-item-wrapper { -webkit-animation: fadeOutTop-in .6s both ease-in-out; animation: fadeOutTop-in .6s both ease-in-out } @-webkit-keyframes fadeOutTop-out { 0% { -webkit-transform: translateY(0); opacity: 1 } 100%, 50% { -webkit-transform: translateY(-30px); opacity: 0 } } @keyframes fadeOutTop-out { 0% { transform: translateY(0); opacity: 1 } 100%, 50% { transform: translateY(-30px); opacity: 0 } } @-webkit-keyframes fadeOutTop-in { 0%, 50% { -webkit-transform: translateY(-30px); opacity: 0 } 100% { -webkit-transform: translateY(0); opacity: 1 } } @keyframes fadeOutTop-in { 0%, 50% { transform: translateY(-30px); opacity: 0 } 100% { transform: translateY(0); opacity: 1 } } .cbp-animation-slideLeft .cbp-item { -webkit-perspective: 1000px; perspective: 1000px } .cbp-animation-slideLeft .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-slideLeft .cbp-wrapper-helper .cbp-item-wrapper { -webkit-animation: slideLeft-out .8s both ease-in-out; animation: slideLeft-out .8s both ease-in-out } .cbp-animation-slideLeft .cbp-wrapper .cbp-item-wrapper { -webkit-animation: slideLeft-in .8s both ease-in-out; animation: slideLeft-in .8s both ease-in-out } @-webkit-keyframes slideLeft-out { 0% { opacity: 1; transform: scale(1) } 25% { opacity: .75; -webkit-transform: scale(.8) } 100%, 75% { opacity: .75; -webkit-transform: scale(.8) translateX(-200%) } } @keyframes slideLeft-out { 0% { opacity: 1; transform: scale(1) } 25% { opacity: .75; transform: scale(.8) } 100%, 75% { opacity: .75; transform: scale(.8) translateX(-200%) } } @-webkit-keyframes slideLeft-in { 0%, 25% { opacity: .75; -webkit-transform: scale(.8) translateX(200%) } 75% { opacity: .75; -webkit-transform: scale(.8) } 100% { opacity: 1; -webkit-transform: scale(1) translateX(0) } } @keyframes slideLeft-in { 0%, 25% { opacity: .75; transform: scale(.8) translateX(200%) } 75% { opacity: .75; transform: scale(.8) } 100% { opacity: 1; transform: scale(1) translateX(0) } } .cbp-animation-3dflip, .cbp-animation-flipOutDelay { -webkit-transition: height .6s ease-in-out; will-change: height } .cbp-animation-sequentially .cbp-wrapper-outer { overflow: visible } .cbp-animation-sequentially .cbp-item { -webkit-perspective: 1000px; perspective: 1000px; overflow: visible } .cbp-animation-sequentially .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-sequentially .cbp-wrapper-helper .cbp-item-wrapper { -webkit-animation: fadeOutTop-out .6s both ease; animation: fadeOutTop-out .6s both ease } .cbp-animation-sequentially .cbp-wrapper .cbp-item-wrapper { -webkit-animation: fadeOutTop-in .6s both ease-out; animation: fadeOutTop-in .6s both ease-out } .cbp-animation-3dflip { transition: height .6s ease-in-out } .cbp-animation-3dflip .cbp-item { -webkit-perspective: 1000px; perspective: 1000px } .cbp-animation-3dflip .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-3dflip .cbp-wrapper-helper .cbp-item-wrapper { -webkit-transform-origin: 0 50%; transform-origin: 0 50%; -webkit-animation: flip-out .6s both ease-in-out; animation: flip-out .6s both ease-in-out } .cbp-animation-3dflip .cbp-wrapper .cbp-item-wrapper { -webkit-transform-origin: 100% 50%; transform-origin: 100% 50%; -webkit-animation: flip-in .6s both ease-in-out; animation: flip-in .6s both ease-in-out } @-webkit-keyframes flip-out { 100% { opacity: 0; -webkit-transform: rotateY(90deg) } } @keyframes flip-out { 100% { opacity: 0; transform: rotateY(90deg) } } @-webkit-keyframes flip-in { 0% { opacity: 0; -webkit-transform: rotateY(-90deg) } 100% { opacity: 1; -webkit-transform: rotateY(0) } } @keyframes flip-in { 0% { opacity: 0; transform: rotateY(-90deg) } 100% { opacity: 1; transform: rotateY(0) } } .cbp-animation-flipOutDelay { transition: height .6s ease-in-out } .cbp-animation-rotateSides, .cbp-animation-slideDelay { -webkit-transition: height .6s ease-in-out; will-change: height; transition: height .6s ease-in-out } .cbp-animation-flipOutDelay .cbp-item { -webkit-perspective: 1000px; perspective: 1000px } .cbp-animation-flipOutDelay .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-flipOutDelay .cbp-wrapper-helper .cbp-item-wrapper { -webkit-animation: flipOut-out 1s both ease-in; animation: flipOut-out 1s both ease-in } .cbp-animation-flipOutDelay .cbp-wrapper .cbp-item-wrapper { -webkit-animation: flipOut-in 1s both ease-out; animation: flipOut-in 1s both ease-out } .cbp-animation-slideDelay .cbp-item { -webkit-perspective: 1000px; perspective: 1000px } .cbp-animation-slideDelay .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-slideDelay .cbp-wrapper-helper .cbp-item-wrapper { -webkit-animation: slideDelay-out .5s both ease-in-out; animation: slideDelay-out .5s both ease-in-out } .cbp-animation-slideDelay .cbp-wrapper .cbp-item-wrapper { -webkit-animation: slideDelay-in .5s both ease-in-out; animation: slideDelay-in .5s both ease-in-out } @-webkit-keyframes slideDelay-out { 100% { -webkit-transform: translateX(-100%) } } @keyframes slideDelay-out { 100% { transform: translateX(-100%) } } @-webkit-keyframes slideDelay-in { 0% { -webkit-transform: translateX(100%) } 100% { -webkit-transform: translateX(0) } } @keyframes slideDelay-in { 0% { transform: translateX(100%) } 100% { transform: translateX(0) } } .cbp-animation-foldLeft, .cbp-animation-unfold { -webkit-transition: height .6s ease-in-out; will-change: height } .cbp-animation-rotateSides .cbp-item { -webkit-perspective: 1000px; perspective: 1000px } .cbp-animation-rotateSides .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-rotateSides .cbp-wrapper-helper .cbp-item-wrapper { -webkit-transform-origin: -50% 50%; -webkit-animation: rotateSides-out .5s both ease-in; transform-origin: -50% 50%; animation: rotateSides-out .5s both ease-in } .cbp-animation-rotateSides .cbp-wrapper .cbp-item-wrapper { -webkit-transform-origin: 150% 50%; -webkit-animation: rotateSides-in .6s both ease-out; transform-origin: 150% 50%; animation: rotateSides-in .6s both ease-out } @-webkit-keyframes rotateSides-out { 100% { opacity: 0; -webkit-transform: translateZ(-500px) rotateY(90deg) } } @keyframes rotateSides-out { 100% { opacity: 0; transform: translateZ(-500px) rotateY(90deg) } } @-webkit-keyframes rotateSides-in { 0%, 40% { opacity: 0; -webkit-transform: translateZ(-500px) rotateY(-90deg) } } @keyframes rotateSides-in { 0%, 40% { opacity: 0; transform: translateZ(-500px) rotateY(-90deg) } } .cbp-animation-foldLeft { transition: height .6s ease-in-out } .cbp-animation-foldLeft .cbp-item { -webkit-perspective: 1000px; perspective: 1000px } .cbp-animation-foldLeft .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-foldLeft .cbp-wrapper-helper .cbp-item-wrapper { -webkit-transform-origin: 100% 50%; transform-origin: 100% 50%; -webkit-animation: foldLeft-out .7s both; animation: foldLeft-out .7s both } .cbp-animation-foldLeft .cbp-wrapper .cbp-item-wrapper { -webkit-animation: foldLeft-in .7s both; animation: foldLeft-in .7s both } @-webkit-keyframes foldLeft-out { 100% { opacity: 0; -webkit-transform: translateX(-100%) rotateY(-90deg) } } @keyframes foldLeft-out { 100% { opacity: 0; transform: translateX(-100%) rotateY(-90deg) } } @-webkit-keyframes foldLeft-in { 0% { opacity: .3; -webkit-transform: translateX(100%) } } @keyframes foldLeft-in { 0% { opacity: .3; transform: translateX(100%) } } .cbp-animation-unfold { transition: height .6s ease-in-out } .cbp-animation-frontRow, .cbp-animation-scaleDown { -webkit-transition: height .6s ease-in-out; will-change: height; transition: height .6s ease-in-out } .cbp-animation-unfold .cbp-item { -webkit-perspective: 1000px; perspective: 1000px } .cbp-animation-unfold .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-unfold .cbp-wrapper-helper .cbp-item-wrapper { -webkit-animation: unfold-out .8s both; animation: unfold-out .8s both } .cbp-animation-unfold .cbp-wrapper .cbp-item-wrapper { -webkit-transform-origin: 0 50%; -webkit-animation: unfold-in .8s both; transform-origin: 0 50%; animation: unfold-in .8s both } @-webkit-keyframes unfold-out { 90% { opacity: .3 } 100% { opacity: 0; -webkit-transform: translateX(-100%) } } @keyframes unfold-out { 90% { opacity: .3 } 100% { opacity: 0; transform: translateX(-100%) } } @-webkit-keyframes unfold-in { 0% { opacity: 0; -webkit-transform: translateX(100%) rotateY(90deg) } } @keyframes unfold-in { 0% { opacity: 0; transform: translateX(100%) rotateY(90deg) } } .cbp-animation-scaleDown .cbp-item { -webkit-perspective: 1000px; perspective: 1000px } .cbp-animation-scaleDown .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-scaleDown .cbp-wrapper-helper .cbp-item-wrapper { -webkit-animation: scaleDown-out .7s both; animation: scaleDown-out .7s both } .cbp-animation-scaleDown .cbp-wrapper .cbp-item-wrapper { -webkit-animation: scaleDown-in .6s both; animation: scaleDown-in .6s both } @-webkit-keyframes scaleDown-out { 100% { opacity: 0; -webkit-transform: scale(.8) } } @keyframes scaleDown-out { 100% { opacity: 0; transform: scale(.8) } } @-webkit-keyframes scaleDown-in { 0% { -webkit-transform: translateX(100%) } } @keyframes scaleDown-in { 0% { transform: translateX(100%) } } .cbp-animation-bounceBottom, .cbp-animation-rotateRoom { -webkit-transition: height .6s ease-in-out; will-change: height } .cbp-animation-frontRow .cbp-item { -webkit-perspective: 1000px; perspective: 1000px } .cbp-animation-frontRow .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-frontRow .cbp-wrapper-helper .cbp-item-wrapper { -webkit-animation: frontRow-out .7s both ease; animation: frontRow-out .7s both ease } .cbp-animation-frontRow .cbp-wrapper .cbp-item-wrapper { -webkit-animation: frontRow-in .6s both ease; animation: frontRow-in .6s both ease } @-webkit-keyframes frontRow-out { 100% { -webkit-transform: translateX(-60%) scale(.8); opacity: 0 } } @keyframes frontRow-out { 100% { transform: translateX(-60%) scale(.8); opacity: 0 } } @-webkit-keyframes frontRow-in { 0% { -webkit-transform: translateX(100%) scale(.8) } 100% { opacity: 1; -webkit-transform: translateX(0) scale(1) } } @keyframes frontRow-in { 0% { transform: translateX(100%) scale(.8) } 100% { opacity: 1; transform: translateX(0) scale(1) } } .cbp-animation-rotateRoom { transition: height .6s ease-in-out } .cbp-animation-rotateRoom .cbp-item { -webkit-perspective: 1000px; perspective: 1000px } .cbp-animation-rotateRoom .cbp-item-wrapper { -webkit-transform-style: preserve-3d; transform-style: preserve-3d } .cbp-animation-rotateRoom .cbp-wrapper-helper .cbp-item-wrapper { -webkit-transform-origin: 100% 50%; transform-origin: 100% 50%; -webkit-animation: rotateRoom-out .8s both ease; animation: rotateRoom-out .8s both ease } .cbp-animation-rotateRoom .cbp-wrapper .cbp-item-wrapper { -webkit-transform-origin: 0 50%; transform-origin: 0 50%; -webkit-animation: rotateRoom-in .8s both ease; animation: rotateRoom-in .8s both ease } @-webkit-keyframes rotateRoom-out { 90% { opacity: .3 } 100% { opacity: 0; -webkit-transform: translateX(-100%) rotateY(90deg) } } @keyframes rotateRoom-out { 90% { opacity: .3 } 100% { opacity: 0; transform: translateX(-100%) rotateY(90deg) } } @-webkit-keyframes rotateRoom-in { 0% { opacity: .3; -webkit-transform: translateX(100%) rotateY(-90deg) } } @keyframes rotateRoom-in { 0% { opacity: .3; transform: translateX(100%) rotateY(-90deg) } } .cbp-animation-bounceBottom { transition: height .6s ease-in-out } .cbp-animation-bounceLeft, .cbp-animation-bounceTop { -webkit-transition: height .6s ease-in-out; will-change: height; transition: height .6s ease-in-out } .cbp-animation-bounceBottom .cbp-wrapper-helper { -webkit-animation: bounceBottom-out .6s both ease-in-out; animation: bounceBottom-out .6s both ease-in-out } .cbp-animation-bounceBottom .cbp-wrapper { -webkit-animation: bounceBottom-in .6s both ease-in-out; animation: bounceBottom-in .6s both ease-in-out } @-webkit-keyframes bounceBottom-out { 100% { -webkit-transform: translateY(100%); opacity: 0 } } @keyframes bounceBottom-out { 100% { transform: translateY(100%); opacity: 0 } } @-webkit-keyframes bounceBottom-in { 0% { -webkit-transform: translateY(100%); opacity: 0 } 100% { -webkit-transform: translateY(0); opacity: 1 } } @keyframes bounceBottom-in { 0% { transform: translateY(100%); opacity: 0 } 100% { transform: translateY(0); opacity: 1 } } .cbp-animation-bounceLeft .cbp-wrapper-helper { -webkit-animation: bounceLeft-out .6s both ease-in-out; animation: bounceLeft-out .6s both ease-in-out } .cbp-animation-bounceLeft .cbp-wrapper { -webkit-animation: bounceLeft-in .6s both ease-in-out; animation: bounceLeft-in .6s both ease-in-out } @-webkit-keyframes bounceLeft-out { 100% { -webkit-transform: translateX(-100%); opacity: 0 } } @keyframes bounceLeft-out { 100% { transform: translateX(-100%); opacity: 0 } } @-webkit-keyframes bounceLeft-in { 0% { -webkit-transform: translateX(-100%); opacity: 0 } 100% { -webkit-transform: translateX(0); opacity: 1 } } @keyframes bounceLeft-in { 0% { transform: translateX(-100%); opacity: 0 } 100% { transform: translateX(0); opacity: 1 } } .cbp-animation-bounceTop .cbp-wrapper-helper { -webkit-animation: bounceTop-out .6s both ease-in-out; animation: bounceTop-out .6s both ease-in-out } .cbp-animation-bounceTop .cbp-wrapper { -webkit-animation: bounceTop-in .6s both ease-in-out; animation: bounceTop-in .6s both ease-in-out } @-webkit-keyframes bounceTop-out { 100% { -webkit-transform: translateY(-100%); opacity: 0 } } @keyframes bounceTop-out { 100% { transform: translateY(-100%); opacity: 0 } } @-webkit-keyframes bounceTop-in { 0% { -webkit-transform: translateY(-100%); opacity: 0 } 100% { -webkit-transform: translateY(0); opacity: 1 } } @keyframes bounceTop-in { 0% { transform: translateY(-100%); opacity: 0 } 100% { transform: translateY(0); opacity: 1 } } .cbp-animation-moveLeft { -webkit-transition: height .6s ease-in-out; transition: height .6s ease-in-out; will-change: height } .cbp-animation-moveLeft .cbp-wrapper-helper { -webkit-animation: moveLeft-out .6s both ease-in-out; animation: moveLeft-out .6s both ease-in-out } .cbp-animation-moveLeft .cbp-wrapper { -webkit-animation: moveLeft-in .6s both ease-in-out; animation: moveLeft-in .6s both ease-in-out } @-webkit-keyframes moveLeft-out { 100% { -webkit-transform: translateX(-100%); opacity: 0 } } @keyframes moveLeft-out { 100% { transform: translateX(-100%); opacity: 0 } } @-webkit-keyframes moveLeft-in { 0% { -webkit-transform: translateX(100%); opacity: 0 } 100% { -webkit-transform: translateX(0); opacity: 1 } } @keyframes moveLeft-in { 0% { transform: translateX(100%); opacity: 0 } 100% { transform: translateX(0); opacity: 1 } } .cbp-displayType-bottomToTop { -webkit-perspective: 1000px; perspective: 1000px } .cbp-displayType-bottomToTop .cbp-item { -webkit-animation: fadeInBottomToTop .3s both ease-in; animation: fadeInBottomToTop .3s both ease-in } @-webkit-keyframes fadeInBottomToTop { 0% { opacity: 0; -webkit-transform: translateY(50px) } 100% { opacity: 1; -webkit-transform: translateY(0) } } @keyframes fadeInBottomToTop { 0% { opacity: 0; transform: translateY(50px) } 100% { opacity: 1; transform: translateY(0) } } .cbp-displayType-fadeIn { -webkit-animation: fadeIn .5s both ease-in; animation: fadeIn .5s both ease-in } @-webkit-keyframes fadeIn { 0% { opacity: 0 } 100% { opacity: 1 } } @keyframes fadeIn { 0% { opacity: 0 } 100% { opacity: 1 } } .cbp-displayType-fadeInToTop { -webkit-perspective: 1000px; perspective: 1000px; -webkit-animation: fadeInToTop .5s both ease-in; animation: fadeInToTop .5s both ease-in } @-webkit-keyframes fadeInToTop { 0% { opacity: 0; -webkit-transform: translateY(30px) } 100% { opacity: 1; -webkit-transform: translateY(0) } } @keyframes fadeInToTop { 0% { opacity: 0; transform: translateY(30px) } 100% { opacity: 1; transform: translateY(0) } } .cbp-displayType-sequentially .cbp-item { -webkit-animation: fadeIn .5s both ease-in; animation: fadeIn .5s both ease-in } .cbp-lightbox img { display: block; border: 0; width: 100%; height: auto } .cbp-popup-ie8bg { position: absolute; width: 100%; height: 100%; min-height: 100%; top: 0; left: 0; z-index: -1; background: #000 } .cbp-popup-wrap { height: 100%; text-align: center; position: fixed; width: 100%; left: 0; top: 0; display: none; overflow-y: hidden; -webkit-overflow-scrolling: touch; overflow-x: hidden; z-index: 9990; padding: 0 10px } .cbp-popup-wrap video { outline: 0 } .cbp-popup-lightbox { background: rgba(0, 0, 0, .8); display: flex; justify-content: center; align-items: center } .cbp-popup-content, .cbp-popup-wrap:before { display: inline-block; vertical-align: middle } .cbp-popup-singlePage { background: #fff; padding: 0 } .cbp-popup-wrap:before { content: ""; height: 100% } .cbp-popup-content { position: relative; text-align: left; max-width: 100% } .cbp-popup-lightbox .cbp-popup-content { display: flex } .cbp-popup-singlePage .cbp-popup-content { position: relative; z-index: 1; margin-top: 145px; max-width: 1024px; vertical-align: top; width: 94% } .cbp-popup-singlePage .cbp-popup-content-basic { position: relative; z-index: 1; margin-top: 104px; vertical-align: top; width: 100%; display: inline-block; text-align: left } .cbp-popup-lightbox-figure { width: 100%; position: relative; padding: 20px 0 } .cbp-popup-lightbox-bottom { position: relative; margin-top: 3px } .cbp-popup-lightbox-title { padding-right: 50px } .cbp-popup-lightbox-counter { position: absolute; top: 0; right: 0 } .cbp-popup-lightbox-img { width: auto; max-width: 100%; height: auto; display: block; box-shadow: 0 0 8px rgba(0, 0, 0, .6) } .cbp-popup-lightbox-img[data-action] { cursor: pointer } .cbp-popup-lightbox-isIframe .cbp-popup-content { width: 75%; display: inline-block } @media only screen and (max-width:768px) { .cbp-popup-lightbox-isIframe .cbp-popup-content { width: 95% } } .cbp-popup-lightbox-isIframe .cbp-lightbox-bottom { left: 0; position: absolute; top: 100%; width: 100%; margin-top: 3px } .cbp-popup-lightbox-iframe { position: relative; height: 0; padding-bottom: 56.25%; background: #000 } .cbp-popup-lightbox-iframe iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; box-shadow: 0 0 8px rgba(0, 0, 0, .6) } .cbp-popup-lightbox-iframe audio { margin-top: 27% } .cbp-popup-lightbox-iframe .cbp-popup-lightbox-bottom { position: absolute; left: 0; top: 100%; width: 100% } .cbp-popup-singlePage .cbp-popup-navigation-wrap { position: absolute; top: 0; left: 0; width: 100%; z-index: 9990; height: 104px; background-color: #3D4750 } .cbp-popup-singlePage .cbp-popup-navigation { position: relative; width: 100%; height: 100% } .cbp-popup-singlePage-sticky .cbp-popup-navigation-wrap { position: fixed; top: 0!important } .cbp-popup-singlePage-counter { color: #fff; position: absolute; margin: auto; right: 40px; top: 0; bottom: 0; font: 400 14px/30px "Open Sans Condensed", sans-serif; height: 30px } .cbp-popup-lightbox .cbp-popup-next, .cbp-popup-lightbox .cbp-popup-prev, .cbp-popup-singlePage .cbp-popup-next, .cbp-popup-singlePage .cbp-popup-prev { width: 44px; height: 44px; top: 0; margin: auto; bottom: 0 } @media only screen and (max-width:768px) { .cbp-popup-singlePage-counter { right: 3% } } .cbp-popup-close, .cbp-popup-next, .cbp-popup-prev { padding: 0; border: none; position: absolute; cursor: pointer; outline: 0; user-select: none } .cbp-popup-lightbox .cbp-popup-prev { background: url(../img/cbp-sprite.png) no-repeat; left: 20px } .cbp-popup-lightbox .cbp-popup-prev:hover { background-position: 0 -46px } .cbp-popup-singlePage .cbp-popup-prev { background: url(../img/cbp-sprite.png) 0 -92px no-repeat; right: 108px; left: 0 } .cbp-popup-singlePage .cbp-popup-prev:hover { background-position: 0 -138px } .cbp-popup-lightbox .cbp-popup-next { background: url(../img/cbp-sprite.png) -46px 0 no-repeat; right: 20px } .cbp-popup-lightbox .cbp-popup-next:hover { background-position: -46px -46px } .cbp-popup-singlePage .cbp-popup-next { background: url(../img/cbp-sprite.png) -46px -92px no-repeat; right: 0; left: 108px } .cbp-popup-singlePage .cbp-popup-next:hover { background-position: -46px -138px } .cbp-popup-lightbox .cbp-popup-close { background: url(../img/cbp-sprite.png) -92px 0 no-repeat; height: 40px; width: 40px; right: 20px; top: 20px } .cbp-popup-lightbox .cbp-popup-close:hover { background-position: -92px -46px } .cbp-popup-singlePage .cbp-popup-close { background: url(../img/cbp-sprite.png) -92px -92px no-repeat; height: 44px; width: 44px; margin: auto; top: 0; right: 0; bottom: 0; left: 0 } .cbp-popup-singlePage .cbp-popup-close:hover { background-position: -92px -138px } .cbp-popup-singlePage .cbp-popup-ie8bg { background-color: #fff } @media only screen and (max-width:360px), (max-height:600px) { .cbp-popup-close, .cbp-popup-next, .cbp-popup-prev { -webkit-transform: scale(.8); transform: scale(.8) } .cbp-popup-lightbox .cbp-popup-close { right: 10px; top: 10px } .cbp-popup-lightbox .cbp-popup-next { right: 10px } .cbp-popup-lightbox .cbp-popup-prev { left: 10px } .cbp-popup-singlePage .cbp-popup-navigation-wrap { height: 84px } .cbp-popup-singlePage .cbp-popup-content { margin-top: 120px } } .cbp-popup-loadingBox { width: 100%; height: 100%; position: absolute; top: 0; left: 0 } .cbp-popup-lightbox .cbp-popup-loadingBox:after { border-left: 3px solid rgba(255, 255, 255, .3); border-right: 3px solid rgba(255, 255, 255, .3); border-bottom: 3px solid rgba(255, 255, 255, .3); border-top: 3px solid rgba(255, 255, 255, .85) } .cbp-popup-ready .cbp-popup-loadingBox { visibility: hidden; display: none } .cbp-popup-loading .cbp-popup-loadingBox { visibility: visible; display: block } .cbp-popup-transitionend { overflow-y: scroll } .cbp-popup-singlePage { left: 100%; -webkit-transition: left .6s ease-in-out; transition: left .6s ease-in-out } .cbp-popup-singlePage.cbp-popup-loading .cbp-popup-content { opacity: 0 } .cbp-popup-singlePage-open { left: 0 } .cbp-popup-singlePage.cbp-popup-singlePage-fade { left: 0; opacity: 0; -webkit-transition: opacity .25s ease-in-out; transition: opacity .25s ease-in-out } .cbp-popup-singlePage-open.cbp-popup-singlePage-fade { opacity: 1 } .cbp-popup-singlePage.cbp-popup-singlePage-right { left: -100%; -webkit-transition: left .6s ease-in-out; transition: left .6s ease-in-out } .cbp-popup-singlePage-open.cbp-popup-singlePage-right { left: 0 } .cbp-l-project-title { color: #454444; font: 600 42px/46px "Open Sans Condensed", sans-serif; letter-spacing: 2px; margin-bottom: 15px; text-align: center; text-transform: uppercase } .cbp-l-project-subtitle { color: #787878; font: 400 14px/21px "Open Sans Condensed", sans-serif; margin: 0 auto 50px; max-width: 500px; text-align: center } .cbp-popup-singlePage .cbp-popup-content .cbp-l-project-img { display: block; margin: 0 auto; max-width: 100% } .cbp-l-project-container { overflow: hidden; margin: 40px auto 0; clear: both } .cbp-l-project-desc { float: left; width: 62% } .cbp-l-project-details { float: right; width: 38%; padding-left: 60px; margin-bottom: 15px } @media only screen and (max-width:768px) { .cbp-l-project-title { font-size: 30px; line-height: 34px } .cbp-l-project-desc { width: 100% } .cbp-l-project-details { width: 100%; margin-top: 20px; padding-left: 0 } } .cbp-l-project-desc-title { border-bottom: 1px solid #cdcdcd; margin-bottom: 22px; color: #444 } .cbp-l-project-desc-title span, .cbp-l-project-details-title span { border-bottom: 1px solid #747474; display: inline-block; margin: 0 0 -1px; font: 400 16px/36px "Open Sans Condensed", sans-serif; padding: 0 5px 0 0 } .cbp-l-project-desc-text { font: 400 16px/20px "Open Sans Condensed", sans-serif; color: #555; margin-bottom: 20px } .cbp-l-project-details-title { border-bottom: 1px solid #cdcdcd; margin-bottom: 19px; color: #444 } .cbp-l-project-details-list { margin: 0; padding: 0; list-style: none } .cbp-l-project-details-list>div, .cbp-l-project-details-list>li { border-bottom: 1px dotted #DFDFDF; padding: inherit; color: #666; font: 400 14px/30px "Open Sans Condensed", sans-serif } .cbp-l-project-details-list>div:last-child, .cbp-l-project-details-list>li:last-child { border: none } .cbp-l-project-details-list strong { display: inline-block; color: #696969; font-weight: 600; min-width: 100px } .cbp-l-project-details-visit { color: #FFF; float: right; clear: both; text-decoration: none; font: 400 11px/18px "Open Sans Condensed", sans-serif; margin-top: 25px; background-color: #62B57B; padding: 8px 19px; text-transform: uppercase; letter-spacing: .5px } .cbp-l-project-details-visit:hover { opacity: .9; color: #fff } .cbp-l-project-related-wrap { font-size: 0; margin: 0; padding: 0 } .cbp-l-project-related-item { margin-left: 5%; max-width: 30%; float: left } .cbp-l-project-related-item:first-child { margin-left: 0 } .cbp-l-project-related-title { font: 700 14px/18px "Open Sans Condensed", sans-serif; color: #474747; margin-top: 20px } .cbp-l-project-related-link { text-decoration: none } .cbp-l-project-related-link:hover { opacity: .9 } .cbp-l-member-img { float: left; width: 40%; margin-top: 20px } .cbp-l-member-img img { width: auto; max-width: 100%; height: auto; display: inline-block; border: 0 } .cbp-popup-singlePageInline-close .cbp-popup-singlePageInline:after, .cbp-popup-singlePageInline-ready:after { display: none; visibility: hidden } .cbp-l-member-info { margin-top: 20px; padding-left: 25px; float: left; width: 60% } @media only screen and (max-width:768px) { .cbp-l-member-img { width: 100%; text-align: center } .cbp-l-member-info { width: 100%; padding-left: 0 } } .cbp-l-member-name { font: 400 28px/28px "Open Sans Condensed", sans-serif; color: #474747 } .cbp-l-member-position { font: 400 13px/21px "Open Sans Condensed", sans-serif; color: #888; margin-top: 6px } .cbp-l-member-desc { font: 400 12px/18px "Open Sans Condensed", sans-serif; margin-top: 25px; color: #474747 } .cbp-popup-singlePageInline-open { -webkit-transition: height .5s 0s!important; transition: height .5s 0s!important } .cbp-popup-singlePageInline-open .cbp-item { -webkit-transition: -webkit-transform .5s 0s!important; transition: transform .5s 0s!important } .cbp-popup-singlePageInline-close .cbp-popup-singlePageInline .cbp-popup-content, .cbp-popup-singlePageInline-close .cbp-popup-singlePageInline .cbp-popup-navigation { -webkit-transition-delay: 0; transition-delay: 0 } .cbp-popup-singlePageInline { width: 100%; position: absolute; top: 0; left: 0; z-index: 0; overflow: hidden } .cbp-popup-singlePageInline .cbp-popup-content { opacity: 0; width: 100%; z-index: 1; min-height: 300px } .cbp-popup-singlePageInline .cbp-popup-content, .cbp-popup-singlePageInline .cbp-popup-navigation { -webkit-transition: opacity .4s ease-in .2s; transition: opacity .4s ease-in .2s } .cbp-popup-singlePageInline .cbp-popup-navigation { opacity: 0; position: absolute; top: 0; right: 0; z-index: 2; width: 40px; height: 40px } .cbp-popup-singlePageInline .cbp-popup-close { background: url(../img/cbp-sprite.png) -92px 0 no-repeat; height: 40px; width: 40px; right: 20px; top: 30px } .cbp-popup-singlePageInline .cbp-popup-close:hover { opacity: .7 } .cbp-popup-singlePageInline-ready { z-index: 4 } .cbp-popup-singlePageInline-ready .cbp-popup-content, .cbp-popup-singlePageInline-ready .cbp-popup-navigation { opacity: 1 } .cbp-singlePageInline-active { opacity: .6!important } .cbp-l-inline { margin: 20px 0; overflow: hidden; background: #FAFAFA; padding: 30px } .cbp-l-inline-left { float: left; width: 44% } .cbp-l-project-img { max-width: 100% } .cbp-l-inline-right { float: right; width: 56%; padding-left: inherit } @media only screen and (max-width:768px) { .cbp-l-inline-left { width: 100%; text-align: center; margin-top: 40px } .cbp-l-inline-right { width: 100%; padding-left: 0; margin-top: 20px } } .cbp-l-inline-title { font: 400 28px/30px "Open Sans Condensed", sans-serif; color: #474747 } .cbp-l-inline-subtitle { font: 400 13px/21px "Open Sans Condensed", sans-serif; color: #888; margin-top: 7px } .cbp-l-inline-desc { font: 400 13px/20px "Open Sans Condensed", sans-serif; color: #474747; margin-top: 25px; margin-bottom: 20px } .cbp-l-inline-view-wrap { text-align: right } .cbp-l-loadMore-bgbutton, .cbp-l-loadMore-button, .cbp-l-loadMore-text { text-align: center } .cbp-l-inline-view { font: 400 13px/35px "Open Sans Condensed", sans-serif; color: #9C9C9C; margin-top: 40px; display: inline-block; padding: 0 20px; border: 1px solid #ccc; text-decoration: none } .cbp-l-inline-view:hover { color: #757575 } .cbp-l-inline-details { margin-bottom: 15px; font: 13px/22px "Open Sans Condensed", sans-serif } .cbp-l-loadMore-button-defaultText, .cbp-l-loadMore-defaultText { display: block } .cbp-l-loadMore-button-loadingText, .cbp-l-loadMore-button-noMoreLoading, .cbp-l-loadMore-loadingText, .cbp-l-loadMore-noMoreLoading { display: none } .cbp-l-loadMore-loading .cbp-l-loadMore-button-loadingText, .cbp-l-loadMore-loading .cbp-l-loadMore-loadingText { display: block } .cbp-l-loadMore-loading .cbp-l-loadMore-button-defaultText, .cbp-l-loadMore-loading .cbp-l-loadMore-button-noMoreLoading, .cbp-l-loadMore-loading .cbp-l-loadMore-defaultText, .cbp-l-loadMore-loading .cbp-l-loadMore-noMoreLoading { display: none } .cbp-l-loadMore-stop .cbp-l-loadMore-button-noMoreLoading, .cbp-l-loadMore-stop .cbp-l-loadMore-noMoreLoading { display: block } .cbp-l-loadMore-stop .cbp-l-loadMore-button-defaultText, .cbp-l-loadMore-stop .cbp-l-loadMore-button-loadingText, .cbp-l-loadMore-stop .cbp-l-loadMore-defaultText, .cbp-l-loadMore-stop .cbp-l-loadMore-loadingText { display: none } .cbp-l-loadMore-bgbutton .cbp-l-loadMore-link { border: 1px solid #DEDEDE; color: #7E7B7B; display: inline-block; font: 400 13px/40px Lato, sans-serif; min-width: 80px; text-decoration: none; padding: 0 50px; margin-top: 50px; outline: 0; box-shadow: none; letter-spacing: 1px; -webkit-transition: color .25s; transition: color .25s } .cbp-l-loadMore-bgbutton .cbp-l-loadMore-link.cbp-l-loadMore-loading, .cbp-l-loadMore-bgbutton .cbp-l-loadMore-link:hover { color: #B0B0B0 } .cbp-l-loadMore-bgbutton .cbp-l-loadMore-link.cbp-l-loadMore-stop { color: #B0B0B0; cursor: default } .cbp-l-loadMore-button .cbp-l-loadMore-button-link, .cbp-l-loadMore-button .cbp-l-loadMore-link { border-bottom: 1px solid #DEDEDE; color: #444; display: inline-block; font: 400 16px/36px "Open Sans Condensed", sans-serif; min-width: 80px; text-decoration: none; padding: 0 30px; outline: 0; margin-top: 40px; box-shadow: none; -webkit-transition: color .25s; transition: color .25s } .cbp-l-loadMore-button .cbp-l-loadMore-button-link.cbp-l-loadMore-loading, .cbp-l-loadMore-button .cbp-l-loadMore-button-link:hover, .cbp-l-loadMore-button .cbp-l-loadMore-link.cbp-l-loadMore-loading, .cbp-l-loadMore-button .cbp-l-loadMore-link:hover { color: #B0B0B0 } .cbp-l-loadMore-button .cbp-l-loadMore-button-link.cbp-l-loadMore-button-stop, .cbp-l-loadMore-button .cbp-l-loadMore-button-link.cbp-l-loadMore-stop, .cbp-l-loadMore-button .cbp-l-loadMore-link.cbp-l-loadMore-button-stop, .cbp-l-loadMore-button .cbp-l-loadMore-link.cbp-l-loadMore-stop { cursor: default; color: #B0B0B0 } .cbp-l-loadMore-text .cbp-l-loadMore-link, .cbp-l-loadMore-text .cbp-l-loadMore-text-link { font: 400 15px "Open Sans Condensed", sans-serif; color: #7E7B7B; text-decoration: none; cursor: pointer; margin-top: 50px; display: block } .cbp-l-loadMore-text .cbp-l-loadMore-stop, .cbp-l-loadMore-text .cbp-l-loadMore-text-stop { color: #B0B0B0; cursor: default } .cbp-mode-slider { -webkit-transition: height .35s; transition: height .35s } .cbp-mode-slider .cbp-item, .cbp-mode-slider .cbp-wrapper { -webkit-transition: -webkit-transform .35s; transition: transform .35s } .cbp-mode-slider .cbp-wrapper { cursor: -webkit-grab; cursor: -o-grab; cursor: -ms-grab; cursor: grab } .cbp-mode-slider-dragStart * { cursor: move!important; cursor: -ms-grabbing!important; cursor: -webkit-grabbing!important; cursor: -moz-grabbing!important; cursor: grabbing!important } .cbp-mode-slider-dragStart .cbp-wrapper { -webkit-transition: none; transition: none } .cbp-nav-next, .cbp-nav-prev { position: relative; background: #7c8b90; cursor: pointer; display: inline-block; margin-left: 1px; height: 22px; width: 21px } .cbp-nav-next { border-radius: 0 2px 2px 0 } .cbp-nav-prev { border-radius: 2px 0 0 2px } .cbp-nav-next:hover, .cbp-nav-prev:hover { opacity: .8 } .cbp-nav-next:after, .cbp-nav-prev:after { content: ''; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; background: url(../img/cbp-sprite.png) no-repeat; height: 10px; width: 7px } .cbp-nav-next:after { background-position: -134px 0 } .cbp-nav-prev:after { background-position: -134px -12px } .cbp-nav-stop { opacity: .5!important; cursor: default!important } .cbp-nav { user-select: none } .cbp-nav-controls { position: absolute; top: -51px; right: 0; z-index: 100 } .cbp-nav-pagination { position: absolute; bottom: -30px; right: 0; z-index: 100; left: 0; text-align: center } .cbp-nav-pagination-item, .cbp-pagination-item { display: inline-block; position: relative; cursor: pointer } .cbp-nav-pagination-item { width: 10px; height: 10px; border-radius: 50%; margin: 0 4px; background: #c2c2c2; -webkit-transition: background .5s; transition: background .5s } .cbp-nav-pagination-active { background: #797979 } .cbp-pagination-item { max-width: 100px; margin-top: 10px; margin-right: 5px } .cbp-pagination-item img { display: block; width: 100%; height: auto; border: 0 } .cbp-pagination-item:after { content: ''; position: absolute; top: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, .5); -webkit-transition: background .5s ease-in-out; transition: background .5s ease-in-out } .cbp-pagination-active:after { background: 0 0 } .cbp-slider-item, .cbp-slider-wrap { margin: 0; padding: 0; list-style-type: none } .cbp-slider .cbp-nav-controls { position: static } .cbp-slider .cbp-nav-next, .cbp-slider .cbp-nav-prev { background: 0 0; position: absolute; margin: auto; top: 0; bottom: 0; z-index: 100; width: 44px; height: 44px } .cbp-slider .cbp-nav-next { right: 25px; left: auto } .cbp-slider .cbp-nav-prev { left: 25px; right: auto } .cbp-slider .cbp-nav-next:after, .cbp-slider .cbp-nav-prev:after { background: url(../img/cbp-sprite.png) no-repeat; width: 44px; height: 44px } .cbp-slider .cbp-nav-next:after { background-position: -46px -92px } .cbp-slider .cbp-nav-next:hover:after { background-position: -46px -46px } .cbp-slider .cbp-nav-prev:after { background-position: 0 -92px } .cbp-slider .cbp-nav-prev:hover:after { background-position: 0 -46px } .cbp-slider .cbp-nav-pagination { text-align: right; bottom: 20px; right: 25px; left: auto } .cbp-slider-edge .cbp-nav-controls { position: static } .cbp-slider-edge .cbp-nav-next, .cbp-slider-edge .cbp-nav-prev { background: 0 0; position: absolute; margin: auto; top: 0; bottom: 0; z-index: 100; width: 44px; height: 44px } .cbp-slider-edge .cbp-nav-next { right: 0; left: auto } .cbp-slider-edge .cbp-nav-prev { left: 0; right: auto } .cbp-slider-edge .cbp-nav-next:after, .cbp-slider-edge .cbp-nav-prev:after { background: url(../img/cbp-sprite.png) no-repeat; width: 9px; height: 16px } .cbp-slider-edge .cbp-nav-next:after { background-position: -134px -24px } .cbp-slider-edge .cbp-nav-prev:after { background-position: -134px -42px } .cbp-slider-edge .cbp-nav-pagination { bottom: -50px } .cbp-slider-edge .cbp-nav-pagination-item { border: 2px solid #0f0f0f; opacity: .4; background: 0 0 } .cbp-slider-edge .cbp-nav-pagination-active { background: #000 } .cbp-slider-inline { position: relative } .cbp-slider-inline .cbp-slider-item { position: absolute; width: 100%; top: 0; -webkit-transition: left .5s; transition: left .5s } .cbp-slider-inline .cbp-slider-item--active { position: relative; z-index: 2 } .cbp-slider-wrapper { position: relative; overflow: hidden } .cbp-slider-controls { position: absolute; top: 0; right: 0; z-index: 100; opacity: 0; -webkit-transition: opacity .7s ease-in-out; transition: opacity .7s ease-in-out } .cbp-slider-inline-ready .cbp-slider-controls { opacity: 1 } .cbp-l-grid-blog-comments:hover, .cbp-l-grid-slider-team-social a:hover, .cbp-social-fb:hover, .cbp-social-googleplus:hover, .cbp-social-pinterest:hover, .cbp-social-twitter:hover { opacity: .8 } .cbp-slider-next, .cbp-slider-prev { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; float: left; cursor: pointer; position: relative; width: 36px; height: 36px; background: #547EB1 } .cbp-slider-next { margin-left: 1px } .cbp-slider-next:after, .cbp-slider-prev:after { content: ''; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; background: url(../img/cbp-sprite.png) no-repeat; width: 9px; height: 16px } .cbp-slider-next:after { background-position: -134px -60px } .cbp-slider-prev:after { background-position: -134px -78px } .cbp-l-grid-agency .cbp-caption:after { position: absolute; content: ''; width: 0; height: 0; border-bottom: 10px solid #fff; border-right: 10px solid transparent; border-left: 10px solid transparent; bottom: 0; left: 50%; margin-left: -5px; z-index: 1 } .cbp-l-grid-agency.cbp-caption-zoom .cbp-caption:hover .cbp-caption-defaultWrap { -webkit-transform: scale(1.15); transform: scale(1.15) } .cbp-l-grid-agency-title { margin-top: 18px; font: 700 17px/24px Lato, sans-serif; color: #666; text-align: center; padding: 0 4px } .cbp-item:hover .cbp-l-grid-agency-title { color: #222 } .cbp-l-grid-agency-desc { font: 400 12px/21px "Open Sans Condensed", sans-serif; color: #aaa; text-align: center } @media only screen and (max-width:480px) { .cbp-l-grid-agency-title { font-size: 15px; line-height: 21px } } .cbp-l-grid-work.cbp-caption-zoom .cbp-caption-activeWrap { background-color: rgba(0, 0, 0, .7) } .cbp-l-grid-work .cbp-item { padding: 3px } .cbp-l-grid-work .cbp-item-wrapper { background-color: #fff; box-shadow: 0 1px 1px rgba(0, 0, 0, .2); padding: 7px 7px 27px; border-top: 1px solid #F4F4F4 } .cbp-l-grid-work-title { margin-top: 17px; font: 400 17px/25px "Roboto Condensed", sans-serif; color: #607D8B; text-align: center; text-transform: uppercase; display: block } .cbp-l-grid-work-title:hover { color: #365D67 } .cbp-l-grid-work-desc { font: 400 11px/16px "Open Sans Condensed", sans-serif; color: #888; text-align: center; text-transform: uppercase } @media only screen and (max-width:480px) { .cbp-l-grid-work-title { font-size: 15px; line-height: 21px; margin-top: 15px } .cbp-l-grid-work .cbp-item-wrapper { padding-bottom: 18px } } .cbp-l-grid-blog-title { font: 400 18px/30px "Open Sans Condensed", sans-serif; color: #444; display: block; margin-top: 17px } .cbp-l-grid-blog-comments, .cbp-l-grid-blog-date { font: 400 12px/18px "Open Sans Condensed", sans-serif } .cbp-l-grid-blog-title:hover { color: #787878 } .cbp-l-grid-blog-date { color: #787878; display: inline-block } .cbp-l-grid-blog-comments { color: #3C6FBB; display: inline-block } .cbp-l-grid-blog-desc { font: 400 13px/18px "Open Sans Condensed", sans-serif; color: #9B9B9B; margin-top: 9px } .cbp-l-grid-blog-split { margin: 0 4px; font: 400 13px/16px "Open Sans Condensed", sans-serif; color: #787878; display: inline-block } .cbp-l-grid-clients { height: 180px } .cbp-l-clients-title-block { font: 400 32px/53px Roboto, sans-serif; color: #666464; text-align: center; margin-bottom: 40px } .cbp-l-grid-faq .cbp-item { width: 100% } .cbp-l-grid-projects-title { font: 700 16px/21px "Open Sans Condensed", sans-serif; color: #474747; margin-top: 15px } .cbp-l-grid-projects-desc { font: 400 16px/18px "Open Sans Condensed", sans-serif; color: #444; margin-top: 5px } @media only screen and (max-width:480px) { .cbp-l-grid-projects-title { margin-top: 12px } .cbp-l-grid-projects-desc { margin-top: 3px } } .cbp-l-grid-masonry-projects .cbp-caption-activeWrap { background-color: #59a3b6; background-color: rgba(89, 163, 182, .95) } .cbp-l-grid-masonry-projects .cbp-l-caption-buttonLeft, .cbp-l-grid-masonry-projects .cbp-l-caption-buttonRight { background-color: #545454 } .cbp-l-grid-masonry-projects-title { font: 500 15px/22px Roboto, sans-serif; color: #59a3b6; text-align: center; display: block; margin-top: 12px } .cbp-l-grid-masonry-projects-title:hover { color: #457C8B } .cbp-l-grid-masonry-projects-desc { font: 400 12px/18px Roboto, sans-serif; color: #b2b2b2; text-align: center } .cbp-l-grid-team-name { font: 400 17px/24px "Open Sans Condensed", sans-serif; color: #456297; display: block; text-align: center; margin-top: 18px } .cbp-l-grid-team-name:hover { color: #34425C } .cbp-l-grid-team-position { font: italic 400 13px/21px "Open Sans Condensed", sans-serif; color: #999; text-align: center } @media only screen and (max-width:480px) { .cbp-l-grid-team-name { font-size: 15px; line-height: 22px; margin-top: 13px } .cbp-l-grid-team-position { font-size: 12px; line-height: 18px } } .cbp-l-grid-mosaic-flat .cbp-caption-activeWrap { background-color: #64C28E; background-color: rgba(101, 199, 150, .95) } .cbp-l-grid-mosaic-flat .cbp-l-caption-title { color: #FFF; font: 400 14px/21px Lato, sans-serif; text-transform: uppercase; letter-spacing: 2px; display: inline-block } .cbp-l-grid-mosaic-flat .cbp-l-caption-title:after { content: ''; display: block; width: 40%; height: 1px; background-color: #fff; margin: 8px auto 0 } @media only screen and (max-width:800px) { .cbp-l-grid-mosaic-flat .cbp-l-caption-title:after { display: none } } .cbp-l-grid-mosaic-projects .cbp-caption-activeWrap { background-color: #59a3b6; background-color: rgba(89, 163, 182, .97) } .cbp-l-grid-mosaic .cbp-caption-activeWrap { background-color: #FFEA71; background-color: rgba(255, 234, 113, .95) } .cbp-l-grid-mosaic .cbp-l-caption-title { color: #5A5A5A; font: 500 18px/22px Roboto, sans-serif; text-transform: uppercase; margin-bottom: 5px } .cbp-l-grid-mosaic .cbp-l-caption-desc { color: #585858; font: 400 13px/20px Roboto, sans-serif } @media only screen and (max-width:480px) { .cbp-l-grid-mosaic .cbp-l-caption-title { font-size: 16px; line-height: 22px; margin-bottom: 0 } .cbp-l-grid-mosaic .cbp-l-caption-desc { font-size: 12px; line-height: 18px } } .cbp-l-slider-title-block { border-bottom: 1px solid #cdcdcd; margin-bottom: 22px } .cbp-l-slider-title-block div { padding: 0 2px 6px 0; display: inline-block; border-bottom: 1px solid #a9a5a5; color: #5e5e5e; margin-bottom: -1px; font: 15px/21px Roboto, sans-serif } .cbp-l-grid-slider-team-name { float: left; font: 20px/30px Roboto, sans-serif; color: #494949; margin-top: 16px } .cbp-l-grid-slider-team-position { clear: both; font: 14px/21px Roboto, sans-serif; color: #A6A6A6 } .cbp-l-grid-slider-team-desc { font: 13px/20px Roboto, sans-serif; color: #969696; margin-top: 15px } .cbp-l-grid-slider-team-social { float: right; margin-top: 22px } .cbp-l-grid-slider-team-social a { margin-left: 4px } @media only screen and (max-width:600px) { .cbp-l-grid-slider-team-wrap { float: left; width: 100%; margin-bottom: 10px } .cbp-l-grid-slider-team-name { font-size: 17px; line-height: 26px; width: 100%; margin-top: 12px; text-align: center } .cbp-l-grid-slider-team-social { width: 100%; text-align: center; margin-top: 8px } .cbp-l-grid-slider-team-position { font-size: 13px; line-height: 20px; text-align: center } .cbp-l-grid-slider-team-desc { font-size: 12px; line-height: 18px; margin-top: 10px; text-align: center } } .cbp-l-slider-testimonials-wrap { background: #f8f9f9; padding: 80px 0 110px; border-width: 1px 0; border-style: solid; border-color: #dce1e2 } .cbp-l-grid-slider-testimonials-body { color: #424242; max-width: 800px; margin: 0 auto; font: 20px/32px sans-serif; text-align: center; padding: 0 40px } .cbp-l-grid-slider-testimonials-footer { font: 12px/19px Roboto, sans-serif; color: #777; text-align: center; margin-bottom: 10px; margin-top: 30px } .cbp-l-grid-tabs { height: 100px } .cbp-l-grid-tabs .cbp-item { font: 16px/24px 'Open Sans Condensed', sans-serif; max-width: 700px; width: 100%; margin: 0 auto; right: 0; text-align: center; color: #5a5a5a } .cbp-l-testimonials-title-block { position: relative; text-align: center; font: 26px/36px Roboto, sans-serif; color: #E7E7E7; margin-bottom: 60px } .cbp-l-testimonials-title-block:after { content: ''; position: absolute; margin: 0 auto; width: 23px; height: 2px; bottom: -6px; background-color: #C2C2C2; left: 0; right: 0 } .cbp-l-testimonials-wrap { background: #2D2D2D; padding: 60px 0 110px } .cbp-l-grid-testimonials-body { color: #e7e7e7; max-width: 800px; margin: 0 auto; font: 20px/32px Roboto, sans-serif; text-align: center; padding: 0 20px } .cbp-l-grid-testimonials-footer { font: 12px/19px Roboto, sans-serif; color: #C2C2C2; text-align: center; margin-bottom: 40px; margin-top: 35px } .cbp-search { position: relative; width: 220px; margin-bottom: 40px } .cbp-search-icon, .cbp-search-nothing { position: absolute; top: 0; text-align: center } .cbp-search .cbp-search-nothing { display: none } .cbp-search-icon { width: 32px; height: 100%; right: 0; cursor: pointer; pointer-events: none } .cbp-search-icon:after { content: ''; display: block; background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNzkyIDE3OTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZmlsbD0iIzczNzM3MyIgZD0iTTEyMTYgODMycTAtMTg1LTEzMS41LTMxNi41VDc2OCAzODQgNDUxLjUgNTE1LjUgMzIwIDgzMnQxMzEuNSAzMTYuNVQ3NjggMTI4MHQzMTYuNS0xMzEuNVQxMjE2IDgzMnptNTEyIDgzMnEwIDUyLTM4IDkwdC05MCAzOHEtNTQgMC05MC0zOGwtMzQzLTM0MnEtMTc5IDEyNC0zOTkgMTI0LTE0MyAwLTI3My41LTU1LjV0LTIyNS0xNTAtMTUwLTIyNVQ2NCA4MzJ0NTUuNS0yNzMuNSAxNTAtMjI1IDIyNS0xNTBUNzY4IDEyOHQyNzMuNSA1NS41IDIyNSAxNTAgMTUwIDIyNVQxNDcyIDgzMnEwIDIyMC0xMjQgMzk5bDM0MyAzNDNxMzcgMzcgMzcgOTB6Ii8+PC9zdmc+) center center no-repeat; width: 100%; height: 100%; pointer-events: none } .cbp-search-input { height: 36px; padding: 0 32px 0 12px; margin: 0; border-radius: 1px; border: 1px solid #c6c3c4; font: 400 12px "Open Sans Condensed", sans-serif; width: 100% } .cbp-search-input[value]+.cbp-search-icon { pointer-events: auto } .cbp-search-input[value]+.cbp-search-icon:after { background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNzkyIDE3OTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZmlsbD0iIzczNzM3MyIgZD0iTTE0OTAgMTMyMnEwIDQwLTI4IDY4bC0xMzYgMTM2cS0yOCAyOC02OCAyOHQtNjgtMjhsLTI5NC0yOTQtMjk0IDI5NHEtMjggMjgtNjggMjh0LTY4LTI4bC0xMzYtMTM2cS0yOC0yOC0yOC02OHQyOC02OGwyOTQtMjk0LTI5NC0yOTRxLTI4LTI4LTI4LTY4dDI4LTY4bDEzNi0xMzZxMjgtMjggNjgtMjh0NjggMjhsMjk0IDI5NCAyOTQtMjk0cTI4LTI4IDY4LTI4dDY4IDI4bDEzNiAxMzZxMjggMjggMjggNjh0LTI4IDY4bC0yOTQgMjk0IDI5NCAyOTRxMjggMjggMjggNjh6Ii8+PC9zdmc+) } .cbp-search-nothing { padding: 0 0 30px; width: 100%; font: 13px "Open Sans Condensed", sans-serif } @media only screen and (max-width:600px) { .cbp-search { width: 100% } } .cbp-l-project-social { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex } .cbp-social-fb, .cbp-social-googleplus, .cbp-social-pinterest, .cbp-social-twitter { margin-right: 9px; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex } .cbp-social-fb:focus, .cbp-social-googleplus:focus, .cbp-social-pinterest:focus, .cbp-social-twitter:focus { outline: 0 } .cbp-social-fb path { fill: #415C9B } .cbp-social-twitter path { fill: #55acee } .cbp-social-googleplus path { fill: #E57371 } .cbp-social-pinterest path { fill: #cb2027 } .cbp-popup-content-wrap { position: absolute; top: 0; right: 0; bottom: 0; left: 0; overflow-y: hidden; overflow-x: hidden; -webkit-overflow-scrolling: touch } .cbp-popup-transitionend .cbp-popup-content-wrap { overflow-y: scroll } .cbp-popup-transitionend { overflow-y: hidden; }
ikehawk10/ikehawk10.github.io
contents/portfolio/css/cubeportfolio.css
CSS
apache-2.0
97,787
#include "stdafx.h" #include "NET_Common.h" #include "net_client.h" #include "net_server.h" #include "net_messages.h" #include "NET_Log.h" #include "../xr_3da/xrGame/battleye.h" #pragma warning(push) #pragma warning(disable:4995) #include <malloc.h> #include "dxerr.h" //#pragma warning(pop) static INetLog* pClNetLog = NULL; #define BASE_PORT_LAN_SV 5445 #define BASE_PORT_LAN_CL 5446 #define BASE_PORT 0 #define END_PORT 65535 void dump_URL (LPCSTR p, IDirectPlay8Address* A) { string256 aaaa; DWORD aaaa_s = sizeof(aaaa); R_CHK (A->GetURLA(aaaa,&aaaa_s)); Log (p,aaaa); } // INetQueue::INetQueue() #ifdef PROFILE_CRITICAL_SECTIONS :cs(MUTEX_PROFILE_ID(INetQueue)) #endif // PROFILE_CRITICAL_SECTIONS { unused.reserve (128); for (int i=0; i<16; i++) unused.push_back (xr_new<NET_Packet>()); } INetQueue::~INetQueue() { cs.Enter (); u32 it; for (it=0; it<unused.size(); it++) xr_delete(unused[it]); for (it=0; it<ready.size(); it++) xr_delete(ready[it]); cs.Leave (); } static u32 LastTimeCreate = 0; void INetQueue::CreateCommit(NET_Packet* P) { cs.Enter (); ready.push_back (P); cs.Leave (); } NET_Packet* INetQueue::CreateGet() { NET_Packet* P = 0; cs.Enter (); if (unused.empty()) { P = xr_new<NET_Packet> (); //. ready.push_back (xr_new<NET_Packet> ()); //. P = ready.back (); LastTimeCreate = GetTickCount(); } else { P = unused.back(); //. ready.push_back (unused.back()); unused.pop_back (); //. P = ready.back (); } cs.Leave (); return P; } /* NET_Packet* INetQueue::Create (const NET_Packet& _other) { NET_Packet* P = 0; cs.Enter (); //#ifdef _DEBUG // Msg ("- INetQueue::Create - ready %d, unused %d", ready.size(), unused.size()); //#endif if (unused.empty()) { ready.push_back (xr_new<NET_Packet> ()); P = ready.back (); //--------------------------------------------- LastTimeCreate = GetTickCount(); //--------------------------------------------- } else { ready.push_back (unused.back()); unused.pop_back (); P = ready.back (); } CopyMemory (P,&_other,sizeof(NET_Packet)); cs.Leave (); return P; } */ NET_Packet* INetQueue::Retreive () { NET_Packet* P = 0; cs.Enter (); //#ifdef _DEBUG // Msg ("INetQueue::Retreive - ready %d, unused %d", ready.size(), unused.size()); //#endif if (!ready.empty()) P = ready.front(); //--------------------------------------------- else { u32 tmp_time = GetTickCount()-60000; u32 size = unused.size(); if ((LastTimeCreate < tmp_time) && (size > 32)) { xr_delete(unused.back()); unused.pop_back(); } } //--------------------------------------------- cs.Leave (); return P; } void INetQueue::Release () { cs.Enter (); //#ifdef _DEBUG // Msg ("INetQueue::Release - ready %d, unused %d", ready.size(), unused.size()); //#endif VERIFY (!ready.empty()); //--------------------------------------------- u32 tmp_time = GetTickCount()-60000; u32 size = unused.size(); if ((LastTimeCreate < tmp_time) && (size > 32)) { xr_delete(ready.front()); } else unused.push_back(ready.front()); //--------------------------------------------- ready.pop_front (); cs.Leave (); } // const u32 syncQueueSize = 512; const int syncSamples = 256; class XRNETSERVER_API syncQueue { u32 table [syncQueueSize]; u32 write; u32 count; public: syncQueue() { clear(); } IC void push (u32 value) { table[write++] = value; if (write == syncQueueSize) write = 0; if (count <= syncQueueSize) count++; } IC u32* begin () { return table; } IC u32* end () { return table+count; } IC u32 size () { return count; } IC void clear () { write=0; count=0; } } net_DeltaArray; //------- XRNETSERVER_API Flags32 psNET_Flags = {0}; XRNETSERVER_API int psNET_ClientUpdate = 30; // FPS XRNETSERVER_API int psNET_ClientPending = 2; XRNETSERVER_API char psNET_Name[32] = "Player"; XRNETSERVER_API BOOL psNET_direct_connect = FALSE; // {0218FA8B-515B-4bf2-9A5F-2F079D1759F3} static const GUID NET_GUID = { 0x218fa8b, 0x515b, 0x4bf2, { 0x9a, 0x5f, 0x2f, 0x7, 0x9d, 0x17, 0x59, 0xf3 } }; // {8D3F9E5E-A3BD-475b-9E49-B0E77139143C} static const GUID CLSID_NETWORKSIMULATOR_DP8SP_TCPIP = { 0x8d3f9e5e, 0xa3bd, 0x475b, { 0x9e, 0x49, 0xb0, 0xe7, 0x71, 0x39, 0x14, 0x3c } }; static HRESULT WINAPI Handler (PVOID pvUserContext, DWORD dwMessageType, PVOID pMessage) { IPureClient* C = (IPureClient*)pvUserContext; return C->net_Handler(dwMessageType,pMessage); } //------------------------------------------------------------------------------ void IPureClient::_SendTo_LL( const void* data, u32 size, u32 flags, u32 timeout ) { IPureClient::SendTo_LL( const_cast<void*>(data), size, flags, timeout ); } //------------------------------------------------------------------------------ void IPureClient::_Recieve( const void* data, u32 data_size, u32 /*param*/ ) { MSYS_PING* cfg = (MSYS_PING*)data; if( (data_size>2*sizeof(u32)) && (cfg->sign1==0x12071980) && (cfg->sign2==0x26111975) ) { // Internal system message if( (data_size == sizeof(MSYS_PING)) ) { // It is reverted(server) ping u32 time = TimerAsync( device_timer ); u32 ping = time - (cfg->dwTime_ClientSend); u32 delta = cfg->dwTime_Server + ping/2 - time; net_DeltaArray.push ( delta ); Sync_Average (); return; } if ( data_size == sizeof(MSYS_CONFIG) ) { MSYS_CONFIG* msys_cfg = (MSYS_CONFIG*)data; if ( msys_cfg->is_battleye ) { #ifdef BATTLEYE if ( !TestLoadBEClient() ) { net_Connected = EnmConnectionFails; return; } #endif // BATTLEYE } net_Connected = EnmConnectionCompleted; return; } Msg( "! Unknown system message" ); return; } else if( net_Connected == EnmConnectionCompleted ) { // one of the messages - decompress it if( psNET_Flags.test( NETFLAG_LOG_CL_PACKETS ) ) { if( !pClNetLog ) pClNetLog = xr_new<INetLog>("logs\\net_cl_log.log", timeServer()); if( pClNetLog ) pClNetLog->LogData( timeServer(), const_cast<void*>(data), data_size, TRUE ); } OnMessage( const_cast<void*>(data), data_size ); } } //============================================================================== IPureClient::IPureClient (CTimer* timer): net_Statistic(timer) #ifdef PROFILE_CRITICAL_SECTIONS ,net_csEnumeration(MUTEX_PROFILE_ID(IPureClient::net_csEnumeration)) #endif // PROFILE_CRITICAL_SECTIONS { NET = NULL; net_Address_server = NULL; net_Address_device = NULL; device_timer = timer; net_TimeDelta_User = 0; net_Time_LastUpdate = 0; net_TimeDelta = 0; net_TimeDelta_Calculated = 0; pClNetLog = NULL;//xr_new<INetLog>("logs\\net_cl_log.log", timeServer()); } IPureClient::~IPureClient () { xr_delete(pClNetLog); pClNetLog = NULL; psNET_direct_connect = FALSE; } void gen_auth_code(); BOOL IPureClient::Connect (LPCSTR options) { R_ASSERT (options); net_Disconnected = FALSE; if(!psNET_direct_connect && !strstr(options,"localhost") ) { gen_auth_code (); } if(!psNET_direct_connect) { // string256 server_name = ""; // strcpy (server_name,options); if (strchr(options, '/')) strncpy(server_name,options, strchr(options, '/')-options); if (strchr(server_name,'/')) *strchr(server_name,'/') = 0; string64 password_str = ""; if (strstr(options, "psw=")) { const char* PSW = strstr(options, "psw=") + 4; if (strchr(PSW, '/')) strncpy(password_str, PSW, strchr(PSW, '/') - PSW); else strcpy(password_str, PSW); } string64 user_name_str = ""; if (strstr(options, "name=")) { const char* NM = strstr(options, "name=") + 5; if (strchr(NM, '/')) strncpy(user_name_str, NM, strchr(NM, '/') - NM); else strcpy(user_name_str, NM); } string64 user_pass = ""; if (strstr(options, "pass=")) { const char* UP = strstr(options, "pass=") + 5; if (strchr(UP, '/')) strncpy(user_pass, UP, strchr(UP, '/') - UP); else strcpy(user_pass, UP); } int psSV_Port = BASE_PORT_LAN_SV; if (strstr(options, "port=")) { string64 portstr; strcpy(portstr, strstr(options, "port=")+5); if (strchr(portstr,'/')) *strchr(portstr,'/') = 0; psSV_Port = atol(portstr); clamp(psSV_Port, int(BASE_PORT), int(END_PORT)); }; BOOL bPortWasSet = FALSE; int psCL_Port = BASE_PORT_LAN_CL; if (strstr(options, "portcl=")) { string64 portstr; strcpy(portstr, strstr(options, "portcl=")+7); if (strchr(portstr,'/')) *strchr(portstr,'/') = 0; psCL_Port = atol(portstr); clamp(psCL_Port, int(BASE_PORT), int(END_PORT)); bPortWasSet = TRUE; }; // Msg("* Client connect on port %d\n",psNET_Port); // net_Connected = EnmConnectionWait; net_Syncronised = FALSE; net_Disconnected= FALSE; //--------------------------- string1024 tmp=""; // HRESULT CoInitializeExRes = CoInitializeEx(NULL, 0); // if (CoInitializeExRes != S_OK && CoInitializeExRes != S_FALSE) // { // DXTRACE_ERR(tmp, CoInitializeExRes); // CHK_DX(CoInitializeExRes); // }; //--------------------------- // Create the IDirectPlay8Client object. HRESULT CoCreateInstanceRes = CoCreateInstance (CLSID_DirectPlay8Client, NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Client, (LPVOID*) &NET); //--------------------------- if (CoCreateInstanceRes != S_OK) { DXTRACE_ERR(tmp, CoCreateInstanceRes ); CHK_DX(CoCreateInstanceRes ); } //--------------------------- // Initialize IDirectPlay8Client object. #ifdef DEBUG R_CHK(NET->Initialize (this, Handler, 0)); #else R_CHK(NET->Initialize (this, Handler, DPNINITIALIZE_DISABLEPARAMVAL )); #endif BOOL bSimulator = FALSE; if (strstr(Core.Params,"-netsim")) bSimulator = TRUE; // Create our IDirectPlay8Address Device Address, --- Set the SP for our Device Address net_Address_device = NULL; R_CHK(CoCreateInstance (CLSID_DirectPlay8Address,NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Address,(LPVOID*) &net_Address_device )); R_CHK(net_Address_device->SetSP(bSimulator? &CLSID_NETWORKSIMULATOR_DP8SP_TCPIP : &CLSID_DP8SP_TCPIP )); // Create our IDirectPlay8Address Server Address, --- Set the SP for our Server Address WCHAR ServerNameUNICODE [256]; R_CHK(MultiByteToWideChar(CP_ACP, 0, server_name, -1, ServerNameUNICODE, 256 )); net_Address_server = NULL; R_CHK(CoCreateInstance (CLSID_DirectPlay8Address,NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Address,(LPVOID*) &net_Address_server )); R_CHK(net_Address_server->SetSP (bSimulator? &CLSID_NETWORKSIMULATOR_DP8SP_TCPIP : &CLSID_DP8SP_TCPIP )); R_CHK(net_Address_server->AddComponent (DPNA_KEY_HOSTNAME, ServerNameUNICODE, 2*u32(wcslen(ServerNameUNICODE) + 1), DPNA_DATATYPE_STRING )); R_CHK(net_Address_server->AddComponent (DPNA_KEY_PORT, &psSV_Port, sizeof(psSV_Port), DPNA_DATATYPE_DWORD )); // Debug // dump_URL ("! cl ", net_Address_device); // dump_URL ("! en ", net_Address_server); // Now set up the Application Description DPN_APPLICATION_DESC dpAppDesc; ZeroMemory (&dpAppDesc, sizeof(DPN_APPLICATION_DESC)); dpAppDesc.dwSize = sizeof(DPN_APPLICATION_DESC); dpAppDesc.guidApplication = NET_GUID; // Setup client info /*strcpy_s( tmp, server_name ); strcat_s( tmp, "/name=" ); strcat_s( tmp, user_name_str ); strcat_s( tmp, "/" );*/ WCHAR ClientNameUNICODE [256]; R_CHK(MultiByteToWideChar (CP_ACP, 0, user_name_str, -1, ClientNameUNICODE, 256 )); { DPN_PLAYER_INFO Pinfo; ZeroMemory (&Pinfo,sizeof(Pinfo)); Pinfo.dwSize = sizeof(Pinfo); Pinfo.dwInfoFlags = DPNINFO_NAME|DPNINFO_DATA; Pinfo.pwszName = ClientNameUNICODE; SClientConnectData cl_data; cl_data.process_id = GetCurrentProcessId(); strcpy_s( cl_data.name, user_name_str ); strcpy_s( cl_data.pass, user_pass ); Pinfo.pvData = &cl_data; Pinfo.dwDataSize = sizeof(cl_data); R_CHK(NET->SetClientInfo (&Pinfo,0,0,DPNSETCLIENTINFO_SYNC)); } if ( stricmp( server_name, "localhost" ) == 0 ) { WCHAR SessionPasswordUNICODE[4096]; if ( xr_strlen( password_str ) ) { CHK_DX(MultiByteToWideChar (CP_ACP, 0, password_str, -1, SessionPasswordUNICODE, 4096 )); dpAppDesc.dwFlags |= DPNSESSION_REQUIREPASSWORD; dpAppDesc.pwszPassword = SessionPasswordUNICODE; }; u32 c_port = u32(psCL_Port); HRESULT res = S_FALSE; while (res != S_OK && c_port <=u32(psCL_Port+100)) { R_CHK(net_Address_device->AddComponent (DPNA_KEY_PORT, &c_port, sizeof(c_port), DPNA_DATATYPE_DWORD )); res = NET->Connect( &dpAppDesc, // pdnAppDesc net_Address_server, // pHostAddr net_Address_device, // pDeviceInfo NULL, // pdnSecurity NULL, // pdnCredentials NULL, 0, // pvUserConnectData/Size NULL, // pvAsyncContext NULL, // pvAsyncHandle DPNCONNECT_SYNC); // dwFlags if (res != S_OK) { // xr_string res = Debug.error2string(HostSuccess); if (bPortWasSet) { Msg("! IPureClient : port %d is BUSY!", c_port); return FALSE; } #ifdef DEBUG else Msg("! IPureClient : port %d is BUSY!", c_port); #endif c_port++; } else { Msg("- IPureClient : created on port %d!", c_port); } }; // R_CHK(res); if (res != S_OK) return FALSE; // Create ONE node HOST_NODE NODE; ZeroMemory (&NODE, sizeof(HOST_NODE)); // Copy the Host Address R_CHK (net_Address_server->Duplicate(&NODE.pHostAddress ) ); // Retreive session name char desc[4096]; ZeroMemory (desc,sizeof(desc)); DPN_APPLICATION_DESC* dpServerDesc=(DPN_APPLICATION_DESC*)desc; DWORD dpServerDescSize=sizeof(desc); dpServerDesc->dwSize = sizeof(DPN_APPLICATION_DESC); R_CHK (NET->GetApplicationDesc(dpServerDesc,&dpServerDescSize,0)); if( dpServerDesc->pwszSessionName) { string4096 dpSessionName; R_CHK(WideCharToMultiByte(CP_ACP,0,dpServerDesc->pwszSessionName,-1,dpSessionName,sizeof(dpSessionName),0,0)); NODE.dpSessionName = (char*)(&dpSessionName[0]); } net_Hosts.push_back (NODE); } else { string64 EnumData; EnumData[0] = 0; strcat (EnumData, "ToConnect"); DWORD EnumSize = xr_strlen(EnumData) + 1; // We now have the host address so lets enum u32 c_port = psCL_Port; HRESULT res = S_FALSE; while (res != S_OK && c_port <=END_PORT) { R_CHK(net_Address_device->AddComponent (DPNA_KEY_PORT, &c_port, sizeof(c_port), DPNA_DATATYPE_DWORD )); res = NET->EnumHosts( &dpAppDesc, // pApplicationDesc net_Address_server, // pdpaddrHost net_Address_device, // pdpaddrDeviceInfo EnumData, EnumSize, // pvUserEnumData, size 10, // dwEnumCount 1000, // dwRetryInterval 1000, // dwTimeOut NULL, // pvUserContext NULL, // pAsyncHandle DPNENUMHOSTS_SYNC // dwFlags ); if (res != S_OK) { // xr_string res = Debug.error2string(HostSuccess); switch (res) { case DPNERR_INVALIDHOSTADDRESS: { OnInvalidHost(); return FALSE; }break; case DPNERR_SESSIONFULL: { OnSessionFull(); return FALSE; }break; }; if (bPortWasSet) { Msg("! IPureClient : port %d is BUSY!", c_port); return FALSE; } #ifdef DEBUG else Msg("! IPureClient : port %d is BUSY!", c_port); // const char* x = DXGetErrorString9(res); string1024 tmp = ""; DXTRACE_ERR(tmp, res); #endif c_port++; } else { Msg("- IPureClient : created on port %d!", c_port); } }; // ****** Connection IDirectPlay8Address* pHostAddress = NULL; if (net_Hosts.empty()) { OnInvalidHost(); return FALSE; }; WCHAR SessionPasswordUNICODE[4096]; if ( xr_strlen( password_str) ) { CHK_DX(MultiByteToWideChar(CP_ACP, 0, password_str, -1, SessionPasswordUNICODE, 4096 )); dpAppDesc.dwFlags |= DPNSESSION_REQUIREPASSWORD; dpAppDesc.pwszPassword = SessionPasswordUNICODE; }; net_csEnumeration.Enter (); // real connect for (u32 I=0; I<net_Hosts.size(); I++) Msg("* HOST #%d: %s\n",I+1,*net_Hosts[I].dpSessionName); R_CHK(net_Hosts.front().pHostAddress->Duplicate(&pHostAddress ) ); // dump_URL ("! c2s ", pHostAddress); res = NET->Connect( &dpAppDesc, // pdnAppDesc pHostAddress, // pHostAddr net_Address_device, // pDeviceInfo NULL, // pdnSecurity NULL, // pdnCredentials NULL, 0, // pvUserConnectData/Size NULL, // pvAsyncContext NULL, // pvAsyncHandle DPNCONNECT_SYNC); // dwFlags // R_CHK(res); net_csEnumeration.Leave (); _RELEASE (pHostAddress); #ifdef DEBUG // const char* x = DXGetErrorString9(res); string1024 tmp = ""; DXTRACE_ERR(tmp, res); #endif switch (res) { case DPNERR_INVALIDPASSWORD: { OnInvalidPassword(); }break; case DPNERR_SESSIONFULL: { OnSessionFull(); }break; case DPNERR_CANTCREATEPLAYER: { Msg("! Error: Can\'t create player"); }break; } if (res != S_OK) return FALSE; } // Caps /* GUID sp_guid; DPN_SP_CAPS sp_caps; net_Address_device->GetSP(&sp_guid); ZeroMemory (&sp_caps,sizeof(sp_caps)); sp_caps.dwSize = sizeof(sp_caps); R_CHK (NET->GetSPCaps(&sp_guid,&sp_caps,0)); sp_caps.dwSystemBufferSize = 0; R_CHK (NET->SetSPCaps(&sp_guid,&sp_caps,0)); R_CHK (NET->GetSPCaps(&sp_guid,&sp_caps,0)); */ } //psNET_direct_connect // Sync net_TimeDelta = 0; return TRUE; } void IPureClient::Disconnect() { if( NET ) NET->Close(0); // Clean up Host _list_ net_csEnumeration.Enter (); for (u32 i=0; i<net_Hosts.size(); i++) { HOST_NODE& N = net_Hosts[i]; _RELEASE (N.pHostAddress); } net_Hosts.clear (); net_csEnumeration.Leave (); // Release interfaces _SHOW_REF ("cl_netADR_Server",net_Address_server); _RELEASE (net_Address_server); _SHOW_REF ("cl_netADR_Device",net_Address_device); _RELEASE (net_Address_device); _SHOW_REF ("cl_netCORE",NET); _RELEASE (NET); net_Connected = EnmConnectionWait; net_Syncronised = FALSE; } HRESULT IPureClient::net_Handler(u32 dwMessageType, PVOID pMessage) { // HRESULT hr = S_OK; switch (dwMessageType) { case DPN_MSGID_ENUM_HOSTS_RESPONSE: { PDPNMSG_ENUM_HOSTS_RESPONSE pEnumHostsResponseMsg; const DPN_APPLICATION_DESC* pDesc; // HOST_NODE* pHostNode = NULL; // WCHAR* pwszSession = NULL; pEnumHostsResponseMsg = (PDPNMSG_ENUM_HOSTS_RESPONSE) pMessage; pDesc = pEnumHostsResponseMsg->pApplicationDescription; // Insert each host response if it isn't already present net_csEnumeration.Enter (); BOOL bHostRegistered = FALSE; for (u32 I=0; I<net_Hosts.size(); I++) { HOST_NODE& N = net_Hosts [I]; if ( pDesc->guidInstance == N.dpAppDesc.guidInstance) { // This host is already in the list bHostRegistered = TRUE; break; } } if (!bHostRegistered) { // This host session is not in the list then so insert it. HOST_NODE NODE; ZeroMemory (&NODE, sizeof(HOST_NODE)); // Copy the Host Address R_CHK (pEnumHostsResponseMsg->pAddressSender->Duplicate(&NODE.pHostAddress ) ); CopyMemory(&NODE.dpAppDesc,pDesc,sizeof(DPN_APPLICATION_DESC)); // Null out all the pointers we aren't copying NODE.dpAppDesc.pwszSessionName = NULL; NODE.dpAppDesc.pwszPassword = NULL; NODE.dpAppDesc.pvReservedData = NULL; NODE.dpAppDesc.dwReservedDataSize = 0; NODE.dpAppDesc.pvApplicationReservedData = NULL; NODE.dpAppDesc.dwApplicationReservedDataSize = 0; if( pDesc->pwszSessionName) { string4096 dpSessionName; R_CHK (WideCharToMultiByte(CP_ACP,0,pDesc->pwszSessionName,-1,dpSessionName,sizeof(dpSessionName),0,0)); NODE.dpSessionName = (char*)(&dpSessionName[0]); } net_Hosts.push_back (NODE); } net_csEnumeration.Leave (); } break; case DPN_MSGID_RECEIVE: { PDPNMSG_RECEIVE pMsg = (PDPNMSG_RECEIVE) pMessage; MultipacketReciever::RecievePacket( pMsg->pReceiveData, pMsg->dwReceiveDataSize ); } break; case DPN_MSGID_TERMINATE_SESSION: { PDPNMSG_TERMINATE_SESSION pMsg = (PDPNMSG_TERMINATE_SESSION ) pMessage; char* m_data = (char*)pMsg->pvTerminateData; u32 m_size = pMsg->dwTerminateDataSize; HRESULT m_hResultCode = pMsg->hResultCode; net_Disconnected = TRUE; if (m_size != 0) { OnSessionTerminate(m_data); //Msg("- Session terminated : %s", m_data); } else { OnSessionTerminate( (::Debug.error2string(m_hResultCode))); //Msg("- Session terminated : %s", (::Debug.error2string(m_hResultCode))); } }; break; default: { #if 1 LPSTR msg = ""; switch (dwMessageType) { case DPN_MSGID_ADD_PLAYER_TO_GROUP: msg = "DPN_MSGID_ADD_PLAYER_TO_GROUP"; break; case DPN_MSGID_ASYNC_OP_COMPLETE: msg = "DPN_MSGID_ASYNC_OP_COMPLETE"; break; case DPN_MSGID_CLIENT_INFO: msg = "DPN_MSGID_CLIENT_INFO"; break; case DPN_MSGID_CONNECT_COMPLETE: { PDPNMSG_CONNECT_COMPLETE pMsg = (PDPNMSG_CONNECT_COMPLETE)pMessage; #ifdef DEBUG // const char* x = DXGetErrorString9(pMsg->hResultCode); if (pMsg->hResultCode != S_OK) { string1024 tmp=""; DXTRACE_ERR(tmp, pMsg->hResultCode); } #endif if (pMsg->dwApplicationReplyDataSize) { string256 ResStr = ""; strncpy(ResStr, (char*)(pMsg->pvApplicationReplyData), pMsg->dwApplicationReplyDataSize); Msg("Connection result : %s", ResStr); } else msg = "DPN_MSGID_CONNECT_COMPLETE"; }break; case DPN_MSGID_CREATE_GROUP: msg = "DPN_MSGID_CREATE_GROUP"; break; case DPN_MSGID_CREATE_PLAYER: msg = "DPN_MSGID_CREATE_PLAYER"; break; case DPN_MSGID_DESTROY_GROUP: msg = "DPN_MSGID_DESTROY_GROUP"; break; case DPN_MSGID_DESTROY_PLAYER: msg = "DPN_MSGID_DESTROY_PLAYER"; break; case DPN_MSGID_ENUM_HOSTS_QUERY: msg = "DPN_MSGID_ENUM_HOSTS_QUERY"; break; case DPN_MSGID_GROUP_INFO: msg = "DPN_MSGID_GROUP_INFO"; break; case DPN_MSGID_HOST_MIGRATE: msg = "DPN_MSGID_HOST_MIGRATE"; break; case DPN_MSGID_INDICATE_CONNECT: msg = "DPN_MSGID_INDICATE_CONNECT"; break; case DPN_MSGID_INDICATED_CONNECT_ABORTED: msg = "DPN_MSGID_INDICATED_CONNECT_ABORTED"; break; case DPN_MSGID_PEER_INFO: msg = "DPN_MSGID_PEER_INFO"; break; case DPN_MSGID_REMOVE_PLAYER_FROM_GROUP: msg = "DPN_MSGID_REMOVE_PLAYER_FROM_GROUP"; break; case DPN_MSGID_RETURN_BUFFER: msg = "DPN_MSGID_RETURN_BUFFER"; break; case DPN_MSGID_SEND_COMPLETE: msg = "DPN_MSGID_SEND_COMPLETE"; break; case DPN_MSGID_SERVER_INFO: msg = "DPN_MSGID_SERVER_INFO"; break; case DPN_MSGID_TERMINATE_SESSION: msg = "DPN_MSGID_TERMINATE_SESSION"; break; default: msg = "???"; break; } //Msg("! ************************************ : %s",msg); #endif } break; } return S_OK; } void IPureClient::OnMessage(void* data, u32 size) { // One of the messages - decompress it NET_Packet* P = net_Queue.CreateGet(); P->construct (data, size); P->timeReceive = timeServer_Async(); u16 tmp_type; P->r_begin (tmp_type); net_Queue.CreateCommit (P); } void IPureClient::timeServer_Correct(u32 sv_time, u32 cl_time) { u32 ping = net_Statistic.getPing(); u32 delta = sv_time + ping/2 - cl_time; net_DeltaArray.push (delta); Sync_Average (); } void IPureClient::SendTo_LL(void* data, u32 size, u32 dwFlags, u32 dwTimeout) { if( net_Disconnected ) return; if( psNET_Flags.test(NETFLAG_LOG_CL_PACKETS) ) { if( !pClNetLog) pClNetLog = xr_new<INetLog>( "logs\\net_cl_log.log", timeServer() ); if( pClNetLog ) pClNetLog->LogData( timeServer(), data, size ); } DPN_BUFFER_DESC desc; desc.dwBufferSize = size; desc.pBufferData = (BYTE*)data; net_Statistic.dwBytesSended += size; // verify VERIFY(desc.dwBufferSize); VERIFY(desc.pBufferData); VERIFY(NET); DPNHANDLE hAsync = 0; HRESULT hr = NET->Send( &desc, 1, dwTimeout, 0, &hAsync, dwFlags | DPNSEND_COALESCE ); // Msg("- Client::SendTo_LL [%d]", size); if( FAILED(hr) ) { Msg ("! ERROR: Failed to send net-packet, reason: %s",::Debug.error2string(hr)); // const char* x = DXGetErrorString9(hr); string1024 tmp=""; DXTRACE_ERR(tmp, hr); } // UpdateStatistic(); } void IPureClient::Send( NET_Packet& packet, u32 dwFlags, u32 dwTimeout ) { MultipacketSender::SendPacket( packet.B.data, packet.B.count, dwFlags, dwTimeout ); } void IPureClient::Flush_Send_Buffer () { MultipacketSender::FlushSendBuffer( 0 ); } BOOL IPureClient::net_HasBandwidth () { u32 dwTime = TimeGlobal(device_timer); u32 dwInterval = 0; if (net_Disconnected) return FALSE; if (psNET_ClientUpdate != 0) dwInterval = 1000/psNET_ClientUpdate; if (psNET_Flags.test(NETFLAG_MINIMIZEUPDATES)) dwInterval = 1000; // approx 3 times per second if(psNET_direct_connect) { if( 0 != psNET_ClientUpdate && (dwTime-net_Time_LastUpdate)>dwInterval) { net_Time_LastUpdate = dwTime; return TRUE; }else return FALSE; }else if (0 != psNET_ClientUpdate && (dwTime-net_Time_LastUpdate)>dwInterval) { HRESULT hr; R_ASSERT (NET); // check queue for "empty" state DWORD dwPending=0; hr = NET->GetSendQueueInfo(&dwPending,0,0); if (FAILED(hr)) return FALSE; if (dwPending > u32(psNET_ClientPending)) { net_Statistic.dwTimesBlocked++; return FALSE; }; UpdateStatistic(); // ok net_Time_LastUpdate = dwTime; return TRUE; } return FALSE; } void IPureClient::UpdateStatistic() { // Query network statistic for this client DPN_CONNECTION_INFO CI; ZeroMemory (&CI,sizeof(CI)); CI.dwSize = sizeof(CI); HRESULT hr = NET->GetConnectionInfo(&CI,0); if (FAILED(hr)) return; net_Statistic.Update(CI); } void IPureClient::Sync_Thread () { MSYS_PING clPing; //***** Ping server net_DeltaArray.clear(); R_ASSERT (NET); for (; NET && !net_Disconnected; ) { // Waiting for queue empty state if (net_Syncronised) break; // Sleep(2000); else { DWORD dwPending=0; do { R_CHK (NET->GetSendQueueInfo(&dwPending,0,0)); Sleep (1); } while (dwPending); } // Construct message clPing.sign1 = 0x12071980; clPing.sign2 = 0x26111975; clPing.dwTime_ClientSend = TimerAsync(device_timer); // Send it __try { DPN_BUFFER_DESC desc; DPNHANDLE hAsync=0; desc.dwBufferSize = sizeof(clPing); desc.pBufferData = LPBYTE(&clPing); if (0==NET || net_Disconnected) break; if (FAILED(NET->Send(&desc,1,0,0,&hAsync,net_flags(FALSE,FALSE,TRUE)))) { Msg("* CLIENT: SyncThread: EXIT. (failed to send - disconnected?)"); break; } } __except (EXCEPTION_EXECUTE_HANDLER) { Msg("* CLIENT: SyncThread: EXIT. (failed to send - disconnected?)"); break; } // Waiting for reply-packet to arrive if (!net_Syncronised) { u32 old_size = net_DeltaArray.size(); u32 timeBegin = TimerAsync(device_timer); while ((net_DeltaArray.size()==old_size)&&(TimerAsync(device_timer)-timeBegin<5000)) Sleep(1); if (net_DeltaArray.size()>=syncSamples) { net_Syncronised = TRUE; net_TimeDelta = net_TimeDelta_Calculated; // Msg ("* CL_TimeSync: DELTA: %d",net_TimeDelta); } } } } void IPureClient::Sync_Average () { //***** Analyze results s64 summary_delta = 0; s32 size = net_DeltaArray.size(); u32* I = net_DeltaArray.begin(); u32* E = I+size; for (; I!=E; I++) summary_delta += *((int*)I); s64 frac = s64(summary_delta) % s64(size); if (frac<0) frac=-frac; summary_delta /= s64(size); if (frac>s64(size/2)) summary_delta += (summary_delta<0)?-1:1; net_TimeDelta_Calculated= s32(summary_delta); net_TimeDelta = (net_TimeDelta*5+net_TimeDelta_Calculated)/6; // Msg("* CLIENT: d(%d), dc(%d), s(%d)",net_TimeDelta,net_TimeDelta_Calculated,size); } void sync_thread(void* P) { SetThreadPriority (GetCurrentThread(),THREAD_PRIORITY_TIME_CRITICAL); IPureClient* C = (IPureClient*)P; C->Sync_Thread (); } void IPureClient::net_Syncronize () { net_Syncronised = FALSE; net_DeltaArray.clear(); thread_spawn (sync_thread,"network-time-sync",0,this); } void IPureClient::ClearStatistic() { net_Statistic.Clear(); } BOOL IPureClient::net_IsSyncronised() { return net_Syncronised; } #include <WINSOCK2.H> #include <Ws2tcpip.h> bool IPureClient::GetServerAddress (ip_address& pAddress, DWORD* pPort) { *pPort = 0; if (!net_Address_server) return false; WCHAR wstrHostname[ 2048 ] = {0}; DWORD dwHostNameSize = sizeof(wstrHostname); DWORD dwHostNameDataType = DPNA_DATATYPE_STRING; CHK_DX(net_Address_server->GetComponentByName( DPNA_KEY_HOSTNAME, wstrHostname, &dwHostNameSize, &dwHostNameDataType )); string2048 HostName; CHK_DX(WideCharToMultiByte(CP_ACP,0,wstrHostname,-1,HostName,sizeof(HostName),0,0)); hostent* pHostEnt = gethostbyname(HostName); char* localIP; localIP = inet_ntoa (*(struct in_addr *)*pHostEnt->h_addr_list); pHostEnt = gethostbyname(pHostEnt->h_name); localIP = inet_ntoa (*(struct in_addr *)*pHostEnt->h_addr_list); pAddress.set (localIP); //. pAddress[0] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_net; //. pAddress[1] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_host; //. pAddress[2] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_lh; //. pAddress[3] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_impno; DWORD dwPort = 0; DWORD dwPortSize = sizeof(dwPort); DWORD dwPortDataType = DPNA_DATATYPE_DWORD; CHK_DX(net_Address_server->GetComponentByName( DPNA_KEY_PORT, &dwPort, &dwPortSize, &dwPortDataType )); *pPort = dwPort; return true; };
OLR-xray/OLR-3.0
src/xray/xrNetServer/NET_Client.cpp
C++
apache-2.0
30,074
# IOSStudyResource IOS学习资源整理,不定期的更新 #完整的IOS项目,具有很大的教学意义 1.https://github.com/JakeLin/SwiftWeather 一天swift版本的天气项目 2.https://github.com/xushao1990/XTNews 仿网易新闻的app,里面介绍了一些比较好的库 3.https://github.com/12207480/KnowingLife 基于天气,查询,团购,新闻类查询应用 #Xcode中不错的插件 1.https://github.com/limejelly/Backlight-for-XCode 高亮当前正在编辑的一行 2.https://github.com/FuzzyAutocomplete/FuzzyAutocompletePlugin 强大的模糊匹配输入 让你写代码的时候再也不用费脑子去记住名字那么长的对象或者函数名了 好用到让你想哭 3. #IOS第三库依赖管理,类似Java中的maven,Android中的Gradle 1.https://github.com/CocoaPods/CocoaPods 2.https://github.com/Carthage/Carthage #IOS中百分比布局库,自动布局可以goodbye了 1.https://github.com/jhurray/EZLayout #带动画效果的UIPagerControl 1.https://github.com/KittenYang/KYAnimatedPageControl 2.https://github.com/Spaceman-Labs/SMPageControl #非常不错的一个库,显示控件的PlaceHolder或者是UIView的大小 1.https://github.com/adad184/MMPlaceHolder #UITableViewCell支持滑动显示更多操作按钮的 1.https://github.com/JonasGessner/JGScrollableTableViewCell 2.https://github.com/MortimerGoro/MGSwipeTableCell 非常强大的控件 3.https://github.com/CEWendel/SWTableViewCell 这个用的最多的一个 #IOS非常漂亮的做引导页滚动视图 1.https://github.com/IFTTT/JazzHands #IOS中不错的菜单 1.https://github.com/12207480/DOPDropDownMenu-Enhanced 高仿美团下拉菜单-优化版 2.https://github.com/KittenYang/KYGooeyMenu 带黏贴效果的菜单 #不错的动画效果库 1.https://github.com/ArtFeel/AFViewShaker 左右震动 2.https://github.com/12207480/TYWaterWaveView 水波纹效果 #十分强大的类似ScrollView的类!提供重用视图及多种3D切换方式 1.https://github.com/nicklockwood/iCarousel 2.https://github.com/12207480/TYHorizenTableView 水平方向的UITableView #瀑布流 1.https://github.com/ptshih/PSCollectionView #Json解析 1.https://github.com/SwiftyJSON/SwiftyJSON swift版本 #网络解析 1.https://github.com/Alamofire/Alamofire AFNetworking的swift版本 #WebSocket 1.https://github.com/daltoniam/Starscream 支持IOS和OSX #数据库封装 1.https://github.com/stephencelis/SQLite.swift sqlite轻量级封装 2.https://github.com/realm/realm-cocoa 志向代替Core Data和SQLite的移动数据库 #图片处理 1.https://github.com/kaishin/gifu 高性能GIF显示类库 2.https://github.com/Nyx0uf/NYXImagesKit 图片过滤等N种效果集合 #自动布局框架 1.https://github.com/robb/Cartography 基于代码级的自动布局封装框架 #进度条 1.https://github.com/kentya6/KYCircularProgress 简单、实用路径可定进程条 #测试框架 1.https://github.com/Quick/Quick 行为驱动测试框架 2.https://github.com/Quick/Nimble 匹配断言测试框架 #手势密码解锁(九宫格) 1.https://github.com/iosdeveloperpanc/PCGestureUnlock 目前最全面最高仿支付宝的手势解锁,而且提供方法进行参数修改,能解决项目开发中所有手势解锁的开发 2.https://github.com/nsdictionary/CoreLock 高仿支付宝解锁 #和Android中TabLayout、PageTab相似的PagesView控件 1.https://github.com/nsdictionary/CorePagesView #图片选择器(支持多选) 1.https://github.com/questbeat/QBImagePicker QBImagePickerController 扩展了 UIImagePickerController 类用于支持图像的多选操作 #带placeholder的UITextView 1.https://github.com/gcamp/GCPlaceholderTextView 2.https://github.com/lukagabric/LPlaceholderTextView #IOS视频播放器 1.https://github.com/iMoreApps/ffmpeg-avplayer-for-ios 支持多种视频编码 2.https://github.com/Bilibili/ijkplayer 非常强大的视频解码库,根据fmpeg封装,支持IOS和Android,Bilibili出品 #IOS在线音频播放器 1.https://github.com/muhku/FreeStreamer FreeStreamer是适用于iOS和OS X的音频播放引擎, 专门为播放音频流而设计。该引擎示范UI简单,效率高,占用内存少,用C++写成 #强大的日志log框架 1.https://github.com/CocoaLumberjack/CocoaLumberjack #聊天页面UI 1.https://github.com/jessesquires/JSQMessagesViewController #自定义显示消息和通知的框架 1.https://github.com/KrauseFx/TSMessages 在屏幕顶部 #UIWebView进度条 1.https://github.com/ninjinkun/NJKWebViewProgress 非常不错的UIWebView进度条 #UIWebView控件 1.https://github.com/TransitApp/SVWebViewController 非常不错,功能强大 #不错的卡片切换效果 1.https://github.com/cwRichardKim/TinderSimpleSwipeCards
hongchenxi/IOSStudyResource
README.md
Markdown
apache-2.0
4,774
/******************************************************************************* * Copyright (c) 2015-2019 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.deeplearning4j.nn.weights.embeddings; import lombok.EqualsAndHashCode; import lombok.NonNull; import org.deeplearning4j.nn.weights.IWeightInit; import org.nd4j.common.base.Preconditions; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.shade.jackson.annotation.JsonIgnoreProperties; import org.nd4j.shade.jackson.annotation.JsonProperty; /** * Weight initialization for initializing the parameters of an EmbeddingLayer from a {@link EmbeddingInitializer} * * Note: WeightInitEmbedding supports both JSON serializable and non JSON serializable initializations. * In the case of non-JSON serializable embeddings, they are a one-time only use: once they have been used * to initialize the parameters, they will be removed from the WeightInitEmbedding instance. * This is to prevent unnecessary references to potentially large objects in memory (i.e., to avoid memory leaks) * * @author Alex Black */ @JsonIgnoreProperties("nonSerializableInit") @EqualsAndHashCode public class WeightInitEmbedding implements IWeightInit { private EmbeddingInitializer serializableInit; private EmbeddingInitializer nonSerializableInit; public WeightInitEmbedding(@NonNull EmbeddingInitializer embeddingInitializer){ this((embeddingInitializer.jsonSerializable() ? embeddingInitializer : null), (embeddingInitializer.jsonSerializable() ? null : embeddingInitializer)); } protected WeightInitEmbedding(@JsonProperty("serializableInit") EmbeddingInitializer serializableInit, @JsonProperty("nonSerializableInit") EmbeddingInitializer nonSerializableInit){ this.serializableInit = serializableInit; this.nonSerializableInit = nonSerializableInit; } @Override public INDArray init(double fanIn, double fanOut, long[] shape, char order, INDArray paramView) { EmbeddingInitializer init = serializableInit != null ? serializableInit : nonSerializableInit; if(init == null){ throw new IllegalStateException("Cannot initialize embedding layer weights: no EmbeddingInitializer is available." + " This can occur if you save network configuration, load it, and the try to "); } Preconditions.checkState(shape[0] == init.vocabSize(), "Parameters shape[0]=%s does not match embedding initializer vocab size of %s", shape[0], init.vocabSize()); Preconditions.checkState(shape[1] == init.vectorSize(), "Parameters shape[1]=%s does not match embedding initializer vector size of %s", shape[1], init.vectorSize()); INDArray reshaped = paramView.reshape('c', shape); init.loadWeightsInto(reshaped); //Now that we've loaded weights - let's clear the reference if it's non-serializable so it can be GC'd this.nonSerializableInit = null; return reshaped; } public long[] shape(){ if(serializableInit != null){ return new long[]{serializableInit.vocabSize(), serializableInit.vectorSize()}; } else if(nonSerializableInit != null){ return new long[]{nonSerializableInit.vocabSize(), nonSerializableInit.vectorSize()}; } return null; } }
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/weights/embeddings/WeightInitEmbedding.java
Java
apache-2.0
3,970
# coding=utf-8 # Copyright 2012 Hewlett-Packard Development Company, L.P. # Copyright (c) 2012 NTT DOCOMO, INC. # Copyright 2014 International Business Machines Corporation # 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. """ IPMI power manager driver. Uses the 'ipmitool' command (http://ipmitool.sourceforge.net/) to remotely manage hardware. This includes setting the boot device, getting a serial-over-LAN console, and controlling the power state of the machine. NOTE THAT CERTAIN DISTROS MAY INSTALL openipmi BY DEFAULT, INSTEAD OF ipmitool, WHICH PROVIDES DIFFERENT COMMAND-LINE OPTIONS AND *IS NOT SUPPORTED* BY THIS DRIVER. """ import contextlib import os import re import subprocess import tempfile import time from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import log as logging from oslo_service import loopingcall from oslo_utils import excutils from ironic.common import boot_devices from ironic.common import exception from ironic.common.i18n import _ from ironic.common.i18n import _LE from ironic.common.i18n import _LI from ironic.common.i18n import _LW from ironic.common import states from ironic.common import utils from ironic.conductor import task_manager from ironic.drivers import base from ironic.drivers.modules import console_utils CONF = cfg.CONF CONF.import_opt('retry_timeout', 'ironic.drivers.modules.ipminative', group='ipmi') CONF.import_opt('min_command_interval', 'ironic.drivers.modules.ipminative', group='ipmi') LOG = logging.getLogger(__name__) VALID_PRIV_LEVELS = ['ADMINISTRATOR', 'CALLBACK', 'OPERATOR', 'USER'] VALID_PROTO_VERSIONS = ('2.0', '1.5') REQUIRED_PROPERTIES = { 'ipmi_address': _("IP address or hostname of the node. Required.") } OPTIONAL_PROPERTIES = { 'ipmi_password': _("password. Optional."), 'ipmi_priv_level': _("privilege level; default is ADMINISTRATOR. One of " "%s. Optional.") % ', '.join(VALID_PRIV_LEVELS), 'ipmi_username': _("username; default is NULL user. Optional."), 'ipmi_bridging': _("bridging_type; default is \"no\". One of \"single\", " "\"dual\", \"no\". Optional."), 'ipmi_transit_channel': _("transit channel for bridged request. Required " "only if ipmi_bridging is set to \"dual\"."), 'ipmi_transit_address': _("transit address for bridged request. Required " "only if ipmi_bridging is set to \"dual\"."), 'ipmi_target_channel': _("destination channel for bridged request. " "Required only if ipmi_bridging is set to " "\"single\" or \"dual\"."), 'ipmi_target_address': _("destination address for bridged request. " "Required only if ipmi_bridging is set " "to \"single\" or \"dual\"."), 'ipmi_local_address': _("local IPMB address for bridged requests. " "Used only if ipmi_bridging is set " "to \"single\" or \"dual\". Optional."), 'ipmi_protocol_version': _('the version of the IPMI protocol; default ' 'is "2.0". One of "1.5", "2.0". Optional.'), } COMMON_PROPERTIES = REQUIRED_PROPERTIES.copy() COMMON_PROPERTIES.update(OPTIONAL_PROPERTIES) CONSOLE_PROPERTIES = { 'ipmi_terminal_port': _("node's UDP port to connect to. Only required for " "console access.") } BRIDGING_OPTIONS = [('local_address', '-m'), ('transit_channel', '-B'), ('transit_address', '-T'), ('target_channel', '-b'), ('target_address', '-t')] LAST_CMD_TIME = {} TIMING_SUPPORT = None SINGLE_BRIDGE_SUPPORT = None DUAL_BRIDGE_SUPPORT = None TMP_DIR_CHECKED = None ipmitool_command_options = { 'timing': ['ipmitool', '-N', '0', '-R', '0', '-h'], 'single_bridge': ['ipmitool', '-m', '0', '-b', '0', '-t', '0', '-h'], 'dual_bridge': ['ipmitool', '-m', '0', '-b', '0', '-t', '0', '-B', '0', '-T', '0', '-h']} # Note(TheJulia): This string is hardcoded in ipmitool's lanplus driver # and is substituted in return for the error code received from the IPMI # controller. As of 1.8.15, no internationalization support appears to # be in ipmitool which means the string should always be returned in this # form regardless of locale. IPMITOOL_RETRYABLE_FAILURES = ['insufficient resources for session'] def _check_option_support(options): """Checks if the specific ipmitool options are supported on host. This method updates the module-level variables indicating whether an option is supported so that it is accessible by any driver interface class in this module. It is intended to be called from the __init__ method of such classes only. :param options: list of ipmitool options to be checked :raises: OSError """ for opt in options: if _is_option_supported(opt) is None: try: cmd = ipmitool_command_options[opt] # NOTE(cinerama): use subprocess.check_call to # check options & suppress ipmitool output to # avoid alarming people with open(os.devnull, 'wb') as nullfile: subprocess.check_call(cmd, stdout=nullfile, stderr=nullfile) except subprocess.CalledProcessError: LOG.info(_LI("Option %(opt)s is not supported by ipmitool"), {'opt': opt}) _is_option_supported(opt, False) else: LOG.info(_LI("Option %(opt)s is supported by ipmitool"), {'opt': opt}) _is_option_supported(opt, True) def _is_option_supported(option, is_supported=None): """Indicates whether the particular ipmitool option is supported. :param option: specific ipmitool option :param is_supported: Optional Boolean. when specified, this value is assigned to the module-level variable indicating whether the option is supported. Used only if a value is not already assigned. :returns: True, indicates the option is supported :returns: False, indicates the option is not supported :returns: None, indicates that it is not aware whether the option is supported """ global SINGLE_BRIDGE_SUPPORT global DUAL_BRIDGE_SUPPORT global TIMING_SUPPORT if option == 'single_bridge': if (SINGLE_BRIDGE_SUPPORT is None) and (is_supported is not None): SINGLE_BRIDGE_SUPPORT = is_supported return SINGLE_BRIDGE_SUPPORT elif option == 'dual_bridge': if (DUAL_BRIDGE_SUPPORT is None) and (is_supported is not None): DUAL_BRIDGE_SUPPORT = is_supported return DUAL_BRIDGE_SUPPORT elif option == 'timing': if (TIMING_SUPPORT is None) and (is_supported is not None): TIMING_SUPPORT = is_supported return TIMING_SUPPORT def _console_pwfile_path(uuid): """Return the file path for storing the ipmi password for a console.""" file_name = "%(uuid)s.pw" % {'uuid': uuid} return os.path.join(CONF.tempdir, file_name) @contextlib.contextmanager def _make_password_file(password): """Makes a temporary file that contains the password. :param password: the password :returns: the absolute pathname of the temporary file :raises: PasswordFileFailedToCreate from creating or writing to the temporary file """ f = None try: f = tempfile.NamedTemporaryFile(mode='w', dir=CONF.tempdir) f.write(str(password)) f.flush() except (IOError, OSError) as exc: if f is not None: f.close() raise exception.PasswordFileFailedToCreate(error=exc) except Exception: with excutils.save_and_reraise_exception(): if f is not None: f.close() try: # NOTE(jlvillal): This yield can not be in the try/except block above # because an exception by the caller of this function would then get # changed to a PasswordFileFailedToCreate exception which would mislead # about the problem and its cause. yield f.name finally: if f is not None: f.close() def _parse_driver_info(node): """Gets the parameters required for ipmitool to access the node. :param node: the Node of interest. :returns: dictionary of parameters. :raises: InvalidParameterValue when an invalid value is specified :raises: MissingParameterValue when a required ipmi parameter is missing. """ info = node.driver_info or {} bridging_types = ['single', 'dual'] missing_info = [key for key in REQUIRED_PROPERTIES if not info.get(key)] if missing_info: raise exception.MissingParameterValue(_( "Missing the following IPMI credentials in node's" " driver_info: %s.") % missing_info) address = info.get('ipmi_address') username = info.get('ipmi_username') password = info.get('ipmi_password') port = info.get('ipmi_terminal_port') priv_level = info.get('ipmi_priv_level', 'ADMINISTRATOR') bridging_type = info.get('ipmi_bridging', 'no') local_address = info.get('ipmi_local_address') transit_channel = info.get('ipmi_transit_channel') transit_address = info.get('ipmi_transit_address') target_channel = info.get('ipmi_target_channel') target_address = info.get('ipmi_target_address') protocol_version = str(info.get('ipmi_protocol_version', '2.0')) if protocol_version not in VALID_PROTO_VERSIONS: valid_versions = ', '.join(VALID_PROTO_VERSIONS) raise exception.InvalidParameterValue(_( "Invalid IPMI protocol version value %(version)s, the valid " "value can be one of %(valid_versions)s") % {'version': protocol_version, 'valid_versions': valid_versions}) if port: try: port = int(port) except ValueError: raise exception.InvalidParameterValue(_( "IPMI terminal port is not an integer.")) # check if ipmi_bridging has proper value if bridging_type == 'no': # if bridging is not selected, then set all bridging params to None (local_address, transit_channel, transit_address, target_channel, target_address) = (None,) * 5 elif bridging_type in bridging_types: # check if the particular bridging option is supported on host if not _is_option_supported('%s_bridge' % bridging_type): raise exception.InvalidParameterValue(_( "Value for ipmi_bridging is provided as %s, but IPMI " "bridging is not supported by the IPMI utility installed " "on host. Ensure ipmitool version is > 1.8.11" ) % bridging_type) # ensure that all the required parameters are provided params_undefined = [param for param, value in [ ("ipmi_target_channel", target_channel), ('ipmi_target_address', target_address)] if value is None] if bridging_type == 'dual': params_undefined2 = [param for param, value in [ ("ipmi_transit_channel", transit_channel), ('ipmi_transit_address', transit_address) ] if value is None] params_undefined.extend(params_undefined2) else: # if single bridging was selected, set dual bridge params to None transit_channel = transit_address = None # If the required parameters were not provided, # raise an exception if params_undefined: raise exception.MissingParameterValue(_( "%(param)s not provided") % {'param': params_undefined}) else: raise exception.InvalidParameterValue(_( "Invalid value for ipmi_bridging: %(bridging_type)s," " the valid value can be one of: %(bridging_types)s" ) % {'bridging_type': bridging_type, 'bridging_types': bridging_types + ['no']}) if priv_level not in VALID_PRIV_LEVELS: valid_priv_lvls = ', '.join(VALID_PRIV_LEVELS) raise exception.InvalidParameterValue(_( "Invalid privilege level value:%(priv_level)s, the valid value" " can be one of %(valid_levels)s") % {'priv_level': priv_level, 'valid_levels': valid_priv_lvls}) return { 'address': address, 'username': username, 'password': password, 'port': port, 'uuid': node.uuid, 'priv_level': priv_level, 'local_address': local_address, 'transit_channel': transit_channel, 'transit_address': transit_address, 'target_channel': target_channel, 'target_address': target_address, 'protocol_version': protocol_version, } def _exec_ipmitool(driver_info, command): """Execute the ipmitool command. :param driver_info: the ipmitool parameters for accessing a node. :param command: the ipmitool command to be executed. :returns: (stdout, stderr) from executing the command. :raises: PasswordFileFailedToCreate from creating or writing to the temporary file. :raises: processutils.ProcessExecutionError from executing the command. """ ipmi_version = ('lanplus' if driver_info['protocol_version'] == '2.0' else 'lan') args = ['ipmitool', '-I', ipmi_version, '-H', driver_info['address'], '-L', driver_info['priv_level'] ] if driver_info['username']: args.append('-U') args.append(driver_info['username']) for name, option in BRIDGING_OPTIONS: if driver_info[name] is not None: args.append(option) args.append(driver_info[name]) # specify retry timing more precisely, if supported num_tries = max( (CONF.ipmi.retry_timeout // CONF.ipmi.min_command_interval), 1) if _is_option_supported('timing'): args.append('-R') args.append(str(num_tries)) args.append('-N') args.append(str(CONF.ipmi.min_command_interval)) end_time = (time.time() + CONF.ipmi.retry_timeout) while True: num_tries = num_tries - 1 # NOTE(deva): ensure that no communications are sent to a BMC more # often than once every min_command_interval seconds. time_till_next_poll = CONF.ipmi.min_command_interval - ( time.time() - LAST_CMD_TIME.get(driver_info['address'], 0)) if time_till_next_poll > 0: time.sleep(time_till_next_poll) # Resetting the list that will be utilized so the password arguments # from any previous execution are preserved. cmd_args = args[:] # 'ipmitool' command will prompt password if there is no '-f' # option, we set it to '\0' to write a password file to support # empty password with _make_password_file(driver_info['password'] or '\0') as pw_file: cmd_args.append('-f') cmd_args.append(pw_file) cmd_args.extend(command.split(" ")) try: out, err = utils.execute(*cmd_args) return out, err except processutils.ProcessExecutionError as e: with excutils.save_and_reraise_exception() as ctxt: err_list = [x for x in IPMITOOL_RETRYABLE_FAILURES if x in e.args[0]] if ((time.time() > end_time) or (num_tries == 0) or not err_list): LOG.error(_LE('IPMI Error while attempting "%(cmd)s"' 'for node %(node)s. Error: %(error)s'), { 'node': driver_info['uuid'], 'cmd': e.cmd, 'error': e }) else: ctxt.reraise = False LOG.warning(_LW('IPMI Error encountered, retrying ' '"%(cmd)s" for node %(node)s. ' 'Error: %(error)s'), { 'node': driver_info['uuid'], 'cmd': e.cmd, 'error': e }) finally: LAST_CMD_TIME[driver_info['address']] = time.time() def _sleep_time(iter): """Return the time-to-sleep for the n'th iteration of a retry loop. This implementation increases exponentially. :param iter: iteration number :returns: number of seconds to sleep """ if iter <= 1: return 1 return iter ** 2 def _set_and_wait(target_state, driver_info): """Helper function for DynamicLoopingCall. This method changes the power state and polls the BMCuntil the desired power state is reached, or CONF.ipmi.retry_timeout would be exceeded by the next iteration. This method assumes the caller knows the current power state and does not check it prior to changing the power state. Most BMCs should be fine, but if a driver is concerned, the state should be checked prior to calling this method. :param target_state: desired power state :param driver_info: the ipmitool parameters for accessing a node. :returns: one of ironic.common.states """ if target_state == states.POWER_ON: state_name = "on" elif target_state == states.POWER_OFF: state_name = "off" def _wait(mutable): try: # Only issue power change command once if mutable['iter'] < 0: _exec_ipmitool(driver_info, "power %s" % state_name) else: mutable['power'] = _power_status(driver_info) except (exception.PasswordFileFailedToCreate, processutils.ProcessExecutionError, exception.IPMIFailure): # Log failures but keep trying LOG.warning(_LW("IPMI power %(state)s failed for node %(node)s."), {'state': state_name, 'node': driver_info['uuid']}) finally: mutable['iter'] += 1 if mutable['power'] == target_state: raise loopingcall.LoopingCallDone() sleep_time = _sleep_time(mutable['iter']) if (sleep_time + mutable['total_time']) > CONF.ipmi.retry_timeout: # Stop if the next loop would exceed maximum retry_timeout LOG.error(_LE('IPMI power %(state)s timed out after ' '%(tries)s retries on node %(node_id)s.'), {'state': state_name, 'tries': mutable['iter'], 'node_id': driver_info['uuid']}) mutable['power'] = states.ERROR raise loopingcall.LoopingCallDone() else: mutable['total_time'] += sleep_time return sleep_time # Use mutable objects so the looped method can change them. # Start 'iter' from -1 so that the first two checks are one second apart. status = {'power': None, 'iter': -1, 'total_time': 0} timer = loopingcall.DynamicLoopingCall(_wait, status) timer.start().wait() return status['power'] def _power_on(driver_info): """Turn the power ON for this node. :param driver_info: the ipmitool parameters for accessing a node. :returns: one of ironic.common.states POWER_ON or ERROR. :raises: IPMIFailure on an error from ipmitool (from _power_status call). """ return _set_and_wait(states.POWER_ON, driver_info) def _power_off(driver_info): """Turn the power OFF for this node. :param driver_info: the ipmitool parameters for accessing a node. :returns: one of ironic.common.states POWER_OFF or ERROR. :raises: IPMIFailure on an error from ipmitool (from _power_status call). """ return _set_and_wait(states.POWER_OFF, driver_info) def _power_status(driver_info): """Get the power status for a node. :param driver_info: the ipmitool access parameters for a node. :returns: one of ironic.common.states POWER_OFF, POWER_ON or ERROR. :raises: IPMIFailure on an error from ipmitool. """ cmd = "power status" try: out_err = _exec_ipmitool(driver_info, cmd) except (exception.PasswordFileFailedToCreate, processutils.ProcessExecutionError) as e: LOG.warning(_LW("IPMI power status failed for node %(node_id)s with " "error: %(error)s."), {'node_id': driver_info['uuid'], 'error': e}) raise exception.IPMIFailure(cmd=cmd) if out_err[0] == "Chassis Power is on\n": return states.POWER_ON elif out_err[0] == "Chassis Power is off\n": return states.POWER_OFF else: return states.ERROR def _process_sensor(sensor_data): sensor_data_fields = sensor_data.split('\n') sensor_data_dict = {} for field in sensor_data_fields: if not field: continue kv_value = field.split(':') if len(kv_value) != 2: continue sensor_data_dict[kv_value[0].strip()] = kv_value[1].strip() return sensor_data_dict def _get_sensor_type(node, sensor_data_dict): # Have only three sensor type name IDs: 'Sensor Type (Analog)' # 'Sensor Type (Discrete)' and 'Sensor Type (Threshold)' for key in ('Sensor Type (Analog)', 'Sensor Type (Discrete)', 'Sensor Type (Threshold)'): try: return sensor_data_dict[key].split(' ', 1)[0] except KeyError: continue raise exception.FailedToParseSensorData( node=node.uuid, error=(_("parse ipmi sensor data failed, unknown sensor type" " data: %(sensors_data)s"), {'sensors_data': sensor_data_dict})) def _parse_ipmi_sensors_data(node, sensors_data): """Parse the IPMI sensors data and format to the dict grouping by type. We run 'ipmitool' command with 'sdr -v' options, which can return sensor details in human-readable format, we need to format them to JSON string dict-based data for Ceilometer Collector which can be sent it as payload out via notification bus and consumed by Ceilometer Collector. :param sensors_data: the sensor data returned by ipmitool command. :returns: the sensor data with JSON format, grouped by sensor type. :raises: FailedToParseSensorData when error encountered during parsing. """ sensors_data_dict = {} if not sensors_data: return sensors_data_dict sensors_data_array = sensors_data.split('\n\n') for sensor_data in sensors_data_array: sensor_data_dict = _process_sensor(sensor_data) if not sensor_data_dict: continue sensor_type = _get_sensor_type(node, sensor_data_dict) # ignore the sensors which has no current 'Sensor Reading' data if 'Sensor Reading' in sensor_data_dict: sensors_data_dict.setdefault( sensor_type, {})[sensor_data_dict['Sensor ID']] = sensor_data_dict # get nothing, no valid sensor data if not sensors_data_dict: raise exception.FailedToParseSensorData( node=node.uuid, error=(_("parse ipmi sensor data failed, get nothing with input" " data: %(sensors_data)s") % {'sensors_data': sensors_data})) return sensors_data_dict @task_manager.require_exclusive_lock def send_raw(task, raw_bytes): """Send raw bytes to the BMC. Bytes should be a string of bytes. :param task: a TaskManager instance. :param raw_bytes: a string of raw bytes to send, e.g. '0x00 0x01' :raises: IPMIFailure on an error from ipmitool. :raises: MissingParameterValue if a required parameter is missing. :raises: InvalidParameterValue when an invalid value is specified. """ node_uuid = task.node.uuid LOG.debug('Sending node %(node)s raw bytes %(bytes)s', {'bytes': raw_bytes, 'node': node_uuid}) driver_info = _parse_driver_info(task.node) cmd = 'raw %s' % raw_bytes try: out, err = _exec_ipmitool(driver_info, cmd) LOG.debug('send raw bytes returned stdout: %(stdout)s, stderr:' ' %(stderr)s', {'stdout': out, 'stderr': err}) except (exception.PasswordFileFailedToCreate, processutils.ProcessExecutionError) as e: LOG.exception(_LE('IPMI "raw bytes" failed for node %(node_id)s ' 'with error: %(error)s.'), {'node_id': node_uuid, 'error': e}) raise exception.IPMIFailure(cmd=cmd) def _check_temp_dir(): """Check for Valid temp directory.""" global TMP_DIR_CHECKED # because a temporary file is used to pass the password to ipmitool, # we should check the directory if TMP_DIR_CHECKED is None: try: utils.check_dir() except (exception.PathNotFound, exception.DirectoryNotWritable, exception.InsufficientDiskSpace) as e: with excutils.save_and_reraise_exception(): TMP_DIR_CHECKED = False err_msg = (_("Ipmitool drivers need to be able to create " "temporary files to pass password to ipmitool. " "Encountered error: %s") % e) e.message = err_msg LOG.error(err_msg) else: TMP_DIR_CHECKED = True class IPMIPower(base.PowerInterface): def __init__(self): try: _check_option_support(['timing', 'single_bridge', 'dual_bridge']) except OSError: raise exception.DriverLoadError( driver=self.__class__.__name__, reason=_("Unable to locate usable ipmitool command in " "the system path when checking ipmitool version")) _check_temp_dir() def get_properties(self): return COMMON_PROPERTIES def validate(self, task): """Validate driver_info for ipmitool driver. Check that node['driver_info'] contains IPMI credentials. :param task: a TaskManager instance containing the node to act on. :raises: InvalidParameterValue if required ipmi parameters are missing. :raises: MissingParameterValue if a required parameter is missing. """ _parse_driver_info(task.node) # NOTE(deva): don't actually touch the BMC in validate because it is # called too often, and BMCs are too fragile. # This is a temporary measure to mitigate problems while # 1314954 and 1314961 are resolved. def get_power_state(self, task): """Get the current power state of the task's node. :param task: a TaskManager instance containing the node to act on. :returns: one of ironic.common.states POWER_OFF, POWER_ON or ERROR. :raises: InvalidParameterValue if required ipmi parameters are missing. :raises: MissingParameterValue if a required parameter is missing. :raises: IPMIFailure on an error from ipmitool (from _power_status call). """ driver_info = _parse_driver_info(task.node) return _power_status(driver_info) @task_manager.require_exclusive_lock def set_power_state(self, task, pstate): """Turn the power on or off. :param task: a TaskManager instance containing the node to act on. :param pstate: The desired power state, one of ironic.common.states POWER_ON, POWER_OFF. :raises: InvalidParameterValue if an invalid power state was specified. :raises: MissingParameterValue if required ipmi parameters are missing :raises: PowerStateFailure if the power couldn't be set to pstate. """ driver_info = _parse_driver_info(task.node) if pstate == states.POWER_ON: state = _power_on(driver_info) elif pstate == states.POWER_OFF: state = _power_off(driver_info) else: raise exception.InvalidParameterValue( _("set_power_state called " "with invalid power state %s.") % pstate) if state != pstate: raise exception.PowerStateFailure(pstate=pstate) @task_manager.require_exclusive_lock def reboot(self, task): """Cycles the power to the task's node. :param task: a TaskManager instance containing the node to act on. :raises: MissingParameterValue if required ipmi parameters are missing. :raises: InvalidParameterValue if an invalid power state was specified. :raises: PowerStateFailure if the final state of the node is not POWER_ON. """ driver_info = _parse_driver_info(task.node) _power_off(driver_info) state = _power_on(driver_info) if state != states.POWER_ON: raise exception.PowerStateFailure(pstate=states.POWER_ON) class IPMIManagement(base.ManagementInterface): def get_properties(self): return COMMON_PROPERTIES def __init__(self): try: _check_option_support(['timing', 'single_bridge', 'dual_bridge']) except OSError: raise exception.DriverLoadError( driver=self.__class__.__name__, reason=_("Unable to locate usable ipmitool command in " "the system path when checking ipmitool version")) _check_temp_dir() def validate(self, task): """Check that 'driver_info' contains IPMI credentials. Validates whether the 'driver_info' property of the supplied task's node contains the required credentials information. :param task: a task from TaskManager. :raises: InvalidParameterValue if required IPMI parameters are missing. :raises: MissingParameterValue if a required parameter is missing. """ _parse_driver_info(task.node) def get_supported_boot_devices(self, task): """Get a list of the supported boot devices. :param task: a task from TaskManager. :returns: A list with the supported boot devices defined in :mod:`ironic.common.boot_devices`. """ return [boot_devices.PXE, boot_devices.DISK, boot_devices.CDROM, boot_devices.BIOS, boot_devices.SAFE] @task_manager.require_exclusive_lock def set_boot_device(self, task, device, persistent=False): """Set the boot device for the task's node. Set the boot device to use on next reboot of the node. :param task: a task from TaskManager. :param device: the boot device, one of :mod:`ironic.common.boot_devices`. :param persistent: Boolean value. True if the boot device will persist to all future boots, False if not. Default: False. :raises: InvalidParameterValue if an invalid boot device is specified :raises: MissingParameterValue if required ipmi parameters are missing. :raises: IPMIFailure on an error from ipmitool. """ if device not in self.get_supported_boot_devices(task): raise exception.InvalidParameterValue(_( "Invalid boot device %s specified.") % device) # note(JayF): IPMI spec indicates unless you send these raw bytes the # boot device setting times out after 60s. Since it's possible it # could be >60s before a node is rebooted, we should always send them. # This mimics pyghmi's current behavior, and the "option=timeout" # setting on newer ipmitool binaries. timeout_disable = "0x00 0x08 0x03 0x08" send_raw(task, timeout_disable) cmd = "chassis bootdev %s" % device if persistent: cmd = cmd + " options=persistent" driver_info = _parse_driver_info(task.node) try: out, err = _exec_ipmitool(driver_info, cmd) except (exception.PasswordFileFailedToCreate, processutils.ProcessExecutionError) as e: LOG.warning(_LW('IPMI set boot device failed for node %(node)s ' 'when executing "ipmitool %(cmd)s". ' 'Error: %(error)s'), {'node': driver_info['uuid'], 'cmd': cmd, 'error': e}) raise exception.IPMIFailure(cmd=cmd) def get_boot_device(self, task): """Get the current boot device for the task's node. Returns the current boot device of the node. :param task: a task from TaskManager. :raises: InvalidParameterValue if required IPMI parameters are missing. :raises: IPMIFailure on an error from ipmitool. :raises: MissingParameterValue if a required parameter is missing. :returns: a dictionary containing: :boot_device: the boot device, one of :mod:`ironic.common.boot_devices` or None if it is unknown. :persistent: Whether the boot device will persist to all future boots or not, None if it is unknown. """ cmd = "chassis bootparam get 5" driver_info = _parse_driver_info(task.node) response = {'boot_device': None, 'persistent': None} try: out, err = _exec_ipmitool(driver_info, cmd) except (exception.PasswordFileFailedToCreate, processutils.ProcessExecutionError) as e: LOG.warning(_LW('IPMI get boot device failed for node %(node)s ' 'when executing "ipmitool %(cmd)s". ' 'Error: %(error)s'), {'node': driver_info['uuid'], 'cmd': cmd, 'error': e}) raise exception.IPMIFailure(cmd=cmd) re_obj = re.search('Boot Device Selector : (.+)?\n', out) if re_obj: boot_selector = re_obj.groups('')[0] if 'PXE' in boot_selector: response['boot_device'] = boot_devices.PXE elif 'Hard-Drive' in boot_selector: if 'Safe-Mode' in boot_selector: response['boot_device'] = boot_devices.SAFE else: response['boot_device'] = boot_devices.DISK elif 'BIOS' in boot_selector: response['boot_device'] = boot_devices.BIOS elif 'CD/DVD' in boot_selector: response['boot_device'] = boot_devices.CDROM response['persistent'] = 'Options apply to all future boots' in out return response def get_sensors_data(self, task): """Get sensors data. :param task: a TaskManager instance. :raises: FailedToGetSensorData when getting the sensor data fails. :raises: FailedToParseSensorData when parsing sensor data fails. :raises: InvalidParameterValue if required ipmi parameters are missing :raises: MissingParameterValue if a required parameter is missing. :returns: returns a dict of sensor data group by sensor type. """ driver_info = _parse_driver_info(task.node) # with '-v' option, we can get the entire sensor data including the # extended sensor informations cmd = "sdr -v" try: out, err = _exec_ipmitool(driver_info, cmd) except (exception.PasswordFileFailedToCreate, processutils.ProcessExecutionError) as e: raise exception.FailedToGetSensorData(node=task.node.uuid, error=e) return _parse_ipmi_sensors_data(task.node, out) class VendorPassthru(base.VendorInterface): def __init__(self): try: _check_option_support(['single_bridge', 'dual_bridge']) except OSError: raise exception.DriverLoadError( driver=self.__class__.__name__, reason=_("Unable to locate usable ipmitool command in " "the system path when checking ipmitool version")) _check_temp_dir() @base.passthru(['POST']) @task_manager.require_exclusive_lock def send_raw(self, task, http_method, raw_bytes): """Send raw bytes to the BMC. Bytes should be a string of bytes. :param task: a TaskManager instance. :param http_method: the HTTP method used on the request. :param raw_bytes: a string of raw bytes to send, e.g. '0x00 0x01' :raises: IPMIFailure on an error from ipmitool. :raises: MissingParameterValue if a required parameter is missing. :raises: InvalidParameterValue when an invalid value is specified. """ send_raw(task, raw_bytes) @base.passthru(['POST']) @task_manager.require_exclusive_lock def bmc_reset(self, task, http_method, warm=True): """Reset BMC with IPMI command 'bmc reset (warm|cold)'. :param task: a TaskManager instance. :param http_method: the HTTP method used on the request. :param warm: boolean parameter to decide on warm or cold reset. :raises: IPMIFailure on an error from ipmitool. :raises: MissingParameterValue if a required parameter is missing. :raises: InvalidParameterValue when an invalid value is specified """ node_uuid = task.node.uuid if warm: warm_param = 'warm' else: warm_param = 'cold' LOG.debug('Doing %(warm)s BMC reset on node %(node)s', {'warm': warm_param, 'node': node_uuid}) driver_info = _parse_driver_info(task.node) cmd = 'bmc reset %s' % warm_param try: out, err = _exec_ipmitool(driver_info, cmd) LOG.debug('bmc reset returned stdout: %(stdout)s, stderr:' ' %(stderr)s', {'stdout': out, 'stderr': err}) except (exception.PasswordFileFailedToCreate, processutils.ProcessExecutionError) as e: LOG.exception(_LE('IPMI "bmc reset" failed for node %(node_id)s ' 'with error: %(error)s.'), {'node_id': node_uuid, 'error': e}) raise exception.IPMIFailure(cmd=cmd) def get_properties(self): return COMMON_PROPERTIES def validate(self, task, method, **kwargs): """Validate vendor-specific actions. If invalid, raises an exception; otherwise returns None. Valid methods: * send_raw * bmc_reset :param task: a task from TaskManager. :param method: method to be validated :param kwargs: info for action. :raises: InvalidParameterValue when an invalid parameter value is specified. :raises: MissingParameterValue if a required parameter is missing. """ if method == 'send_raw': if not kwargs.get('raw_bytes'): raise exception.MissingParameterValue(_( 'Parameter raw_bytes (string of bytes) was not ' 'specified.')) _parse_driver_info(task.node) class IPMIShellinaboxConsole(base.ConsoleInterface): """A ConsoleInterface that uses ipmitool and shellinabox.""" def __init__(self): try: _check_option_support(['timing', 'single_bridge', 'dual_bridge']) except OSError: raise exception.DriverLoadError( driver=self.__class__.__name__, reason=_("Unable to locate usable ipmitool command in " "the system path when checking ipmitool version")) _check_temp_dir() def get_properties(self): d = COMMON_PROPERTIES.copy() d.update(CONSOLE_PROPERTIES) return d def validate(self, task): """Validate the Node console info. :param task: a task from TaskManager. :raises: InvalidParameterValue :raises: MissingParameterValue when a required parameter is missing """ driver_info = _parse_driver_info(task.node) if not driver_info['port']: raise exception.MissingParameterValue(_( "Missing 'ipmi_terminal_port' parameter in node's" " driver_info.")) if driver_info['protocol_version'] != '2.0': raise exception.InvalidParameterValue(_( "Serial over lan only works with IPMI protocol version 2.0. " "Check the 'ipmi_protocol_version' parameter in " "node's driver_info")) def start_console(self, task): """Start a remote console for the node. :param task: a task from TaskManager :raises: InvalidParameterValue if required ipmi parameters are missing :raises: PasswordFileFailedToCreate if unable to create a file containing the password :raises: ConsoleError if the directory for the PID file cannot be created :raises: ConsoleSubprocessFailed when invoking the subprocess failed """ driver_info = _parse_driver_info(task.node) path = _console_pwfile_path(driver_info['uuid']) pw_file = console_utils.make_persistent_password_file( path, driver_info['password']) ipmi_cmd = ("/:%(uid)s:%(gid)s:HOME:ipmitool -H %(address)s" " -I lanplus -U %(user)s -f %(pwfile)s" % {'uid': os.getuid(), 'gid': os.getgid(), 'address': driver_info['address'], 'user': driver_info['username'], 'pwfile': pw_file}) for name, option in BRIDGING_OPTIONS: if driver_info[name] is not None: ipmi_cmd = " ".join([ipmi_cmd, option, driver_info[name]]) if CONF.debug: ipmi_cmd += " -v" ipmi_cmd += " sol activate" try: console_utils.start_shellinabox_console(driver_info['uuid'], driver_info['port'], ipmi_cmd) except (exception.ConsoleError, exception.ConsoleSubprocessFailed): with excutils.save_and_reraise_exception(): utils.unlink_without_raise(path) def stop_console(self, task): """Stop the remote console session for the node. :param task: a task from TaskManager :raises: InvalidParameterValue if required ipmi parameters are missing :raises: ConsoleError if unable to stop the console """ driver_info = _parse_driver_info(task.node) try: console_utils.stop_shellinabox_console(driver_info['uuid']) finally: utils.unlink_without_raise( _console_pwfile_path(driver_info['uuid'])) def get_console(self, task): """Get the type and connection information about the console.""" driver_info = _parse_driver_info(task.node) url = console_utils.get_shellinabox_console_url(driver_info['port']) return {'type': 'shellinabox', 'url': url}
Tan0/ironic
ironic/drivers/modules/ipmitool.py
Python
apache-2.0
44,249
# Allium rudbaricum Boiss. & Buhse SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Amaryllidaceae/Allium/Allium erubescens/ Syn. Allium rudbaricum/README.md
Markdown
apache-2.0
189
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * 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.kie.dmn.openapi.impl; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.eclipse.microprofile.openapi.OASFactory; import org.eclipse.microprofile.openapi.models.media.Schema; import org.eclipse.microprofile.openapi.models.media.Schema.SchemaType; import org.kie.dmn.api.core.DMNType; import org.kie.dmn.core.impl.BaseDMNTypeImpl; import org.kie.dmn.core.impl.CompositeTypeImpl; import org.kie.dmn.core.impl.SimpleTypeImpl; import org.kie.dmn.openapi.NamingPolicy; import org.kie.dmn.openapi.model.DMNModelIOSets; import org.kie.dmn.openapi.model.DMNModelIOSets.DSIOSets; import org.kie.dmn.typesafe.DMNTypeUtils; public class DMNTypeSchemas { private final List<DMNModelIOSets> ioSets; private final Set<DMNType> typesIndex; private final NamingPolicy namingPolicy; public DMNTypeSchemas(List<DMNModelIOSets> ioSets, Set<DMNType> typesIndex, NamingPolicy namingPolicy) { this.ioSets = Collections.unmodifiableList(ioSets); this.typesIndex = Collections.unmodifiableSet(typesIndex); this.namingPolicy = namingPolicy; } public Map<DMNType, Schema> generateSchemas() { Map<DMNType, Schema> schemas = new HashMap<>(); for (DMNType t : typesIndex) { Schema schema = schemaFromType(t); schemas.put(t, schema); } return schemas; } private Schema refOrBuiltinSchema(DMNType t) { if (DMNTypeUtils.isFEELBuiltInType(t)) { return FEELBuiltinTypeSchemas.from(t); } if (typesIndex.contains(t)) { Schema schema = OASFactory.createObject(Schema.class).ref(namingPolicy.getRef(t)); return schema; } throw new UnsupportedOperationException(); } private boolean isIOSet(DMNType t) { for (DMNModelIOSets ios : ioSets) { if (ios.getInputSet().equals(t)) { return true; } for (DSIOSets ds : ios.getDSIOSets()) { if (ds.getDSInputSet().equals(t)) { return true; } } } return false; } private Schema schemaFromType(DMNType t) { if (t instanceof CompositeTypeImpl) { return schemaFromCompositeType((CompositeTypeImpl) t); } if (t instanceof SimpleTypeImpl) { return schemaFromSimpleType((SimpleTypeImpl) t); } throw new UnsupportedOperationException(); } private Schema schemaFromSimpleType(SimpleTypeImpl t) { DMNType baseType = t.getBaseType(); if (baseType == null) { throw new IllegalStateException(); } Schema schema = refOrBuiltinSchema(baseType); if (t.getAllowedValues() != null && !t.getAllowedValues().isEmpty()) { FEELSchemaEnum.parseAllowedValuesIntoSchema(schema, t.getAllowedValues()); } schema = nestAsItemIfCollection(schema, t); schema.addExtension(DMNOASConstants.X_DMN_TYPE, getDMNTypeSchemaXDMNTYPEdescr(t)); return schema; } private Schema schemaFromCompositeType(CompositeTypeImpl ct) { Schema schema = OASFactory.createObject(Schema.class).type(SchemaType.OBJECT); if (ct.getBaseType() == null) { // main case for (Entry<String, DMNType> fkv : ct.getFields().entrySet()) { schema.addProperty(fkv.getKey(), refOrBuiltinSchema(fkv.getValue())); } if (isIOSet(ct) && ct.getFields().size() > 0) { schema.required(new ArrayList<>(ct.getFields().keySet())); } } else if (ct.isCollection()) { schema = refOrBuiltinSchema(ct.getBaseType()); } else { throw new IllegalStateException(); } schema = nestAsItemIfCollection(schema, ct); schema.addExtension(DMNOASConstants.X_DMN_TYPE, getDMNTypeSchemaXDMNTYPEdescr(ct)); return schema; } private Schema nestAsItemIfCollection(Schema original, DMNType t) { if (t.isCollection()) { return OASFactory.createObject(Schema.class).type(SchemaType.ARRAY).items(original); } else { return original; } } private String getDMNTypeSchemaXDMNTYPEdescr(DMNType t) { if (((BaseDMNTypeImpl) t).getBelongingType() == null) { // internals for anonymous inner types. return t.toString(); } else { return null; } } }
droolsjbpm/drools
kie-dmn/kie-dmn-openapi/src/main/java/org/kie/dmn/openapi/impl/DMNTypeSchemas.java
Java
apache-2.0
5,225
Link analysis between john boards, dating websites, and prostitution websites to find serial/high frequency buyers. How it would work: Comparison of writing style across websites. There are a number of ways to tell if an author is the same across many mediums. Some parts of a writers signature will vary with context, but sort phrases and word choices will be consistent across mediums, for a small period of time. I believe the way this project would look is simple. I'd scrape the site types mentioned above, apply the necessary nlp, to establish matching conditions, and then try to build a single person for each handle. The expectation is that handles would change over time or that multiple handles may refer to a single person. Deliverables: Pictures associated with high volume consumers of commercial sex - many dating websites require you to upload pictures. And sometimes people just do this because. A more accurate representation of the number of active users of john boards. A set of ontologies of terms used by members of various john boards and how that ontology evolves over time and regionally. A greater understanding of the demand side by age, gender,ethnicity, and socio-economic class - often times people will post salary range, profession and other personal information on dating websites. A psychological understanding of high volume buyers of sex, statistically - often times people on dating websites will answer a series of questions indicating their psychological make up, used for matching algorithms. If we can link a profile to an investigation, a law enforcement agency could use subpoena compliance to obtain the list of questions and their answers. Such information could even be anonymized passed back to dating websites and be used to statistically flag for buyers of commercial sex by dating websites. This level of cooperation between companies and dating websites is unlikely, but possible. ##To Dos ##Scrapers: * Build a scraper for dating websites * Build scrapers for all of the prostitution websites * Do integrity testing of john board scraper/ integrate selenium scraper for deep web ##Identification of prostitution websites to scrape * adultsearch * alibaba * anunico * backpage * cityvibe * cityxguide * cityxguideforum * classivox * craigslist * ec21 * eroticmugshots * eroticreview * escortadsxxx * escortphonelist * escortsinca * escortsincollege * escortsintheus * gmdu * gulfjobsbank * happymassage * justlanded * liveescortreviews * manpowervacancy * massagetroll * missingkids * myproviderguide * myproviderguideforum * naughtyreviews * redbook * redbook_forum * rubads * sipsap * tradekey * usasexguide * utopiaguide ##Identification of John Boards to scrape * usasexguide.com * erotic review * Eros * city vibe ##Identification of dating websites to scrape - to do - indentify all of these * ##Database: * Choose a database for storing all of this information, pulling out keywords, hard attributes, and full text * implement the database Visualizations:
EricSchles/link_analyzer
documentation.md
Markdown
apache-2.0
3,043
<!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>My Website, improved</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="apple-touch-icon" href="apple-touch-icon.png"> <link rel="stylesheet" href="css/bootstrap.min.css"> <style> body { padding-top: 50px; padding-bottom: 20px; } </style> <link rel="stylesheet" href="css/bootstrap-theme.min.css"> <link rel="stylesheet" href="css/main.css"> <script src="js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script> </head> <body> <!--[if lt IE 8]> <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <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="#">Project name</a> </div> <div id="navbar" class="navbar-collapse collapse"> <form class="navbar-form navbar-right" role="form"> <div class="form-group"> <input type="text" placeholder="Email" class="form-control"> </div> <div class="form-group"> <input type="password" placeholder="Password" class="form-control"> </div> <button type="submit" class="btn btn-success">Sign in</button> </form> </div><!--/.navbar-collapse --> </div> </nav> <!-- Main jumbotron for a primary marketing message or call to action --> <div class="jumbotron"> <div class="container"> <h1>Hello, world!</h1> <p>This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique.</p> <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more &raquo;</a></p> </div> </div> <div class="container"> <!-- Example row of columns --> <div class="row"> <div class="col-md-4"> <h2>Heading</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p> </div> <div class="col-md-4"> <h2>Heading</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p> </div> <div class="col-md-4"> <h2>Heading</h2> <p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p> <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p> </div> </div> <hr> <footer> <p>&copy; Company 2015</p> </footer> </div> <!-- /container --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.2.min.js"><\/script>')</script> <script src="js/vendor/bootstrap.min.js"></script> <script src="js/main.js"></script> <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --> <script> (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]= function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date; e=o.createElement(i);r=o.getElementsByTagName(i)[0]; e.src='//www.google-analytics.com/analytics.js'; r.parentNode.insertBefore(e,r)}(window,document,'script','ga')); ga('create','UA-XXXXX-X','auto');ga('send','pageview'); </script> </body> </html>
dmourmouras/website
index.html
HTML
apache-2.0
5,152
<html> <head> <title>Inserir Veiculos</title> <link rel="stylesheet" href="estilo.css" type="text/css"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script language="JavaScript" type="text/javascript" src="..\MascaraValidacao.js"></script> <script> function busca(){ document.form.submit(); return true; } </script> </head> <body onload="document.form.PLACA.focus();"> <form name="form" method="post" action="InserirVeiculo2.php" onsubmit="return busca();"> <table width="100%" border="1" align="center" cellpadding="0" cellspacing="0" bordercolor="#CCCCCC"> <tr><td bgcolor="#CCCCCC" align="center" class="titulo">Inseri Veículo</td></tr> <tr> <table> <tr> <td>Placa</td> <td>Tipo</td> <td>Modelo</td> <td>Ano</td> <td>Cor</td> <td>Cliente</td> </tr> <tr> <td><input name="PLACA" type="text" id="PLACA" maxlength="8" onKeyPress="ColocaMascaraPlaca(document.form.PLACA);"/></td> <td><select name=TIPO> <option value="Carro">Carro</option> <option value="Moto">Moto</option> <option value="Caminhao">Caminhão</option> <option value="Outro">Outro</option> </select></td> <td><input name="MODELO" type="text" id="MODELO" maxlength="30"/></td> <td><input name="ANO" type="text" id="ANO" maxlength="4"/></td> <td><input name="COR" type="text" id="COR" maxlength="15"/></td> <td><?php require_once('funcoes.php'); conectar('localhost', 'root','', 'bd_estacionamento'); $sql=mysql_query("SELECT nome_cliente,id_cliente FROM clientes order by nome_cliente"); echo "<select name=CLIENTES>"; while($rowl = mysql_fetch_assoc($sql)){ echo "<option value=". $rowl['id_cliente'] . ">" . $rowl['nome_cliente'] . "</option>"; } echo "</select>";// Closing of list box ?></td> <td><input type="submit" name="Submit" value="Incluir"</td> </tr> </table> </tr> </table> </form> <?php require_once('funcoes.php'); conectar('localhost', 'root','', 'bd_estacionamento'); $PLACA = $_POST["PLACA"]; $TIPO = $_POST["TIPO"]; $MODELO = $_POST["MODELO"]; $ANO = $_POST["ANO"]; $COR = $_POST["COR"]; $CLIENTES = $_POST["CLIENTES"]; $query = "INSERT INTO veiculos VALUES('', '$TIPO', '$ANO', '$PLACA', '$MODELO', '$COR', '$CLIENTES')"; mysql_query($query) or die ('Falha ao executar query no banco de dados'); mysql_close() or die ('Falha ao fechar o banco de dados'); ?> <?php require_once('funcoes.php'); conectar('localhost', 'root','', 'bd_estacionamento'); $result = mysql_query("SELECT * FROM veiculos"); echo "<table border=5 style=3 width=100%><tr><td>ID</td><td>Placa</td><td>Tipo</td><td>Modelo</td><td>Ano</td><td>Cor</td><td>Cliente</td></tr>"; while($row = mysql_fetch_assoc($result)){ echo "<tr><td>".$row['id_veiculo']."</td>"."<td>".$row['placa_veiculo']."</td>"."<td>".$row['tipo_veiculo']."</td>"."<td>".$row['modelo_veiculo']."</td>"."<td>".$row['ano_veiculo']."</td>"."<td>".$row['cor_veiculo']."</td>"; $fk = mysql_fetch_assoc(mysql_query("SELECT * FROM clientes where id_cliente='".$row['fk_cliente_veiculo']."'")); echo "<td>".$fk['nome_cliente']."</td></tr>"; } echo "</table><br><br>"; echo ""; ?> </body> </html>
danilohenriqueandrade/AtividadeFinal
home/Veiculos/InserirVeiculo2.php
PHP
apache-2.0
3,283
/* * Copyright 2018 OPS4J 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 org.ops4j.kaiserkai.rest; import com.spotify.docker.client.auth.RegistryAuthSupplier; import com.spotify.docker.client.exceptions.DockerException; import com.spotify.docker.client.messages.RegistryAuth; import com.spotify.docker.client.messages.RegistryConfigs; /** * @author Harald Wellmann * */ public class LocalAuthSupplier implements RegistryAuthSupplier { @Override public RegistryAuth authFor(String imageName) throws DockerException { if (imageName.startsWith("127.0.0.1")) { RegistryAuth auth = RegistryAuth.builder().username("admin").password("admin").build(); return auth; } return null; } @Override public RegistryAuth authForSwarm() throws DockerException { return null; } @Override public RegistryConfigs authForBuild() throws DockerException { return null; } }
hwellmann/org.ops4j.kaiserkai
kaiserkai-itest/src/test/java/org/ops4j/kaiserkai/rest/LocalAuthSupplier.java
Java
apache-2.0
1,497