max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
435 | {
"description": "The `Bokeh data visualization library <http://bokeh.pydata.org/>`__\nallows you to build interactive visualizations for the web in python. It\nhas a range of capabilities from quick \"one-line\" charts to streaming\ndatasets to integrating with your existing plot libraries such as\nmatplotlib or ggplot.\n\nThis training gives a quick hands-on introduction to Bokeh's core\nfeatures. We'll do exercises building up a variety of visualizations and\nfinish up discussing topics and questions from participants related to\ntheir own datasets & needs.\n\nThis is the planned outline:\n\n- (20 minutes) Bokeh feature walk-through. The relationship between\n bokeh, bokehjs and bokeh-server. The various API levels of bokeh\n (models, plotting, charts). And, examples of a variety of\n visualizations.\n\n- (20 minutes): Exercises - 1 - The charts & plotting interface. Get\n quickly plotting in an ipython notebook. Different types of data\n accepted, and how to customize a plot.\n\n- (10 minutes): Tips for navigating the Bokeh docs and examples as\n you're getting up to speed.\n\n- (20 minutes): Exercises - 2 - (a) The models interface. Build a\n custom plot from the ground up using the Models API. (b) Quick, yet\n custom, using the charts interface and models together.\n\n- (10 minutes): Sharing your plots. Overview of the different ways to\n share your plots with your colleagues and the world.\n\n- (20 minutes): Exercises - 3 - Add custom interactivity - Customize\n your hover and selections. Implement linked selection, brushing, and\n panning.\n\n- (20 minutes): open space for questions and interactively solving\n Bokeh problems on your real-life problems & data as time permits.\n",
"duration": 4774,
"language": "eng",
"recorded": "2015-06-19",
"speakers": [
"<NAME>",
"<NAME>"
],
"summary": "The Bokeh data visualization library allows you to build interactive\nvisualizations for the web in python. This training gives a quick\nintroduction to Bokeh's unique features. We'll do exercixes building\nup a variety of visualizations and finish discussing topics and\nquestions from participants related to their own datasets & needs.",
"thumbnail_url": "https://i.ytimg.com/vi/XBiS0oBzX3o/hqdefault.jpg",
"title": "Getting started with Bokeh / Let's build an interactive data visualization for the web..in Python!",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=XBiS0oBzX3o"
}
]
}
| 754 |
416 | /*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.cat.v20180409.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class CatLog extends AbstractModel{
/**
* 拨测时间点
*/
@SerializedName("Time")
@Expose
private String Time;
/**
* 拨测类型
*/
@SerializedName("CatTypeName")
@Expose
private String CatTypeName;
/**
* 任务ID
*/
@SerializedName("TaskId")
@Expose
private Long TaskId;
/**
* 拨测点所在城市
*/
@SerializedName("City")
@Expose
private String City;
/**
* 拨测点所在运营商
*/
@SerializedName("Isp")
@Expose
private String Isp;
/**
* 被拨测Server的IP
*/
@SerializedName("ServerIp")
@Expose
private String ServerIp;
/**
* 被拨测Server的域名
*/
@SerializedName("DomainName")
@Expose
private String DomainName;
/**
* 执行耗时,单位毫秒
*/
@SerializedName("TotalTime")
@Expose
private Long TotalTime;
/**
* 成功失败(1 失败,0 成功)
*/
@SerializedName("ResultType")
@Expose
private Long ResultType;
/**
* 失败错误码
*/
@SerializedName("ResultCode")
@Expose
private Long ResultCode;
/**
* 请求包大小
*/
@SerializedName("ReqPkgSize")
@Expose
private Long ReqPkgSize;
/**
* 回应包大小
*/
@SerializedName("RspPkgSize")
@Expose
private Long RspPkgSize;
/**
* 拨测请求
*/
@SerializedName("ReqMsg")
@Expose
private String ReqMsg;
/**
* 拨测回应
*/
@SerializedName("RespMsg")
@Expose
private String RespMsg;
/**
* 客户端IP
*/
@SerializedName("ClientIp")
@Expose
private String ClientIp;
/**
* 拨测点所在城市名称
*/
@SerializedName("CityName")
@Expose
private String CityName;
/**
* 拨测点所在运营商名称
*/
@SerializedName("IspName")
@Expose
private String IspName;
/**
* 解析耗时,单位毫秒
*/
@SerializedName("ParseTime")
@Expose
private Long ParseTime;
/**
* 连接耗时,单位毫秒
*/
@SerializedName("ConnectTime")
@Expose
private Long ConnectTime;
/**
* 数据发送耗时,单位毫秒
*/
@SerializedName("SendTime")
@Expose
private Long SendTime;
/**
* 等待耗时,单位毫秒
*/
@SerializedName("WaitTime")
@Expose
private Long WaitTime;
/**
* 接收耗时,单位毫秒
*/
@SerializedName("ReceiveTime")
@Expose
private Long ReceiveTime;
/**
* Get 拨测时间点
* @return Time 拨测时间点
*/
public String getTime() {
return this.Time;
}
/**
* Set 拨测时间点
* @param Time 拨测时间点
*/
public void setTime(String Time) {
this.Time = Time;
}
/**
* Get 拨测类型
* @return CatTypeName 拨测类型
*/
public String getCatTypeName() {
return this.CatTypeName;
}
/**
* Set 拨测类型
* @param CatTypeName 拨测类型
*/
public void setCatTypeName(String CatTypeName) {
this.CatTypeName = CatTypeName;
}
/**
* Get 任务ID
* @return TaskId 任务ID
*/
public Long getTaskId() {
return this.TaskId;
}
/**
* Set 任务ID
* @param TaskId 任务ID
*/
public void setTaskId(Long TaskId) {
this.TaskId = TaskId;
}
/**
* Get 拨测点所在城市
* @return City 拨测点所在城市
*/
public String getCity() {
return this.City;
}
/**
* Set 拨测点所在城市
* @param City 拨测点所在城市
*/
public void setCity(String City) {
this.City = City;
}
/**
* Get 拨测点所在运营商
* @return Isp 拨测点所在运营商
*/
public String getIsp() {
return this.Isp;
}
/**
* Set 拨测点所在运营商
* @param Isp 拨测点所在运营商
*/
public void setIsp(String Isp) {
this.Isp = Isp;
}
/**
* Get 被拨测Server的IP
* @return ServerIp 被拨测Server的IP
*/
public String getServerIp() {
return this.ServerIp;
}
/**
* Set 被拨测Server的IP
* @param ServerIp 被拨测Server的IP
*/
public void setServerIp(String ServerIp) {
this.ServerIp = ServerIp;
}
/**
* Get 被拨测Server的域名
* @return DomainName 被拨测Server的域名
*/
public String getDomainName() {
return this.DomainName;
}
/**
* Set 被拨测Server的域名
* @param DomainName 被拨测Server的域名
*/
public void setDomainName(String DomainName) {
this.DomainName = DomainName;
}
/**
* Get 执行耗时,单位毫秒
* @return TotalTime 执行耗时,单位毫秒
*/
public Long getTotalTime() {
return this.TotalTime;
}
/**
* Set 执行耗时,单位毫秒
* @param TotalTime 执行耗时,单位毫秒
*/
public void setTotalTime(Long TotalTime) {
this.TotalTime = TotalTime;
}
/**
* Get 成功失败(1 失败,0 成功)
* @return ResultType 成功失败(1 失败,0 成功)
*/
public Long getResultType() {
return this.ResultType;
}
/**
* Set 成功失败(1 失败,0 成功)
* @param ResultType 成功失败(1 失败,0 成功)
*/
public void setResultType(Long ResultType) {
this.ResultType = ResultType;
}
/**
* Get 失败错误码
* @return ResultCode 失败错误码
*/
public Long getResultCode() {
return this.ResultCode;
}
/**
* Set 失败错误码
* @param ResultCode 失败错误码
*/
public void setResultCode(Long ResultCode) {
this.ResultCode = ResultCode;
}
/**
* Get 请求包大小
* @return ReqPkgSize 请求包大小
*/
public Long getReqPkgSize() {
return this.ReqPkgSize;
}
/**
* Set 请求包大小
* @param ReqPkgSize 请求包大小
*/
public void setReqPkgSize(Long ReqPkgSize) {
this.ReqPkgSize = ReqPkgSize;
}
/**
* Get 回应包大小
* @return RspPkgSize 回应包大小
*/
public Long getRspPkgSize() {
return this.RspPkgSize;
}
/**
* Set 回应包大小
* @param RspPkgSize 回应包大小
*/
public void setRspPkgSize(Long RspPkgSize) {
this.RspPkgSize = RspPkgSize;
}
/**
* Get 拨测请求
* @return ReqMsg 拨测请求
*/
public String getReqMsg() {
return this.ReqMsg;
}
/**
* Set 拨测请求
* @param ReqMsg 拨测请求
*/
public void setReqMsg(String ReqMsg) {
this.ReqMsg = ReqMsg;
}
/**
* Get 拨测回应
* @return RespMsg 拨测回应
*/
public String getRespMsg() {
return this.RespMsg;
}
/**
* Set 拨测回应
* @param RespMsg 拨测回应
*/
public void setRespMsg(String RespMsg) {
this.RespMsg = RespMsg;
}
/**
* Get 客户端IP
* @return ClientIp 客户端IP
*/
public String getClientIp() {
return this.ClientIp;
}
/**
* Set 客户端IP
* @param ClientIp 客户端IP
*/
public void setClientIp(String ClientIp) {
this.ClientIp = ClientIp;
}
/**
* Get 拨测点所在城市名称
* @return CityName 拨测点所在城市名称
*/
public String getCityName() {
return this.CityName;
}
/**
* Set 拨测点所在城市名称
* @param CityName 拨测点所在城市名称
*/
public void setCityName(String CityName) {
this.CityName = CityName;
}
/**
* Get 拨测点所在运营商名称
* @return IspName 拨测点所在运营商名称
*/
public String getIspName() {
return this.IspName;
}
/**
* Set 拨测点所在运营商名称
* @param IspName 拨测点所在运营商名称
*/
public void setIspName(String IspName) {
this.IspName = IspName;
}
/**
* Get 解析耗时,单位毫秒
* @return ParseTime 解析耗时,单位毫秒
*/
public Long getParseTime() {
return this.ParseTime;
}
/**
* Set 解析耗时,单位毫秒
* @param ParseTime 解析耗时,单位毫秒
*/
public void setParseTime(Long ParseTime) {
this.ParseTime = ParseTime;
}
/**
* Get 连接耗时,单位毫秒
* @return ConnectTime 连接耗时,单位毫秒
*/
public Long getConnectTime() {
return this.ConnectTime;
}
/**
* Set 连接耗时,单位毫秒
* @param ConnectTime 连接耗时,单位毫秒
*/
public void setConnectTime(Long ConnectTime) {
this.ConnectTime = ConnectTime;
}
/**
* Get 数据发送耗时,单位毫秒
* @return SendTime 数据发送耗时,单位毫秒
*/
public Long getSendTime() {
return this.SendTime;
}
/**
* Set 数据发送耗时,单位毫秒
* @param SendTime 数据发送耗时,单位毫秒
*/
public void setSendTime(Long SendTime) {
this.SendTime = SendTime;
}
/**
* Get 等待耗时,单位毫秒
* @return WaitTime 等待耗时,单位毫秒
*/
public Long getWaitTime() {
return this.WaitTime;
}
/**
* Set 等待耗时,单位毫秒
* @param WaitTime 等待耗时,单位毫秒
*/
public void setWaitTime(Long WaitTime) {
this.WaitTime = WaitTime;
}
/**
* Get 接收耗时,单位毫秒
* @return ReceiveTime 接收耗时,单位毫秒
*/
public Long getReceiveTime() {
return this.ReceiveTime;
}
/**
* Set 接收耗时,单位毫秒
* @param ReceiveTime 接收耗时,单位毫秒
*/
public void setReceiveTime(Long ReceiveTime) {
this.ReceiveTime = ReceiveTime;
}
public CatLog() {
}
/**
* NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy,
* and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy.
*/
public CatLog(CatLog source) {
if (source.Time != null) {
this.Time = new String(source.Time);
}
if (source.CatTypeName != null) {
this.CatTypeName = new String(source.CatTypeName);
}
if (source.TaskId != null) {
this.TaskId = new Long(source.TaskId);
}
if (source.City != null) {
this.City = new String(source.City);
}
if (source.Isp != null) {
this.Isp = new String(source.Isp);
}
if (source.ServerIp != null) {
this.ServerIp = new String(source.ServerIp);
}
if (source.DomainName != null) {
this.DomainName = new String(source.DomainName);
}
if (source.TotalTime != null) {
this.TotalTime = new Long(source.TotalTime);
}
if (source.ResultType != null) {
this.ResultType = new Long(source.ResultType);
}
if (source.ResultCode != null) {
this.ResultCode = new Long(source.ResultCode);
}
if (source.ReqPkgSize != null) {
this.ReqPkgSize = new Long(source.ReqPkgSize);
}
if (source.RspPkgSize != null) {
this.RspPkgSize = new Long(source.RspPkgSize);
}
if (source.ReqMsg != null) {
this.ReqMsg = new String(source.ReqMsg);
}
if (source.RespMsg != null) {
this.RespMsg = new String(source.RespMsg);
}
if (source.ClientIp != null) {
this.ClientIp = new String(source.ClientIp);
}
if (source.CityName != null) {
this.CityName = new String(source.CityName);
}
if (source.IspName != null) {
this.IspName = new String(source.IspName);
}
if (source.ParseTime != null) {
this.ParseTime = new Long(source.ParseTime);
}
if (source.ConnectTime != null) {
this.ConnectTime = new Long(source.ConnectTime);
}
if (source.SendTime != null) {
this.SendTime = new Long(source.SendTime);
}
if (source.WaitTime != null) {
this.WaitTime = new Long(source.WaitTime);
}
if (source.ReceiveTime != null) {
this.ReceiveTime = new Long(source.ReceiveTime);
}
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "Time", this.Time);
this.setParamSimple(map, prefix + "CatTypeName", this.CatTypeName);
this.setParamSimple(map, prefix + "TaskId", this.TaskId);
this.setParamSimple(map, prefix + "City", this.City);
this.setParamSimple(map, prefix + "Isp", this.Isp);
this.setParamSimple(map, prefix + "ServerIp", this.ServerIp);
this.setParamSimple(map, prefix + "DomainName", this.DomainName);
this.setParamSimple(map, prefix + "TotalTime", this.TotalTime);
this.setParamSimple(map, prefix + "ResultType", this.ResultType);
this.setParamSimple(map, prefix + "ResultCode", this.ResultCode);
this.setParamSimple(map, prefix + "ReqPkgSize", this.ReqPkgSize);
this.setParamSimple(map, prefix + "RspPkgSize", this.RspPkgSize);
this.setParamSimple(map, prefix + "ReqMsg", this.ReqMsg);
this.setParamSimple(map, prefix + "RespMsg", this.RespMsg);
this.setParamSimple(map, prefix + "ClientIp", this.ClientIp);
this.setParamSimple(map, prefix + "CityName", this.CityName);
this.setParamSimple(map, prefix + "IspName", this.IspName);
this.setParamSimple(map, prefix + "ParseTime", this.ParseTime);
this.setParamSimple(map, prefix + "ConnectTime", this.ConnectTime);
this.setParamSimple(map, prefix + "SendTime", this.SendTime);
this.setParamSimple(map, prefix + "WaitTime", this.WaitTime);
this.setParamSimple(map, prefix + "ReceiveTime", this.ReceiveTime);
}
}
| 7,817 |
1,405 | <reponame>jarekankowski/pegasus_spyware<filename>sample4/recompiled_java/sources/org/apache/commons/httpclient/cookie/RFC2965Spec.java
package org.apache.commons.httpclient.cookie;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HeaderElement;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.util.ParameterFormatter;
public class RFC2965Spec extends CookieSpecBase implements CookieVersionSupport {
public static final String SET_COOKIE2_KEY = "set-cookie2";
private static final Comparator b = new CookiePathComparator();
private final ParameterFormatter c = new ParameterFormatter();
private final List d;
private final Map e;
private final CookieSpec f;
static boolean a(int x1, int[] x2) {
for (int i2 : x2) {
if (x1 == i2) {
return true;
}
}
return false;
}
static int[] a(String x1) throws MalformedCookieException {
return b(x1);
}
public RFC2965Spec() {
this.c.setAlwaysUseQuotes(true);
this.e = new HashMap(10);
this.d = new ArrayList(10);
this.f = new RFC2109Spec();
registerAttribHandler(Cookie2.PATH, new c(this, (byte) 0));
registerAttribHandler(Cookie2.DOMAIN, new a(this, (byte) 0));
registerAttribHandler(Cookie2.PORT, new d(this, (byte) 0));
registerAttribHandler(Cookie2.MAXAGE, new b(this, (byte) 0));
registerAttribHandler(Cookie2.SECURE, new i(this, (byte) 0));
registerAttribHandler(Cookie2.COMMENT, new f(this, (byte) 0));
registerAttribHandler(Cookie2.COMMENTURL, new g(this, (byte) 0));
registerAttribHandler(Cookie2.DISCARD, new h(this, (byte) 0));
registerAttribHandler("version", new e(this, (byte) 0));
}
/* access modifiers changed from: protected */
public void registerAttribHandler(String name, CookieAttributeHandler handler) {
if (name == null) {
throw new IllegalArgumentException("Attribute name may not be null");
} else if (handler == null) {
throw new IllegalArgumentException("Attribute handler may not be null");
} else {
if (!this.d.contains(handler)) {
this.d.add(handler);
}
this.e.put(name, handler);
}
}
/* access modifiers changed from: protected */
public CookieAttributeHandler findAttribHandler(String name) {
return (CookieAttributeHandler) this.e.get(name);
}
/* access modifiers changed from: protected */
public CookieAttributeHandler getAttribHandler(String name) {
CookieAttributeHandler handler = findAttribHandler(name);
if (handler != null) {
return handler;
}
throw new IllegalStateException(new StringBuffer().append("Handler not registered for ").append(name).append(" attribute.").toString());
}
/* access modifiers changed from: protected */
public Iterator getAttribHandlerIterator() {
return this.d.iterator();
}
@Override // org.apache.commons.httpclient.cookie.CookieSpec, org.apache.commons.httpclient.cookie.CookieSpecBase
public Cookie[] parse(String host, int port, String path, boolean secure, Header header) throws MalformedCookieException {
LOG.trace("enter RFC2965.parse(String, int, String, boolean, Header)");
if (header == null) {
throw new IllegalArgumentException("Header may not be null.");
} else if (header.getName() == null) {
throw new IllegalArgumentException("Header name may not be null.");
} else if (header.getName().equalsIgnoreCase(SET_COOKIE2_KEY)) {
return parse(host, port, path, secure, header.getValue());
} else {
if (header.getName().equalsIgnoreCase(RFC2109Spec.SET_COOKIE_KEY)) {
return this.f.parse(host, port, path, secure, header.getValue());
}
throw new MalformedCookieException("Header name is not valid. RFC 2965 supports \"set-cookie\" and \"set-cookie2\" headers.");
}
}
@Override // org.apache.commons.httpclient.cookie.CookieSpec, org.apache.commons.httpclient.cookie.CookieSpecBase
public Cookie[] parse(String host, int port, String path, boolean secure, String header) throws MalformedCookieException {
LOG.trace("enter RFC2965Spec.parse(String, int, String, boolean, String)");
if (host == null) {
throw new IllegalArgumentException("Host of origin may not be null");
} else if (host.trim().equals("")) {
throw new IllegalArgumentException("Host of origin may not be blank");
} else if (port < 0) {
throw new IllegalArgumentException(new StringBuffer().append("Invalid port: ").append(port).toString());
} else if (path == null) {
throw new IllegalArgumentException("Path of origin may not be null.");
} else if (header == null) {
throw new IllegalArgumentException("Header may not be null.");
} else {
if (path.trim().equals("")) {
path = CookieSpec.PATH_DELIM;
}
String host2 = c(host);
HeaderElement[] headerElements = HeaderElement.parseElements(header.toCharArray());
List cookies = new LinkedList();
for (HeaderElement headerelement : headerElements) {
try {
Cookie2 cookie = new Cookie2(host2, headerelement.getName(), headerelement.getValue(), path, null, false, new int[]{port});
NameValuePair[] parameters = headerelement.getParameters();
if (parameters != null) {
Map attribmap = new HashMap(parameters.length);
for (int j = parameters.length - 1; j >= 0; j--) {
NameValuePair param = parameters[j];
attribmap.put(param.getName().toLowerCase(), param);
}
for (Map.Entry entry : attribmap.entrySet()) {
parseAttribute((NameValuePair) entry.getValue(), cookie);
}
}
cookies.add(cookie);
} catch (IllegalArgumentException ex) {
throw new MalformedCookieException(ex.getMessage());
}
}
return (Cookie[]) cookies.toArray(new Cookie[cookies.size()]);
}
}
@Override // org.apache.commons.httpclient.cookie.CookieSpec, org.apache.commons.httpclient.cookie.CookieSpecBase
public void parseAttribute(NameValuePair attribute, Cookie cookie) throws MalformedCookieException {
if (attribute == null) {
throw new IllegalArgumentException("Attribute may not be null.");
} else if (attribute.getName() == null) {
throw new IllegalArgumentException("Attribute Name may not be null.");
} else if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null.");
} else {
String paramName = attribute.getName().toLowerCase();
String paramValue = attribute.getValue();
CookieAttributeHandler handler = findAttribHandler(paramName);
if (handler != null) {
handler.parse(cookie, paramValue);
} else if (LOG.isDebugEnabled()) {
LOG.debug(new StringBuffer().append("Unrecognized cookie attribute: ").append(attribute.toString()).toString());
}
}
}
@Override // org.apache.commons.httpclient.cookie.CookieSpec, org.apache.commons.httpclient.cookie.CookieSpecBase
public void validate(String host, int port, String path, boolean secure, Cookie cookie) throws MalformedCookieException {
LOG.trace("enter RFC2965Spec.validate(String, int, String, boolean, Cookie)");
if (!(cookie instanceof Cookie2)) {
this.f.validate(host, port, path, secure, cookie);
} else if (cookie.getName().indexOf(32) != -1) {
throw new MalformedCookieException("Cookie name may not contain blanks");
} else if (cookie.getName().startsWith("$")) {
throw new MalformedCookieException("Cookie name may not start with $");
} else {
CookieOrigin origin = new CookieOrigin(c(host), port, path, secure);
Iterator i2 = getAttribHandlerIterator();
while (i2.hasNext()) {
((CookieAttributeHandler) i2.next()).validate(cookie, origin);
}
}
}
@Override // org.apache.commons.httpclient.cookie.CookieSpec, org.apache.commons.httpclient.cookie.CookieSpecBase
public boolean match(String host, int port, String path, boolean secure, Cookie cookie) {
LOG.trace("enter RFC2965.match(String, int, String, boolean, Cookie");
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
} else if (!(cookie instanceof Cookie2)) {
return this.f.match(host, port, path, secure, cookie);
} else {
if (cookie.isPersistent() && cookie.isExpired()) {
return false;
}
CookieOrigin origin = new CookieOrigin(c(host), port, path, secure);
Iterator i2 = getAttribHandlerIterator();
while (i2.hasNext()) {
if (!((CookieAttributeHandler) i2.next()).match(cookie, origin)) {
return false;
}
}
return true;
}
}
private void a(Cookie2 cookie, StringBuffer buffer) {
String name = cookie.getName();
String value = cookie.getValue();
if (value == null) {
value = "";
}
this.c.format(buffer, new NameValuePair(name, value));
if (cookie.getDomain() != null && cookie.isDomainAttributeSpecified()) {
buffer.append("; ");
this.c.format(buffer, new NameValuePair("$Domain", cookie.getDomain()));
}
if (cookie.getPath() != null && cookie.isPathAttributeSpecified()) {
buffer.append("; ");
this.c.format(buffer, new NameValuePair("$Path", cookie.getPath()));
}
if (cookie.isPortAttributeSpecified()) {
String portValue = "";
if (!cookie.isPortAttributeBlank()) {
int[] ports = cookie.getPorts();
StringBuffer stringBuffer = new StringBuffer();
int length = ports.length;
for (int i2 = 0; i2 < length; i2++) {
if (i2 > 0) {
stringBuffer.append(",");
}
stringBuffer.append(ports[i2]);
}
portValue = stringBuffer.toString();
}
buffer.append("; ");
this.c.format(buffer, new NameValuePair("$Port", portValue));
}
}
@Override // org.apache.commons.httpclient.cookie.CookieSpec, org.apache.commons.httpclient.cookie.CookieSpecBase
public String formatCookie(Cookie cookie) {
LOG.trace("enter RFC2965Spec.formatCookie(Cookie)");
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
} else if (!(cookie instanceof Cookie2)) {
return this.f.formatCookie(cookie);
} else {
Cookie2 cookie2 = (Cookie2) cookie;
int version = cookie2.getVersion();
StringBuffer buffer = new StringBuffer();
this.c.format(buffer, new NameValuePair("$Version", Integer.toString(version)));
buffer.append("; ");
a(cookie2, buffer);
return buffer.toString();
}
}
@Override // org.apache.commons.httpclient.cookie.CookieSpec, org.apache.commons.httpclient.cookie.CookieSpecBase
public String formatCookies(Cookie[] cookies) {
LOG.trace("enter RFC2965Spec.formatCookieHeader(Cookie[])");
if (cookies == null) {
throw new IllegalArgumentException("Cookies may not be null");
}
boolean hasOldStyleCookie = false;
int version = -1;
int i2 = 0;
while (true) {
if (i2 >= cookies.length) {
break;
}
Cookie cookie = cookies[i2];
if (!(cookie instanceof Cookie2)) {
hasOldStyleCookie = true;
break;
}
if (cookie.getVersion() > version) {
version = cookie.getVersion();
}
i2++;
}
if (version < 0) {
version = 0;
}
if (hasOldStyleCookie || version < 1) {
return this.f.formatCookies(cookies);
}
Arrays.sort(cookies, b);
StringBuffer buffer = new StringBuffer();
this.c.format(buffer, new NameValuePair("$Version", Integer.toString(version)));
for (Cookie cookie2 : cookies) {
buffer.append("; ");
a((Cookie2) cookie2, buffer);
}
return buffer.toString();
}
private static int[] b(String portValue) throws MalformedCookieException {
StringTokenizer st = new StringTokenizer(portValue, ",");
int[] ports = new int[st.countTokens()];
int i2 = 0;
while (st.hasMoreTokens()) {
try {
ports[i2] = Integer.parseInt(st.nextToken().trim());
if (ports[i2] < 0) {
throw new MalformedCookieException("Invalid Port attribute.");
}
i2++;
} catch (NumberFormatException e2) {
throw new MalformedCookieException(new StringBuffer().append("Invalid Port attribute: ").append(e2.getMessage()).toString());
}
}
return ports;
}
private static String c(String host) {
String effectiveHost = host.toLowerCase();
if (host.indexOf(46) < 0) {
return new StringBuffer().append(effectiveHost).append(".local").toString();
}
return effectiveHost;
}
@Override // org.apache.commons.httpclient.cookie.CookieSpec, org.apache.commons.httpclient.cookie.CookieSpecBase
public boolean domainMatch(String host, String domain) {
return host.equals(domain) || (domain.startsWith(".") && host.endsWith(domain));
}
private class c implements CookieAttributeHandler {
private final RFC2965Spec a;
private c(RFC2965Spec rFC2965Spec) {
this.a = rFC2965Spec;
}
c(RFC2965Spec x0, byte b) {
this(x0);
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void parse(Cookie cookie, String path) throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
} else if (path == null) {
throw new MalformedCookieException("Missing value for path attribute");
} else if (path.trim().equals("")) {
throw new MalformedCookieException("Blank value for path attribute");
} else {
cookie.setPath(path);
cookie.setPathAttributeSpecified(true);
}
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
} else if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
} else {
String path = origin.getPath();
if (path == null) {
throw new IllegalArgumentException("Path of origin host may not be null.");
} else if (cookie.getPath() == null) {
throw new MalformedCookieException("Invalid cookie state: path attribute is null.");
} else {
if (path.trim().equals("")) {
path = CookieSpec.PATH_DELIM;
}
if (!this.a.pathMatch(path, cookie.getPath())) {
throw new MalformedCookieException(new StringBuffer().append("Illegal path attribute \"").append(cookie.getPath()).append("\". Path of origin: \"").append(path).append(com.lenovo.lps.sus.c.c.M).toString());
}
}
}
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final boolean match(Cookie cookie, CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
} else if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
} else {
String path = origin.getPath();
if (cookie.getPath() == null) {
CookieSpecBase.LOG.warn("Invalid cookie state: path attribute is null.");
return false;
}
if (path.trim().equals("")) {
path = CookieSpec.PATH_DELIM;
}
if (this.a.pathMatch(path, cookie.getPath())) {
return true;
}
return false;
}
}
}
private class a implements CookieAttributeHandler {
private final RFC2965Spec a;
private a(RFC2965Spec rFC2965Spec) {
this.a = rFC2965Spec;
}
a(RFC2965Spec x0, byte b) {
this(x0);
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void parse(Cookie cookie, String domain) throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
} else if (domain == null) {
throw new MalformedCookieException("Missing value for domain attribute");
} else if (domain.trim().equals("")) {
throw new MalformedCookieException("Blank value for domain attribute");
} else {
String domain2 = domain.toLowerCase();
if (!domain2.startsWith(".")) {
domain2 = new StringBuffer().append(".").append(domain2).toString();
}
cookie.setDomain(domain2);
cookie.setDomainAttributeSpecified(true);
}
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
} else if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
} else {
String host = origin.getHost().toLowerCase();
if (cookie.getDomain() == null) {
throw new MalformedCookieException("Invalid cookie state: domain not specified");
}
String cookieDomain = cookie.getDomain().toLowerCase();
if (cookie.isDomainAttributeSpecified()) {
if (!cookieDomain.startsWith(".")) {
throw new MalformedCookieException(new StringBuffer().append("Domain attribute \"").append(cookie.getDomain()).append("\" violates RFC 2109: domain must start with a dot").toString());
}
int dotIndex = cookieDomain.indexOf(46, 1);
if ((dotIndex < 0 || dotIndex == cookieDomain.length() - 1) && !cookieDomain.equals(".local")) {
throw new MalformedCookieException(new StringBuffer().append("Domain attribute \"").append(cookie.getDomain()).append("\" violates RFC 2965: the value contains no embedded dots ").append("and the value is not .local").toString());
} else if (!this.a.domainMatch(host, cookieDomain)) {
throw new MalformedCookieException(new StringBuffer().append("Domain attribute \"").append(cookie.getDomain()).append("\" violates RFC 2965: effective host name does not ").append("domain-match domain attribute.").toString());
} else if (host.substring(0, host.length() - cookieDomain.length()).indexOf(46) != -1) {
throw new MalformedCookieException(new StringBuffer().append("Domain attribute \"").append(cookie.getDomain()).append("\" violates RFC 2965: ").append("effective host minus domain may not contain any dots").toString());
}
} else if (!cookie.getDomain().equals(host)) {
throw new MalformedCookieException(new StringBuffer().append("Illegal domain attribute: \"").append(cookie.getDomain()).append("\".").append("Domain of origin: \"").append(host).append(com.lenovo.lps.sus.c.c.M).toString());
}
}
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final boolean match(Cookie cookie, CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
} else if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
} else {
String host = origin.getHost().toLowerCase();
String cookieDomain = cookie.getDomain();
if (this.a.domainMatch(host, cookieDomain) && host.substring(0, host.length() - cookieDomain.length()).indexOf(46) == -1) {
return true;
}
return false;
}
}
}
private class d implements CookieAttributeHandler {
private final RFC2965Spec a;
private d(RFC2965Spec rFC2965Spec) {
this.a = rFC2965Spec;
}
d(RFC2965Spec x0, byte b) {
this(x0);
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void parse(Cookie cookie, String portValue) throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
} else if (cookie instanceof Cookie2) {
Cookie2 cookie2 = (Cookie2) cookie;
if (portValue == null || portValue.trim().equals("")) {
cookie2.setPortAttributeBlank(true);
} else {
RFC2965Spec rFC2965Spec = this.a;
cookie2.setPorts(RFC2965Spec.a(portValue));
}
cookie2.setPortAttributeSpecified(true);
}
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
} else if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
} else if (cookie instanceof Cookie2) {
Cookie2 cookie2 = (Cookie2) cookie;
int port = origin.getPort();
if (cookie2.isPortAttributeSpecified()) {
RFC2965Spec rFC2965Spec = this.a;
if (!RFC2965Spec.a(port, cookie2.getPorts())) {
throw new MalformedCookieException("Port attribute violates RFC 2965: Request port not found in cookie's port list.");
}
}
}
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final boolean match(Cookie cookie, CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
} else if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
} else if (!(cookie instanceof Cookie2)) {
return false;
} else {
Cookie2 cookie2 = (Cookie2) cookie;
int port = origin.getPort();
if (cookie2.isPortAttributeSpecified()) {
if (cookie2.getPorts() == null) {
CookieSpecBase.LOG.warn("Invalid cookie state: port not specified");
return false;
}
RFC2965Spec rFC2965Spec = this.a;
if (RFC2965Spec.a(port, cookie2.getPorts())) {
return true;
}
return false;
}
return true;
}
}
}
private class b implements CookieAttributeHandler {
private final RFC2965Spec a;
private b(RFC2965Spec rFC2965Spec) {
this.a = rFC2965Spec;
}
b(RFC2965Spec x0, byte b) {
this(x0);
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void parse(Cookie cookie, String value) throws MalformedCookieException {
int age;
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
} else if (value == null) {
throw new MalformedCookieException("Missing value for max-age attribute");
} else {
try {
age = Integer.parseInt(value);
} catch (NumberFormatException e) {
age = -1;
}
if (age < 0) {
throw new MalformedCookieException("Invalid max-age attribute.");
}
cookie.setExpiryDate(new Date(System.currentTimeMillis() + (((long) age) * 1000)));
}
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void validate(Cookie cookie, CookieOrigin origin) {
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final boolean match(Cookie cookie, CookieOrigin origin) {
return true;
}
}
private class i implements CookieAttributeHandler {
private final RFC2965Spec a;
private i(RFC2965Spec rFC2965Spec) {
this.a = rFC2965Spec;
}
i(RFC2965Spec x0, byte b) {
this(x0);
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void parse(Cookie cookie, String secure) throws MalformedCookieException {
cookie.setSecure(true);
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final boolean match(Cookie cookie, CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
} else if (origin != null) {
return cookie.getSecure() == origin.isSecure();
} else {
throw new IllegalArgumentException("Cookie origin may not be null");
}
}
}
private class f implements CookieAttributeHandler {
private final RFC2965Spec a;
private f(RFC2965Spec rFC2965Spec) {
this.a = rFC2965Spec;
}
f(RFC2965Spec x0, byte b) {
this(x0);
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void parse(Cookie cookie, String comment) throws MalformedCookieException {
cookie.setComment(comment);
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final boolean match(Cookie cookie, CookieOrigin origin) {
return true;
}
}
private class g implements CookieAttributeHandler {
private final RFC2965Spec a;
private g(RFC2965Spec rFC2965Spec) {
this.a = rFC2965Spec;
}
g(RFC2965Spec x0, byte b) {
this(x0);
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void parse(Cookie cookie, String commenturl) throws MalformedCookieException {
if (cookie instanceof Cookie2) {
((Cookie2) cookie).setCommentURL(commenturl);
}
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final boolean match(Cookie cookie, CookieOrigin origin) {
return true;
}
}
private class h implements CookieAttributeHandler {
private final RFC2965Spec a;
private h(RFC2965Spec rFC2965Spec) {
this.a = rFC2965Spec;
}
h(RFC2965Spec x0, byte b) {
this(x0);
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void parse(Cookie cookie, String commenturl) throws MalformedCookieException {
if (cookie instanceof Cookie2) {
((Cookie2) cookie).setDiscard(true);
}
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final boolean match(Cookie cookie, CookieOrigin origin) {
return true;
}
}
private class e implements CookieAttributeHandler {
private final RFC2965Spec a;
private e(RFC2965Spec rFC2965Spec) {
this.a = rFC2965Spec;
}
e(RFC2965Spec x0, byte b) {
this(x0);
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void parse(Cookie cookie, String value) throws MalformedCookieException {
int version;
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
} else if (cookie instanceof Cookie2) {
Cookie2 cookie2 = (Cookie2) cookie;
if (value == null) {
throw new MalformedCookieException("Missing value for version attribute");
}
try {
version = Integer.parseInt(value);
} catch (NumberFormatException e) {
version = -1;
}
if (version < 0) {
throw new MalformedCookieException("Invalid cookie version.");
}
cookie2.setVersion(version);
cookie2.setVersionAttributeSpecified(true);
}
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
} else if ((cookie instanceof Cookie2) && !((Cookie2) cookie).isVersionAttributeSpecified()) {
throw new MalformedCookieException("Violates RFC 2965. Version attribute is required.");
}
}
@Override // org.apache.commons.httpclient.cookie.CookieAttributeHandler
public final boolean match(Cookie cookie, CookieOrigin origin) {
return true;
}
}
@Override // org.apache.commons.httpclient.cookie.CookieVersionSupport
public int getVersion() {
return 1;
}
@Override // org.apache.commons.httpclient.cookie.CookieVersionSupport
public Header getVersionHeader() {
ParameterFormatter formatter = new ParameterFormatter();
StringBuffer buffer = new StringBuffer();
formatter.format(buffer, new NameValuePair("$Version", Integer.toString(getVersion())));
return new Header("Cookie2", buffer.toString(), true);
}
}
| 14,836 |
5,903 | <reponame>zhouguangping/pentaho-kettle<gh_stars>1000+
/*!
* Copyright 2010 - 2017 <NAME>. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.pentaho.di.ui.repository.repositoryexplorer.abs.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.repository.IUser;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.RepositorySecurityManager;
import org.pentaho.di.repository.pur.model.AbsRoleInfo;
import org.pentaho.di.repository.pur.model.EEUserInfo;
import org.pentaho.di.repository.pur.model.IRole;
import org.pentaho.di.ui.repository.pur.repositoryexplorer.IUIRole;
import org.pentaho.di.ui.repository.pur.repositoryexplorer.abs.IUIAbsRole;
import org.pentaho.di.ui.repository.pur.repositoryexplorer.abs.model.UIAbsRepositoryRole;
import org.pentaho.di.ui.repository.pur.repositoryexplorer.model.UIEESecurity;
import org.pentaho.di.ui.repository.pur.services.IAbsSecurityManager;
import org.pentaho.di.ui.repository.pur.services.IRoleSupportSecurityManager;
import org.pentaho.di.ui.repository.repositoryexplorer.model.IUIUser;
import org.pentaho.di.ui.repository.repositoryexplorer.model.UIRepositoryUser;
public class RepsitoryUserTestImpl implements RepositorySecurityManager, IRoleSupportSecurityManager,
IAbsSecurityManager, java.io.Serializable {
static final long serialVersionUID = -3031163963776739401L; /* EESOURCE: UPDATE SERIALVERUID */
private List<IUser> users;
private List<IRole> roles;
private List<IRole> systemRoles;
private UIEESecurity security;
public RepsitoryUserTestImpl() {
users = new ArrayList<IUser>();
roles = new ArrayList<IRole>();
systemRoles = new ArrayList<IRole>();
security = new UIEESecurity();
List<IUIRole> rroles;
List<IUIUser> rusers;
EEUserInfo joeUser;
EEUserInfo patUser;
EEUserInfo suzyUser;
EEUserInfo tiffanyUser;
IRole adminRole = new AbsRoleInfo( "Admin", "Super User" );
IRole anonymousRole = new AbsRoleInfo( "Anonymous", "User has not logged in" );
IRole authenticatedRole = new AbsRoleInfo( "Authenticated", "User has logged in" );
IRole ceoRole = new AbsRoleInfo( "ceo", "Chief Executive Officer" );
IRole ctoRole = new AbsRoleInfo( "cto", "Chief Technology Officer" );
IRole devRole = new AbsRoleInfo( "dev", "Developer" );
IRole devmgrRole = new AbsRoleInfo( "devmgr", "Development Manager" );
IRole isRole = new AbsRoleInfo( "is", "Information Services" );
roles.add( adminRole );
roles.add( ceoRole );
roles.add( ctoRole );
roles.add( devRole );
roles.add( devmgrRole );
roles.add( isRole );
systemRoles.add( anonymousRole );
systemRoles.add( authenticatedRole );
joeUser = new EEUserInfo( "joe", "password", "<PASSWORD>", "<PASSWORD>", true );
patUser = new EEUserInfo( "pat", "password", "<PASSWORD>", "<PASSWORD>", true );
suzyUser = new EEUserInfo( "suzy", "password", "<PASSWORD>", "<PASSWORD>", true );
tiffanyUser = new EEUserInfo( "tiffany", "password", "<PASSWORD>", "<PASSWORD>", true );
joeUser.addRole( roles.get( 0 ) );
joeUser.addRole( roles.get( 2 ) );
joeUser.addRole( roles.get( 3 ) );
suzyUser.addRole( roles.get( 2 ) );
suzyUser.addRole( roles.get( 4 ) );
suzyUser.addRole( roles.get( 1 ) );
patUser.addRole( roles.get( 2 ) );
patUser.addRole( roles.get( 4 ) );
tiffanyUser.addRole( roles.get( 1 ) );
tiffanyUser.addRole( roles.get( 2 ) );
tiffanyUser.addRole( roles.get( 4 ) );
adminRole.addUser( joeUser );
adminRole.addUser( patUser );
anonymousRole.addUser( tiffanyUser );
authenticatedRole.addUser( joeUser );
authenticatedRole.addUser( patUser );
authenticatedRole.addUser( suzyUser );
authenticatedRole.addUser( tiffanyUser );
ceoRole.addUser( joeUser );
ctoRole.addUser( patUser );
devmgrRole.addUser( joeUser );
devmgrRole.addUser( patUser );
isRole.addUser( joeUser );
isRole.addUser( suzyUser );
users.add( joeUser );
users.add( patUser );
users.add( suzyUser );
users.add( tiffanyUser );
rroles = new ArrayList<IUIRole>();
for ( IRole roleInfo : roles ) {
IUIAbsRole role = new UIAbsRepositoryRole( roleInfo );
rroles.add( role );
}
rusers = new ArrayList<IUIUser>();
for ( IUser eEUserInfo : users ) {
rusers.add( new UIRepositoryUser( eEUserInfo ) );
}
security.setUserList( rusers );
security.setRoleList( rroles );
}
public IRole constructRole() throws KettleException {
return new AbsRoleInfo();
}
public void createRole( IRole arg0 ) throws KettleException {
// TODO Auto-generated method stub
}
public void delUser( ObjectId arg0 ) throws KettleException {
// TODO Auto-generated method stub
}
public void delUser( String arg0 ) throws KettleException {
// TODO Auto-generated method stub
}
public void deleteRole( String arg0 ) throws KettleException {
// TODO Auto-generated method stub
}
public void deleteRoles( List<IRole> arg0 ) throws KettleException {
// TODO Auto-generated method stub
}
public void deleteUsers( List<IUser> arg0 ) throws KettleException {
// TODO Auto-generated method stub
}
public List<String> getAllRoles() throws KettleException {
// TODO Auto-generated method stub
return null;
}
public List<String> getAllUsers() throws KettleException {
// TODO Auto-generated method stub
return null;
}
public IRole getRole( String arg0 ) throws KettleException {
// TODO Auto-generated method stub
return null;
}
public List<IRole> getRoles() throws KettleException {
// TODO Auto-generated method stub
return roles;
}
public ObjectId getUserID( String arg0 ) throws KettleException {
// TODO Auto-generated method stub
return null;
}
public ObjectId[] getUserIDs() throws KettleException {
// TODO Auto-generated method stub
return null;
}
public IUser getUserInfo() {
// TODO Auto-generated method stub
return null;
}
public String[] getUserLogins() throws KettleException {
// TODO Auto-generated method stub
return null;
}
public List<IUser> getUsers() throws KettleException {
// TODO Auto-generated method stub
return users;
}
public IUser loadUserInfo( String arg0 ) throws KettleException {
// TODO Auto-generated method stub
return null;
}
public IUser loadUserInfo( String arg0, String arg1 ) throws KettleException {
// TODO Auto-generated method stub
return null;
}
public void renameUser( ObjectId arg0, String arg1 ) throws KettleException {
// TODO Auto-generated method stub
}
public void saveUserInfo( IUser arg0 ) throws KettleException {
// TODO Auto-generated method stub
}
public void setRoles( List<IRole> arg0 ) throws KettleException {
// TODO Auto-generated method stub
}
public void setUserInfo( IUser arg0 ) {
// TODO Auto-generated method stub
}
public void setUsers( List<IUser> arg0 ) throws KettleException {
// TODO Auto-generated method stub
}
public void updateRole( IRole arg0 ) throws KettleException {
// TODO Auto-generated method stub
}
public void updateUser( IUser arg0 ) throws KettleException {
// TODO Auto-generated method stub
}
public IUser constructUser() throws KettleException {
// TODO Auto-generated method stub
return new EEUserInfo();
}
public List<IRole> getDefaultRoles() throws KettleException {
// TODO Auto-generated method stub
return null;
}
public boolean isManaged() throws KettleException {
// TODO Auto-generated method stub
return false;
}
public Map<String, String> getAllLogicalRoles( String locale ) throws KettleException {
// TODO Auto-generated method stub
return null;
}
public List<String> getLogicalRoles( String runtimeRole ) throws KettleException {
for ( IRole role : roles ) {
if ( role.getName().equals( runtimeRole ) ) {
return ( (AbsRoleInfo) role ).getLogicalRoles();
}
}
for ( IRole role : systemRoles ) {
if ( role.getName().equals( runtimeRole ) ) {
return ( (AbsRoleInfo) role ).getLogicalRoles();
}
}
return null;
}
public void initialize( String locale ) throws KettleException {
// TODO Auto-generated method stub
}
public void setLogicalRoles( String rolename, List<String> logicalRoles ) throws KettleException {
boolean done = false;
for ( IRole role : roles ) {
if ( role.getName().equals( rolename ) ) {
( (AbsRoleInfo) role ).setLogicalRoles( logicalRoles );
done = true;
}
}
if ( !done ) {
for ( IRole role : systemRoles ) {
if ( role.getName().equals( rolename ) ) {
( (AbsRoleInfo) role ).setLogicalRoles( logicalRoles );
done = true;
}
}
}
}
}
| 3,339 |
348 | <filename>docs/data/leg-t2/059/05914499.json<gh_stars>100-1000
{"nom":"Rexpoëde","circ":"14ème circonscription","dpt":"Nord","inscrits":1470,"abs":818,"votants":652,"blancs":46,"nuls":22,"exp":584,"res":[{"nuance":"LR","nom":"<NAME>","voix":366},{"nuance":"REM","nom":"<NAME>","voix":218}]} | 119 |
372 | <filename>lwnetapi/test/test_lsa.c
/* Editor Settings: expandtabs and use 4 spaces for indentation
* ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: *
*/
/*
* Copyright © BeyondTrust Software 2004 - 2019
* 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.
*
* BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS
* WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH
* BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT
* SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE,
* NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST
* A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT
* BEYONDTRUST AT beyondtrust.com/contact
*/
#include "includes.h"
typedef struct _TEST_LOOKUP
{
PSTR pszDomainName;
PSTR pszName;
PSTR pszSid;
DWORD dwRid;
DWORD dwType;
} TEST_LOOKUP, *PTEST_LOOKUP;
static
DWORD
TestFormatNT4Name(
PWSTR *ppwszNT4Name,
PWSTR pwszDomain,
PWSTR pwszName
);
static
DWORD
TestGetLookupTestSet(
PTEST_LOOKUP *ppTestSet,
PDWORD pdwNumNames,
PCSTR pszTestSetName
);
static
DWORD
TestLsaLookupNames(
PTEST pTest,
PCWSTR pwszHostname,
PCWSTR pwszBindingString,
PCREDENTIALS pCreds,
PPARAMETER pOptions,
DWORD dwOptcount
);
static
DWORD
TestLsaLookupNames2(
PTEST pTest,
PCWSTR pwszHostname,
PCWSTR pwszBindingString,
PCREDENTIALS pCreds,
PPARAMETER pOptions,
DWORD dwOptcount
);
static
DWORD
TestLsaLookupNames3(
PTEST pTest,
PCWSTR pwszHostname,
PCWSTR pwszBindingString,
PCREDENTIALS pCreds,
PPARAMETER pOptions,
DWORD dwOptcount
);
static
DWORD
TestLsaLookupSids(
PTEST pTest,
PCWSTR pwszHostname,
PCWSTR pwszBindingString,
PCREDENTIALS pCreds,
PPARAMETER pOptions,
DWORD dwOptcount
);
static
DWORD
TestLsaQueryInfoPolicy(
PTEST pTest,
PCWSTR pwszHostname,
PCWSTR pwszBindingString,
PCREDENTIALS pCreds,
PPARAMETER pOptions,
DWORD dwOptcount
);
static
DWORD
TestLsaQueryInfoPolicy2(
PTEST pTest,
PCWSTR pwszHostname,
PCWSTR pwszBindingString,
PCREDENTIALS pCreds,
PPARAMETER pOptions,
DWORD dwOptcount
);
static
DWORD
TestLsaInfoPolicy(
PTEST pTest,
PCWSTR pwszHostname,
PCWSTR pwszBindingString,
PCREDENTIALS pCreds,
PPARAMETER pOptions,
DWORD dwOptcount
);
static
DWORD
TestLsaOpenPolicy(
PTEST pTest,
PCWSTR pwszHostname,
PCWSTR pwszBindingString,
PCREDENTIALS pCreds,
PPARAMETER pOptions,
DWORD dwOptcount
);
static
BOOLEAN
CallLsaOpenPolicy(
LSA_BINDING hBinding,
PWSTR pwszSysName,
DWORD dwAccessRights,
POLICY_HANDLE *phPolicy,
PWSTR *ppwszDomainName,
PWSTR *ppwszDnsDomainName,
PSID *ppDomainSid
);
static
BOOLEAN
CallLsaLookupNames(
LSA_BINDING hBinding,
POLICY_HANDLE hPolicy,
DWORD dwNumNames,
PWSTR *ppwszNames,
DWORD dwLevel,
PSID **pppSids,
PDWORD *ppdwTypes
);
static
BOOLEAN
CallLsaLookupNames2(
LSA_BINDING hBinding,
POLICY_HANDLE hPolicy,
DWORD dwNumNames,
PWSTR *ppwszNames,
DWORD dwLevel,
PSID **pppSids,
PDWORD *ppdwTypes
);
static
BOOLEAN
CallLsaLookupNames3(
LSA_BINDING hBinding,
POLICY_HANDLE hPolicy,
DWORD dwNumNames,
PWSTR *ppwszNames,
DWORD dwLevel,
PSID **pppSids,
PDWORD *ppdwTypes
);
static
BOOLEAN
CallLsaLookupSids(
LSA_BINDING hBinding,
POLICY_HANDLE hPolicy,
DWORD dwNumSids,
PSID *ppSids,
DWORD dwLevel,
PWSTR **pppwszNames,
PDWORD *ppdwTypes
);
static
BOOLEAN
CallLsaClosePolicy(
LSA_BINDING hBinding,
POLICY_HANDLE *phPolicy
);
static
TEST_LOOKUP StandaloneNames[] = {
{
.pszDomainName = NULL,
.pszName = "Administrator",
.pszSid = NULL,
.dwRid = DOMAIN_USER_RID_ADMIN,
.dwType = SID_TYPE_USER,
},
{
.pszDomainName = NULL,
.pszName = "Guest",
.pszSid = NULL,
.dwRid = DOMAIN_USER_RID_GUEST,
.dwType = SID_TYPE_USER,
},
{
.pszDomainName = NULL,
.pszName = "_NonExistent",
.pszSid = NULL,
.dwRid = 0,
.dwType = SID_TYPE_UNKNOWN,
},
{
.pszDomainName = "BUILTIN",
.pszName = "Administrators",
.pszSid = "S-1-5-32-544",
.dwRid = DOMAIN_ALIAS_RID_ADMINS,
.dwType = SID_TYPE_ALIAS,
},
{
.pszDomainName = "BUILTIN",
.pszName = "Users",
.pszSid = "S-1-5-32-545",
.dwRid = DOMAIN_ALIAS_RID_USERS,
.dwType = SID_TYPE_ALIAS,
},
};
static
TEST_LOOKUP DomainNames[] = {
{
.pszDomainName = NULL,
.pszName = "_NonExistent",
.pszSid = NULL,
.dwRid = 0,
.dwType = SID_TYPE_UNKNOWN,
},
{
.pszDomainName = NULL,
.pszName = "Administrator",
.pszSid = NULL,
.dwRid = DOMAIN_USER_RID_ADMIN,
.dwType = SID_TYPE_USER,
},
{
.pszDomainName = NULL,
.pszName = "Guest",
.pszSid = NULL,
.dwRid = DOMAIN_USER_RID_GUEST,
.dwType = SID_TYPE_USER,
},
{
.pszDomainName = NULL,
.pszName = "Domain Admins",
.pszSid = NULL,
.dwRid = DOMAIN_GROUP_RID_ADMINS,
.dwType = SID_TYPE_DOM_GRP,
},
{
.pszDomainName = "BUILTIN",
.pszName = "Users",
.pszSid = "S-1-5-32-545",
.dwRid = DOMAIN_ALIAS_RID_USERS,
.dwType = SID_TYPE_ALIAS,
},
{
.pszDomainName = NULL,
.pszName = "Domain Users",
.pszSid = NULL,
.dwRid = DOMAIN_GROUP_RID_USERS,
.dwType = SID_TYPE_DOM_GRP,
},
{
.pszDomainName = "BUILTIN",
.pszName = "Guests",
.pszSid = "S-1-5-32-546",
.dwRid = DOMAIN_ALIAS_RID_GUESTS,
.dwType = SID_TYPE_ALIAS,
},
};
static
TEST_LOOKUP DuplicateNames[] = {
{
.pszDomainName = NULL,
.pszName = "Administrator",
.pszSid = NULL,
.dwRid = DOMAIN_USER_RID_ADMIN,
.dwType = SID_TYPE_USER,
},
{
.pszDomainName = NULL,
.pszName = "Administrator",
.pszSid = NULL,
.dwRid = DOMAIN_USER_RID_ADMIN,
.dwType = SID_TYPE_USER,
},
{
.pszDomainName = NULL,
.pszName = "Domain Users",
.pszSid = NULL,
.dwRid = DOMAIN_GROUP_RID_ADMINS,
.dwType = SID_TYPE_DOM_GRP,
},
{
.pszDomainName = NULL,
.pszName = "Administrator",
.pszSid = NULL,
.dwRid = DOMAIN_USER_RID_ADMIN,
.dwType = SID_TYPE_USER,
},
{
.pszDomainName = NULL,
.pszName = "Domain Users",
.pszSid = NULL,
.dwRid = DOMAIN_GROUP_RID_ADMINS,
.dwType = SID_TYPE_DOM_GRP,
},
{
.pszDomainName = NULL,
.pszName = "Domain Users",
.pszSid = NULL,
.dwRid = DOMAIN_GROUP_RID_ADMINS,
.dwType = SID_TYPE_DOM_GRP,
},
{
.pszDomainName = "BUILTIN",
.pszName = "_NotExisting",
.pszSid = NULL,
.dwRid = 0,
.dwType = SID_TYPE_UNKNOWN,
},
{
.pszDomainName = "BUILTIN",
.pszName = "_NotExisting",
.pszSid = NULL,
.dwRid = 0,
.dwType = SID_TYPE_UNKNOWN,
},
};
static
DWORD
TestLsaOpenPolicy(
PTEST pTest,
PCWSTR pwszHostname,
PCWSTR pwszBindingString,
PCREDENTIALS pCreds,
PPARAMETER pOptions,
DWORD dwOptcount
)
{
const DWORD dwAccessRights = LSA_ACCESS_LOOKUP_NAMES_SIDS;
BOOLEAN bRet = TRUE;
NTSTATUS ntStatus = STATUS_SUCCESS;
LSA_BINDING hLsa = NULL;
POLICY_HANDLE hPolicy = NULL;
TESTINFO(pTest, pwszHostname);
bRet &= CreateRpcBinding(OUT_PPVOID(&hLsa),
RPC_LSA_BINDING,
pwszHostname,
pwszBindingString,
pCreds);
INPUT_ARG_PTR(hLsa);
INPUT_ARG_WSTR(pwszHostname);
INPUT_ARG_UINT(dwAccessRights);
CALL_MSRPC(ntStatus, LsaOpenPolicy2(hLsa, pwszHostname, NULL,
dwAccessRights, &hPolicy));
BAIL_ON_NT_STATUS(ntStatus);
OUTPUT_ARG_PTR(hLsa);
OUTPUT_ARG_PTR(hPolicy);
ntStatus = LsaClose(hLsa, hPolicy);
BAIL_ON_NT_STATUS(ntStatus);
LsaFreeBinding(&hLsa);
error:
return bRet;
}
static
DWORD
TestFormatNT4Name(
PWSTR *ppwszNT4Name,
PWSTR pwszDomain,
PWSTR pwszName
)
{
DWORD dwError = ERROR_SUCCESS;
size_t sDomainLen = 0;
size_t sNameLen = 0;
DWORD dwNT4NameSize = 0;
PWSTR pwszNT4Name = NULL;
dwError = LwWc16sLen(pwszDomain, &sDomainLen);
BAIL_ON_WIN_ERROR(dwError);
dwError = LwWc16sLen(pwszName, &sNameLen);
BAIL_ON_WIN_ERROR(dwError);
dwNT4NameSize = sizeof(WCHAR) * (sDomainLen + 1 + sNameLen);
dwError = LwAllocateMemory(dwNT4NameSize + sizeof(WCHAR),
OUT_PPVOID(&pwszNT4Name));
BAIL_ON_WIN_ERROR(dwError);
if (sDomainLen > 0 && sNameLen > 0)
{
if (sw16printfw(pwszNT4Name, dwNT4NameSize, L"%ws\\%ws",
pwszDomain, pwszName) < 0)
{
dwError = LwErrnoToWin32Error(errno);
}
}
else if (sDomainLen == 0 && sNameLen > 0)
{
if (sw16printfw(pwszNT4Name, dwNT4NameSize, L"%ws",
pwszName) < 0)
{
dwError = LwErrnoToWin32Error(errno);
}
}
else if (sDomainLen > 0 && sNameLen == 0)
{
if (sw16printfw(pwszNT4Name, dwNT4NameSize, L"%ws",
pwszDomain) < 0)
{
dwError = LwErrnoToWin32Error(errno);
}
}
else
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_WIN_ERROR(dwError);
}
*ppwszNT4Name = pwszNT4Name;
cleanup:
return dwError;
error:
LW_SAFE_FREE_MEMORY(pwszNT4Name);
*ppwszNT4Name = NULL;
goto cleanup;
}
static
DWORD
TestGetLookupTestSet(
PTEST_LOOKUP *ppTestSet,
PDWORD pdwNumNames,
PCSTR pszTestSetName
)
{
DWORD dwError = ERROR_SUCCESS;
PTEST_LOOKUP pTestSet = NULL;
DWORD dwNumNames = 0;
if (strcmp(pszTestSetName, "standalone") == 0 ||
strcmp(pszTestSetName, "STANDALONE") == 0)
{
pTestSet = StandaloneNames;
dwNumNames = (sizeof(StandaloneNames)
/sizeof(StandaloneNames[0]));
}
else if (strcmp(pszTestSetName, "domain") == 0 ||
strcmp(pszTestSetName, "DOMAIN") == 0)
{
pTestSet = DomainNames;
dwNumNames = (sizeof(DomainNames)
/sizeof(DomainNames[0]));
}
else if (strcmp(pszTestSetName, "duplicate") == 0 ||
strcmp(pszTestSetName, "DUPLICATE") == 0)
{
pTestSet = DuplicateNames;
dwNumNames = (sizeof(DuplicateNames)
/sizeof(DuplicateNames[0]));
}
else
{
dwError = ERROR_INVALID_PARAMETER;
}
BAIL_ON_WIN_ERROR(dwError);
*ppTestSet = pTestSet;
*pdwNumNames = dwNumNames;
error:
return dwError;
}
static
DWORD
TestLsaLookupNames(
PTEST pTest,
PCWSTR pwszHostname,
PCWSTR pwszBindingString,
PCREDENTIALS pCreds,
PPARAMETER pOptions,
DWORD dwOptcount
)
{
PCSTR pszDefSysName = "\\\\";
const DWORD dwDefLevel = -1;
const BOOLEAN bDefRevLookup = TRUE;
PCSTR pszDefTestSetName = "standalone";
BOOLEAN bRet = TRUE;
DWORD dwError = ERROR_SUCCESS;
NTSTATUS ntStatus = STATUS_SUCCESS;
enum param_err perr = perr_success;
PSTR pszTestSetName = NULL;
LSA_BINDING hLsa = NULL;
PWSTR pwszSysName = NULL;
BOOLEAN bRevLookup = TRUE;
POLICY_HANDLE hPolicy = NULL;
PWSTR pwszDomainName = NULL;
DWORD dwSelectedLevels[] = {0};
DWORD dwAvailableLevels[] = {LSA_LOOKUP_NAMES_ALL,
LSA_LOOKUP_NAMES_DOMAINS_ONLY,
LSA_LOOKUP_NAMES_PRIMARY_DOMAIN_ONLY,
LSA_LOOKUP_NAMES_UPLEVEL_TRUSTS_ONLY,
LSA_LOOKUP_NAMES_FOREST_TRUSTS,
LSA_LOOKUP_NAMES_UPLEVEL_TRUSTS_ONLY2};
PDWORD pdwLevels = NULL;
DWORD dwNumLevels = 0;
DWORD dwLevel = 0;
DWORD iLevel = 0;
DWORD dwNumNames = 0;
DWORD iName = 0;
PWSTR *ppwszNames = NULL;
PWSTR pwszNT4Name = NULL;
PSID *ppSids = NULL;
PDWORD pdwTypes = NULL;
PWSTR *ppwszRetNames = NULL;
PTEST_LOOKUP pTestNames = NULL;
perr = fetch_value(pOptions, dwOptcount, "systemname", pt_w16string,
&pwszSysName, &pszDefSysName);
if (!perr_is_ok(perr)) perr_fail(perr);
perr = fetch_value(pOptions, dwOptcount, "testset", pt_string,
(UINT32*)&pszTestSetName, (UINT32*)&pszDefTestSetName);
if (!perr_is_ok(perr)) perr_fail(perr);
perr = fetch_value(pOptions, dwOptcount, "level", pt_uint32,
(UINT32*)&dwLevel, (UINT32*)&dwDefLevel);
if (!perr_is_ok(perr)) perr_fail(perr);
perr = fetch_value(pOptions, dwOptcount, "revlookup", pt_uint32,
(UINT32*)&bRevLookup, (UINT32*)&bDefRevLookup);
if (!perr_is_ok(perr)) perr_fail(perr);
dwError = TestGetLookupTestSet(&pTestNames, &dwNumNames, pszTestSetName);
BAIL_ON_WIN_ERROR(dwError);
TESTINFO(pTest, pwszHostname);
PARAM_INFO("systemname", pt_w16string, &pwszSysName);
PARAM_INFO("level", pt_uint32, &dwLevel);
if (dwLevel == (DWORD)(-1))
{
pdwLevels = dwAvailableLevels;
dwNumLevels = sizeof(dwAvailableLevels)/sizeof(dwAvailableLevels[0]);
}
else
{
dwSelectedLevels[0] = dwLevel;
pdwLevels = dwSelectedLevels;
dwNumLevels = sizeof(dwSelectedLevels)/sizeof(dwSelectedLevels[0]);
}
bRet &= CreateRpcBinding(OUT_PPVOID(&hLsa),
RPC_LSA_BINDING,
pwszHostname,
pwszBindingString,
pCreds);
bRet &= CallLsaOpenPolicy(hLsa, NULL, 0, &hPolicy,
&pwszDomainName, NULL, NULL);
for (iLevel = 0; iLevel < dwNumLevels; iLevel++)
{
dwLevel = pdwLevels[iLevel];
dwError = LwAllocateMemory(sizeof(PWSTR) * dwNumNames,
OUT_PPVOID(&ppwszNames));
BAIL_ON_WIN_ERROR(dwError);
for (iName = 0; iName < dwNumNames; iName++)
{
PWSTR pwszDomain = NULL;
PWSTR pwszName = NULL;
if (pTestNames[iName].pszDomainName)
{
dwError = LwMbsToWc16s(pTestNames[iName].pszDomainName,
&pwszDomain);
}
else
{
dwError = LwAllocateWc16String(&pwszDomain,
pwszDomainName);
}
BAIL_ON_WIN_ERROR(dwError);
dwError = LwMbsToWc16s(pTestNames[iName].pszName,
&pwszName);
BAIL_ON_WIN_ERROR(dwError);
dwError = TestFormatNT4Name(&pwszNT4Name, pwszDomain, pwszName);
BAIL_ON_WIN_ERROR(dwError);
ppwszNames[iName] = pwszNT4Name;
LW_SAFE_FREE_MEMORY(pwszDomain);
LW_SAFE_FREE_MEMORY(pwszName);
pwszDomain = NULL;
pwszName = NULL;
}
bRet &= CallLsaLookupNames(hLsa, hPolicy, dwNumNames, ppwszNames, dwLevel,
&ppSids, &pdwTypes);
for (iName = 0; iName < dwNumNames; iName++)
{
PSID pSid = NULL;
DWORD dwReturnedRid = 0;
DWORD dwReturnedType = pdwTypes[iName];
if (dwReturnedType == SID_TYPE_USE_NONE ||
dwReturnedType == SID_TYPE_INVALID ||
dwReturnedType == SID_TYPE_UNKNOWN)
{
continue;
}
if (pTestNames[iName].pszSid)
{
ntStatus = RtlAllocateSidFromCString(
&pSid,
pTestNames[iName].pszSid);
BAIL_ON_NT_STATUS(ntStatus);
ASSERT_TEST_MSG((ppSids[iName] != NULL), ("(i = %u)\n", iName));
ASSERT_SID_EQUAL_MSG(pSid, ppSids[iName], ("(i = %u)\n", iName));
if (ppSids[iName])
{
dwReturnedRid =
ppSids[iName]->SubAuthority[ppSids[iName]->SubAuthorityCount - 1];
ASSERT_TEST_MSG(dwReturnedRid == pTestNames[iName].dwRid,
("(i = %u)\n", iName));
}
}
ASSERT_TEST_MSG(dwReturnedType == pTestNames[iName].dwType,
("(i = %u)\n", iName));
RTL_FREE(&pSid);
}
LW_SAFE_FREE_MEMORY(pdwTypes);
pdwTypes = NULL;
if (bRevLookup)
{
bRet &= CallLsaLookupSids(hLsa, hPolicy, dwNumNames, ppSids, dwLevel,
&ppwszRetNames, &pdwTypes);
}
for (iName = 0; iName < dwNumNames; iName++)
{
LW_SAFE_FREE_MEMORY(ppwszNames[iName]);
RTL_FREE(&ppSids[iName]);
}
LW_SAFE_FREE_MEMORY(ppwszNames);
LW_SAFE_FREE_MEMORY(ppSids);
LW_SAFE_FREE_MEMORY(pdwTypes);
ppwszNames = NULL;
ppSids = NULL;
pdwTypes = NULL;
}
bRet &= CallLsaClosePolicy(hLsa, &hPolicy);
error:
if (ntStatus != STATUS_SUCCESS ||
dwError != ERROR_SUCCESS)
{
bRet = FALSE;
}
return bRet;
}
DWORD
TestLsaLookupNames2(
PTEST pTest,
PCWSTR pwszHostname,
PCWSTR pwszBindingString,
PCREDENTIALS pCreds,
PPARAMETER pOptions,
DWORD dwOptcount
)
{
PCSTR pszDefSysName = "\\\\";
const DWORD dwDefLevel = -1;
const BOOLEAN bDefRevLookup = TRUE;
PCSTR pszDefTestSetName = "standalone";
BOOLEAN bRet = TRUE;
DWORD dwError = ERROR_SUCCESS;
NTSTATUS ntStatus = STATUS_SUCCESS;
enum param_err perr = perr_success;
PSTR pszTestSetName = NULL;
LSA_BINDING hLsa = NULL;
PWSTR pwszSysName = NULL;
BOOLEAN bRevLookup = TRUE;
POLICY_HANDLE hPolicy = NULL;
PWSTR pwszDomainName = NULL;
DWORD dwSelectedLevels[] = {0};
DWORD dwAvailableLevels[] = {LSA_LOOKUP_NAMES_ALL,
LSA_LOOKUP_NAMES_DOMAINS_ONLY,
LSA_LOOKUP_NAMES_PRIMARY_DOMAIN_ONLY,
LSA_LOOKUP_NAMES_UPLEVEL_TRUSTS_ONLY,
LSA_LOOKUP_NAMES_FOREST_TRUSTS,
LSA_LOOKUP_NAMES_UPLEVEL_TRUSTS_ONLY2};
PDWORD pdwLevels = NULL;
DWORD dwNumLevels = 0;
DWORD dwLevel = 0;
DWORD iLevel = 0;
DWORD dwNumNames = 0;
DWORD iName = 0;
PWSTR *ppwszNames = NULL;
PWSTR pwszNT4Name = NULL;
PSID *ppSids = NULL;
PDWORD pdwTypes = NULL;
PWSTR *ppwszRetNames = NULL;
PTEST_LOOKUP pTestNames = NULL;
perr = fetch_value(pOptions, dwOptcount, "systemname", pt_w16string,
&pwszSysName, &pszDefSysName);
if (!perr_is_ok(perr)) perr_fail(perr);
perr = fetch_value(pOptions, dwOptcount, "testset", pt_string,
(UINT32*)&pszTestSetName, (UINT32*)&pszDefTestSetName);
if (!perr_is_ok(perr)) perr_fail(perr);
perr = fetch_value(pOptions, dwOptcount, "level", pt_uint32,
(UINT32*)&dwLevel, (UINT32*)&dwDefLevel);
if (!perr_is_ok(perr)) perr_fail(perr);
perr = fetch_value(pOptions, dwOptcount, "revlookup", pt_uint32,
(UINT32*)&bRevLookup, (UINT32*)&bDefRevLookup);
if (!perr_is_ok(perr)) perr_fail(perr);
dwError = TestGetLookupTestSet(&pTestNames, &dwNumNames, pszTestSetName);
BAIL_ON_WIN_ERROR(dwError);
TESTINFO(pTest, pwszHostname);
PARAM_INFO("systemname", pt_w16string, &pwszSysName);
PARAM_INFO("level", pt_uint32, &dwLevel);
if (dwLevel == (DWORD)(-1))
{
pdwLevels = dwAvailableLevels;
dwNumLevels = sizeof(dwAvailableLevels)/sizeof(dwAvailableLevels[0]);
}
else
{
dwSelectedLevels[0] = dwLevel;
pdwLevels = dwSelectedLevels;
dwNumLevels = sizeof(dwSelectedLevels)/sizeof(dwSelectedLevels[0]);
}
bRet &= CreateRpcBinding(OUT_PPVOID(&hLsa),
RPC_LSA_BINDING,
pwszHostname,
pwszBindingString,
pCreds);
bRet &= CallLsaOpenPolicy(hLsa, NULL, 0, &hPolicy,
&pwszDomainName, NULL, NULL);
for (iLevel = 0; iLevel < dwNumLevels; iLevel++)
{
dwLevel = pdwLevels[iLevel];
dwError = LwAllocateMemory(sizeof(PWSTR) * dwNumNames,
OUT_PPVOID(&ppwszNames));
BAIL_ON_WIN_ERROR(dwError);
for (iName = 0; iName < dwNumNames; iName++)
{
PWSTR pwszDomain = NULL;
PWSTR pwszName = NULL;
if (pTestNames[iName].pszDomainName)
{
dwError = LwMbsToWc16s(pTestNames[iName].pszDomainName,
&pwszDomain);
}
else
{
dwError = LwAllocateWc16String(&pwszDomain,
pwszDomainName);
}
BAIL_ON_WIN_ERROR(dwError);
dwError = LwMbsToWc16s(pTestNames[iName].pszName,
&pwszName);
BAIL_ON_WIN_ERROR(dwError);
dwError = TestFormatNT4Name(&pwszNT4Name, pwszDomain, pwszName);
BAIL_ON_WIN_ERROR(dwError);
ppwszNames[iName] = pwszNT4Name;
LW_SAFE_FREE_MEMORY(pwszDomain);
LW_SAFE_FREE_MEMORY(pwszName);
pwszDomain = NULL;
pwszName = NULL;
}
bRet &= CallLsaLookupNames2(hLsa, hPolicy, dwNumNames, ppwszNames, dwLevel,
&ppSids, &pdwTypes);
for (iName = 0; iName < dwNumNames; iName++)
{
PSID pSid = NULL;
DWORD dwReturnedRid = 0;
DWORD dwReturnedType = pdwTypes[iName];
if (dwReturnedType == SID_TYPE_USE_NONE ||
dwReturnedType == SID_TYPE_INVALID ||
dwReturnedType == SID_TYPE_UNKNOWN)
{
continue;
}
if (pTestNames[iName].pszSid)
{
ntStatus = RtlAllocateSidFromCString(
&pSid,
pTestNames[iName].pszSid);
BAIL_ON_NT_STATUS(ntStatus);
ASSERT_TEST_MSG((ppSids[iName] != NULL), ("(i = %u)\n", iName));
ASSERT_SID_EQUAL_MSG(pSid, ppSids[iName], ("(i = %u)\n", iName));
if (ppSids[iName])
{
dwReturnedRid =
ppSids[iName]->SubAuthority[ppSids[iName]->SubAuthorityCount - 1];
ASSERT_TEST_MSG(dwReturnedRid == pTestNames[iName].dwRid,
("(i = %u)\n", iName));
}
}
ASSERT_TEST_MSG(dwReturnedType == pTestNames[iName].dwType,
("(i = %u)\n", iName));
RTL_FREE(&pSid);
}
LW_SAFE_FREE_MEMORY(pdwTypes);
pdwTypes = NULL;
if (bRevLookup)
{
bRet &= CallLsaLookupSids(hLsa, hPolicy, dwNumNames, ppSids, dwLevel,
&ppwszRetNames, &pdwTypes);
}
for (iName = 0; iName < dwNumNames; iName++)
{
LW_SAFE_FREE_MEMORY(ppwszNames[iName]);
RTL_FREE(&ppSids[iName]);
}
LW_SAFE_FREE_MEMORY(ppwszNames);
LW_SAFE_FREE_MEMORY(ppSids);
LW_SAFE_FREE_MEMORY(pdwTypes);
ppwszNames = NULL;
ppSids = NULL;
pdwTypes = NULL;
}
bRet &= CallLsaClosePolicy(hLsa, &hPolicy);
error:
if (ntStatus != STATUS_SUCCESS ||
dwError != ERROR_SUCCESS)
{
bRet = FALSE;
}
return bRet;
}
DWORD
TestLsaLookupNames3(
PTEST pTest,
PCWSTR pwszHostname,
PCWSTR pwszBindingString,
PCREDENTIALS pCreds,
PPARAMETER pOptions,
DWORD dwOptcount
)
{
PCSTR pszDefSysName = "\\\\";
const DWORD dwDefLevel = -1;
const BOOLEAN bDefRevLookup = TRUE;
PCSTR pszDefTestSetName = "standalone";
BOOLEAN bRet = TRUE;
DWORD dwError = ERROR_SUCCESS;
NTSTATUS ntStatus = STATUS_SUCCESS;
enum param_err perr = perr_success;
PSTR pszTestSetName = NULL;
LSA_BINDING hLsa = NULL;
PWSTR pwszSysName = NULL;
BOOLEAN bRevLookup = TRUE;
POLICY_HANDLE hPolicy = NULL;
PWSTR pwszDomainName = NULL;
DWORD dwSelectedLevels[] = {0};
DWORD dwAvailableLevels[] = {LSA_LOOKUP_NAMES_ALL,
LSA_LOOKUP_NAMES_DOMAINS_ONLY,
LSA_LOOKUP_NAMES_PRIMARY_DOMAIN_ONLY,
LSA_LOOKUP_NAMES_UPLEVEL_TRUSTS_ONLY,
LSA_LOOKUP_NAMES_FOREST_TRUSTS,
LSA_LOOKUP_NAMES_UPLEVEL_TRUSTS_ONLY2};
PDWORD pdwLevels = NULL;
DWORD dwNumLevels = 0;
DWORD dwLevel = 0;
DWORD iLevel = 0;
DWORD dwNumNames = 0;
DWORD iName = 0;
PWSTR *ppwszNames = NULL;
PWSTR pwszNT4Name = NULL;
PSID *ppSids = NULL;
PDWORD pdwTypes = NULL;
PWSTR *ppwszRetNames = NULL;
PTEST_LOOKUP pTestNames = NULL;
perr = fetch_value(pOptions, dwOptcount, "systemname", pt_w16string,
&pwszSysName, &pszDefSysName);
if (!perr_is_ok(perr)) perr_fail(perr);
perr = fetch_value(pOptions, dwOptcount, "testset", pt_string,
(UINT32*)&pszTestSetName, (UINT32*)&pszDefTestSetName);
if (!perr_is_ok(perr)) perr_fail(perr);
perr = fetch_value(pOptions, dwOptcount, "level", pt_uint32,
(UINT32*)&dwLevel, (UINT32*)&dwDefLevel);
if (!perr_is_ok(perr)) perr_fail(perr);
perr = fetch_value(pOptions, dwOptcount, "revlookup", pt_uint32,
(UINT32*)&bRevLookup, (UINT32*)&bDefRevLookup);
if (!perr_is_ok(perr)) perr_fail(perr);
dwError = TestGetLookupTestSet(&pTestNames, &dwNumNames, pszTestSetName);
BAIL_ON_WIN_ERROR(dwError);
TESTINFO(pTest, pwszHostname);
PARAM_INFO("systemname", pt_w16string, &pwszSysName);
PARAM_INFO("level", pt_uint32, &dwLevel);
if (dwLevel == (DWORD)(-1))
{
pdwLevels = dwAvailableLevels;
dwNumLevels = sizeof(dwAvailableLevels)/sizeof(dwAvailableLevels[0]);
}
else
{
dwSelectedLevels[0] = dwLevel;
pdwLevels = dwSelectedLevels;
dwNumLevels = sizeof(dwSelectedLevels)/sizeof(dwSelectedLevels[0]);
}
bRet &= CreateRpcBinding(OUT_PPVOID(&hLsa),
RPC_LSA_BINDING,
pwszHostname,
pwszBindingString,
pCreds);
bRet &= CallLsaOpenPolicy(hLsa, NULL, 0, &hPolicy,
&pwszDomainName, NULL, NULL);
for (iLevel = 0; iLevel < dwNumLevels; iLevel++)
{
dwLevel = pdwLevels[iLevel];
dwError = LwAllocateMemory(sizeof(PWSTR) * dwNumNames,
OUT_PPVOID(&ppwszNames));
BAIL_ON_WIN_ERROR(dwError);
for (iName = 0; iName < dwNumNames; iName++)
{
PWSTR pwszDomain = NULL;
PWSTR pwszName = NULL;
if (pTestNames[iName].pszDomainName)
{
dwError = LwMbsToWc16s(pTestNames[iName].pszDomainName,
&pwszDomain);
}
else
{
dwError = LwAllocateWc16String(&pwszDomain,
pwszDomainName);
}
BAIL_ON_WIN_ERROR(dwError);
dwError = LwMbsToWc16s(pTestNames[iName].pszName,
&pwszName);
BAIL_ON_WIN_ERROR(dwError);
dwError = TestFormatNT4Name(&pwszNT4Name, pwszDomain, pwszName);
BAIL_ON_WIN_ERROR(dwError);
ppwszNames[iName] = pwszNT4Name;
LW_SAFE_FREE_MEMORY(pwszDomain);
LW_SAFE_FREE_MEMORY(pwszName);
pwszDomain = NULL;
pwszName = NULL;
}
bRet &= CallLsaLookupNames3(hLsa, hPolicy, dwNumNames, ppwszNames, dwLevel,
&ppSids, &pdwTypes);
for (iName = 0; iName < dwNumNames; iName++)
{
PSID pSid = NULL;
DWORD dwReturnedRid = 0;
DWORD dwReturnedType = pdwTypes[iName];
if (dwReturnedType == SID_TYPE_USE_NONE ||
dwReturnedType == SID_TYPE_INVALID ||
dwReturnedType == SID_TYPE_UNKNOWN)
{
continue;
}
if (pTestNames[iName].pszSid)
{
ntStatus = RtlAllocateSidFromCString(
&pSid,
pTestNames[iName].pszSid);
BAIL_ON_NT_STATUS(ntStatus);
ASSERT_TEST_MSG((ppSids[iName] != NULL), ("(i = %u)\n", iName));
ASSERT_SID_EQUAL_MSG(pSid, ppSids[iName], ("(i = %u)\n", iName));
if (ppSids[iName])
{
dwReturnedRid =
ppSids[iName]->SubAuthority[ppSids[iName]->SubAuthorityCount - 1];
ASSERT_TEST_MSG(dwReturnedRid == pTestNames[iName].dwRid,
("(i = %u)\n", iName));
}
}
ASSERT_TEST_MSG(dwReturnedType == pTestNames[iName].dwType,
("(i = %u)\n", iName));
RTL_FREE(&pSid);
}
LW_SAFE_FREE_MEMORY(pdwTypes);
pdwTypes = NULL;
if (bRevLookup)
{
bRet &= CallLsaLookupSids(hLsa, hPolicy, dwNumNames, ppSids, dwLevel,
&ppwszRetNames, &pdwTypes);
}
for (iName = 0; iName < dwNumNames; iName++)
{
LW_SAFE_FREE_MEMORY(ppwszNames[iName]);
RTL_FREE(&ppSids[iName]);
}
LW_SAFE_FREE_MEMORY(ppwszNames);
LW_SAFE_FREE_MEMORY(ppSids);
LW_SAFE_FREE_MEMORY(pdwTypes);
ppwszNames = NULL;
ppSids = NULL;
pdwTypes = NULL;
}
bRet &= CallLsaClosePolicy(hLsa, &hPolicy);
error:
if (ntStatus != STATUS_SUCCESS ||
dwError != ERROR_SUCCESS)
{
bRet = FALSE;
}
return bRet;
}
static
DWORD
TestLsaLookupSids(
PTEST pTest,
PCWSTR pwszHostname,
PCWSTR pwszBindingString,
PCREDENTIALS pCreds,
PPARAMETER pOptions,
DWORD dwOptcount
)
{
PCSTR pszDefSysName = "\\\\";
const DWORD dwDefLevel = -1;
const BOOLEAN bDefRevLookup = TRUE;
PCSTR pszDefTestSetName = "standalone";
BOOLEAN bRet = TRUE;
DWORD dwError = ERROR_SUCCESS;
NTSTATUS ntStatus = STATUS_SUCCESS;
enum param_err perr = perr_success;
PSTR pszTestSetName = NULL;
LSA_BINDING hLsa = NULL;
PWSTR pwszSysName = NULL;
BOOLEAN bRevLookup = TRUE;
POLICY_HANDLE hPolicy = NULL;
PWSTR pwszDomainName = NULL;
PSID pDomainSid = NULL;
DWORD dwSelectedLevels[] = {0};
DWORD dwAvailableLevels[] = {LSA_LOOKUP_NAMES_ALL,
LSA_LOOKUP_NAMES_DOMAINS_ONLY,
LSA_LOOKUP_NAMES_PRIMARY_DOMAIN_ONLY,
LSA_LOOKUP_NAMES_UPLEVEL_TRUSTS_ONLY,
LSA_LOOKUP_NAMES_FOREST_TRUSTS,
LSA_LOOKUP_NAMES_UPLEVEL_TRUSTS_ONLY2};
PDWORD pdwLevels = NULL;
DWORD dwNumLevels = 0;
DWORD dwLevel = 0;
DWORD iLevel = 0;
DWORD dwNumSids = 0;
DWORD iSid = 0;
PSID *ppSids = NULL;
PWSTR *ppwszNames = NULL;
PDWORD pdwTypes = NULL;
PTEST_LOOKUP pTestSids = NULL;
PWSTR pwszNT4Name = NULL;
perr = fetch_value(pOptions, dwOptcount, "systemname", pt_w16string,
&pwszSysName, &pszDefSysName);
if (!perr_is_ok(perr)) perr_fail(perr);
perr = fetch_value(pOptions, dwOptcount, "testset", pt_string,
(UINT32*)&pszTestSetName, (UINT32*)&pszDefTestSetName);
if (!perr_is_ok(perr)) perr_fail(perr);
perr = fetch_value(pOptions, dwOptcount, "level", pt_uint32,
(UINT32*)&dwLevel, (UINT32*)&dwDefLevel);
if (!perr_is_ok(perr)) perr_fail(perr);
perr = fetch_value(pOptions, dwOptcount, "revlookup", pt_uint32,
(UINT32*)&bRevLookup, (UINT32*)&bDefRevLookup);
if (!perr_is_ok(perr)) perr_fail(perr);
dwError = TestGetLookupTestSet(&pTestSids, &dwNumSids, pszTestSetName);
BAIL_ON_WIN_ERROR(dwError);
TESTINFO(pTest, pwszHostname);
PARAM_INFO("systemname", pt_w16string, &pwszSysName);
PARAM_INFO("level", pt_uint32, &dwLevel);
if (dwLevel == (DWORD)(-1))
{
pdwLevels = dwAvailableLevels;
dwNumLevels = sizeof(dwAvailableLevels)/sizeof(dwAvailableLevels[0]);
}
else
{
dwSelectedLevels[0] = dwLevel;
pdwLevels = dwSelectedLevels;
dwNumLevels = sizeof(dwSelectedLevels)/sizeof(dwSelectedLevels[0]);
}
bRet &= CreateRpcBinding(OUT_PPVOID(&hLsa),
RPC_LSA_BINDING,
pwszHostname,
pwszBindingString,
pCreds);
bRet &= CallLsaOpenPolicy(hLsa, NULL, 0, &hPolicy,
&pwszDomainName, NULL, &pDomainSid);
for (iLevel = 0; iLevel < dwNumLevels; iLevel++)
{
dwLevel = pdwLevels[iLevel];
dwError = LwAllocateMemory(sizeof(PSID) * dwNumSids,
OUT_PPVOID(&ppSids));
BAIL_ON_WIN_ERROR(dwError);
for (iSid = 0; iSid < dwNumSids; iSid++)
{
PSID pSid = NULL;
DWORD dwSidSize = 0;
if (pTestSids[iSid].pszSid)
{
ntStatus = RtlAllocateSidFromCString(&pSid,
pTestSids[iSid].pszSid);
BAIL_ON_NT_STATUS(ntStatus);
}
else
{
dwSidSize = RtlLengthRequiredSid(pDomainSid->SubAuthorityCount + 1);
dwError = LwAllocateMemory(dwSidSize, OUT_PPVOID(&pSid));
BAIL_ON_WIN_ERROR(dwError);
ntStatus = RtlCopySid(dwSidSize, pSid, pDomainSid);
BAIL_ON_NT_STATUS(ntStatus);
ntStatus = RtlAppendRidSid(dwSidSize, pSid,
pTestSids[iSid].dwRid);
BAIL_ON_NT_STATUS(ntStatus);
}
ppSids[iSid] = pSid;
}
bRet &= CallLsaLookupSids(hLsa, hPolicy, dwNumSids, ppSids, dwLevel,
&ppwszNames, &pdwTypes);
for (iSid = 0; iSid < dwNumSids; iSid++)
{
PWSTR pwszDomain = NULL;
PWSTR pwszName = ppwszNames[iSid];
DWORD dwReturnedType = pdwTypes[iSid];
if (dwReturnedType == SID_TYPE_USE_NONE ||
dwReturnedType == SID_TYPE_INVALID ||
dwReturnedType == SID_TYPE_UNKNOWN)
{
continue;
}
if (pTestSids[iSid].pszDomainName)
{
dwError = LwMbsToWc16s(pTestSids[iSid].pszDomainName,
&pwszDomain);
BAIL_ON_WIN_ERROR(dwError);
}
else
{
dwError = LwAllocateWc16String(&pwszDomain,
pwszDomainName);
BAIL_ON_WIN_ERROR(dwError);
}
dwError = LwMbsToWc16s(pTestSids[iSid].pszName, &pwszName);
BAIL_ON_WIN_ERROR(dwError);
dwError = TestFormatNT4Name(&pwszNT4Name, pwszDomain, pwszName);
BAIL_ON_WIN_ERROR(dwError);
ASSERT_TEST_MSG(ppwszNames[iSid] != NULL, ("(i = %u)\n", iSid));
if (ppwszNames[iSid])
{
ASSERT_TEST_MSG(RtlWC16StringIsEqual(ppwszNames[iSid],
pwszNT4Name,
FALSE),
("(i = %u)\n", iSid));
}
ASSERT_TEST_MSG(dwReturnedType == pTestSids[iSid].dwType,
("(i = %u)\n", iSid));
LW_SAFE_FREE_MEMORY(pwszDomain);
LW_SAFE_FREE_MEMORY(pwszName);
LW_SAFE_FREE_MEMORY(pwszNT4Name);
pwszDomain = NULL;
pwszName = NULL;
pwszNT4Name = NULL;
}
for (iSid = 0; iSid < dwNumSids; iSid++)
{
LW_SAFE_FREE_MEMORY(ppwszNames[iSid]);
}
LW_SAFE_FREE_MEMORY(ppwszNames);
LW_SAFE_FREE_MEMORY(pdwTypes);
ppwszNames = NULL;
pdwTypes = NULL;
}
bRet &= CallLsaClosePolicy(hLsa, &hPolicy);
error:
if (ntStatus != STATUS_SUCCESS ||
dwError != ERROR_SUCCESS)
{
bRet = FALSE;
}
return bRet;
}
static
DWORD
TestLsaQueryInfoPolicy(
PTEST pTest,
PCWSTR pwszHostname,
PCWSTR pwszBindingString,
PCREDENTIALS pCreds,
PPARAMETER pOptions,
DWORD dwOptcount
)
{
const UINT32 access_rights = LSA_ACCESS_LOOKUP_NAMES_SIDS |
LSA_ACCESS_VIEW_POLICY_INFO;
const UINT32 def_level = 0;
BOOLEAN bRet = TRUE;
NTSTATUS ntStatus = STATUS_SUCCESS;
enum param_err perr = perr_success;
LSA_BINDING hLsa = NULL;
POLICY_HANDLE hPolicy = NULL;
LsaPolicyInformation *info = NULL;
UINT32 level = 0;
TESTINFO(pTest, pwszHostname);
perr = fetch_value(pOptions, dwOptcount, "level", pt_uint32, &level,
&def_level);
if (!perr_is_ok(perr)) perr_fail(perr);
bRet &= CreateRpcBinding(OUT_PPVOID(&hLsa),
RPC_LSA_BINDING,
pwszHostname,
pwszBindingString,
pCreds);
ntStatus = LsaOpenPolicy2(hLsa,
pwszHostname,
NULL,
access_rights,
&hPolicy);
BAIL_ON_NT_STATUS(ntStatus);
/*
* level = 1 doesn't work yet for some reason (unmarshalling error probably)
*/
if (level) {
if (level == 1)
{
DISPLAY_ERROR(("Level %u unsupported. Exiting...\n", level));
bRet = FALSE;
goto error;
}
INPUT_ARG_PTR(hLsa);
INPUT_ARG_PTR(hPolicy);
INPUT_ARG_UINT(level);
INPUT_ARG_PTR(&info);
CALL_MSRPC(ntStatus, LsaQueryInfoPolicy(hLsa, hPolicy,
level, &info));
OUTPUT_ARG_PTR(&info);
if (info) {
LsaRpcFreeMemory(info);
}
} else {
for (level = 1; level <= 12; level++) {
if (level == 1) continue;
INPUT_ARG_PTR(hLsa);
INPUT_ARG_PTR(hPolicy);
INPUT_ARG_UINT(level);
INPUT_ARG_PTR(&info);
CALL_MSRPC(ntStatus, LsaQueryInfoPolicy(hLsa, hPolicy,
level, &info));
OUTPUT_ARG_PTR(&info);
if (info) {
LsaRpcFreeMemory(info);
}
info = NULL;
}
}
ntStatus = LsaClose(hLsa, hPolicy);
LsaFreeBinding(&hLsa);
error:
return bRet;
}
static
DWORD
TestLsaQueryInfoPolicy2(
PTEST pTest,
PCWSTR pwszHostname,
PCWSTR pwszBindingString,
PCREDENTIALS pCreds,
PPARAMETER pOptions,
DWORD dwOptcount
)
{
const UINT32 access_rights = LSA_ACCESS_LOOKUP_NAMES_SIDS |
LSA_ACCESS_ENABLE_LSA |
LSA_ACCESS_ADMIN_AUDIT_LOG_ATTRS |
LSA_ACCESS_CHANGE_SYS_AUDIT_REQS |
LSA_ACCESS_SET_DEFAULT_QUOTA |
LSA_ACCESS_CREATE_PRIVILEGE |
LSA_ACCESS_CREATE_SECRET_OBJECT |
LSA_ACCESS_CREATE_SPECIAL_ACCOUNTS |
LSA_ACCESS_CHANGE_DOMTRUST_RELATION |
LSA_ACCESS_GET_SENSITIVE_POLICY_INFO |
LSA_ACCESS_VIEW_SYS_AUDIT_REQS |
LSA_ACCESS_VIEW_POLICY_INFO;
const UINT32 def_level = 0;
BOOLEAN bRet = TRUE;
NTSTATUS ntStatus = STATUS_SUCCESS;
enum param_err perr = perr_success;
LSA_BINDING hLsa = NULL;
POLICY_HANDLE hPolicy = NULL;
LsaPolicyInformation *info = NULL;
UINT32 level = 0;
TESTINFO(pTest, pwszHostname);
perr = fetch_value(pOptions, dwOptcount, "level", pt_uint32, &level,
&def_level);
if (!perr_is_ok(perr)) perr_fail(perr);
bRet &= CreateRpcBinding(OUT_PPVOID(&hLsa),
RPC_LSA_BINDING,
pwszHostname,
pwszBindingString,
pCreds);
ntStatus = LsaOpenPolicy2(hLsa,
pwszHostname,
NULL,
access_rights,
&hPolicy);
BAIL_ON_NT_STATUS(ntStatus);
/*
* level = 1 doesn't work yet for some reason (unmarshalling error probably)
*/
if (level) {
if (level == 1)
{
DISPLAY_ERROR(("Level %u unsupported. Exiting...\n", level));
bRet = FALSE;
goto error;
}
INPUT_ARG_PTR(hLsa);
INPUT_ARG_PTR(hPolicy);
INPUT_ARG_UINT(level);
INPUT_ARG_PTR(&info);
CALL_MSRPC(ntStatus, LsaQueryInfoPolicy2(hLsa, hPolicy,
level, &info));
OUTPUT_ARG_PTR(&info);
if (info) {
LsaRpcFreeMemory(info);
}
} else {
for (level = 1; level <= 12; level++) {
if (level == 1) continue;
INPUT_ARG_PTR(hLsa);
INPUT_ARG_PTR(hPolicy);
INPUT_ARG_UINT(level);
INPUT_ARG_PTR(info);
CALL_MSRPC(ntStatus, LsaQueryInfoPolicy2(hLsa, hPolicy,
level, &info));
OUTPUT_ARG_PTR(info);
if (info) {
LsaRpcFreeMemory(info);
}
info = NULL;
}
}
ntStatus = LsaClose(hLsa, hPolicy);
LsaFreeBinding(&hLsa);
error:
return bRet;
}
static
BOOLEAN
CallLsaLookupNames(
LSA_BINDING hBinding,
POLICY_HANDLE hPolicy,
DWORD dwNumNames,
PWSTR *ppwszNames,
DWORD dwLevel,
PSID **pppSids,
PDWORD *ppdwTypes
)
{
BOOLEAN bRet = TRUE;
NTSTATUS ntStatus = STATUS_SUCCESS;
DWORD dwError = ERROR_SUCCESS;
RefDomainList *pDomains = NULL;
TranslatedSid *pTransSids = NULL;
PSID *ppSids = NULL;
PDWORD pdwTypes = NULL;
DWORD dwCount = 0;
DWORD iSid = 0;
CALL_MSRPC(ntStatus, LsaLookupNames(hBinding,
hPolicy,
dwNumNames,
ppwszNames,
&pDomains,
&pTransSids,
dwLevel,
&dwCount));
if (ntStatus == STATUS_SOME_NOT_MAPPED ||
ntStatus == STATUS_NONE_MAPPED)
{
ntStatus = STATUS_SUCCESS;
}
dwError = LwAllocateMemory(sizeof(PSID) * dwNumNames,
OUT_PPVOID(&ppSids));
BAIL_ON_WIN_ERROR(dwError);
dwError = LwAllocateMemory(sizeof(DWORD) * dwNumNames,
OUT_PPVOID(&pdwTypes));
BAIL_ON_WIN_ERROR(dwError);
for (iSid = 0; iSid < dwCount; iSid++)
{
DWORD iDomain = pTransSids[iSid].index;
DWORD dwRid = pTransSids[iSid].rid;
DWORD dwType = pTransSids[iSid].type;
PSID pDomainSid = NULL;
DWORD dwSidSize = 0;
PSID pSid = NULL;
if (dwType == SID_TYPE_USE_NONE ||
dwType == SID_TYPE_INVALID ||
dwType == SID_TYPE_UNKNOWN)
{
continue;
}
ASSERT_TEST_MSG(iDomain < pDomains->count,
("invalid domain index = %u (i = %u)\n",
iDomain, iSid));
if (iDomain >= 0 && iDomain < pDomains->count)
{
pDomainSid = pDomains->domains[iDomain].sid;
ASSERT_TEST_MSG(pDomainSid != NULL && RtlValidSid(pDomainSid),
("invalid domain SID (i = %u)\n", iSid));
if (RtlValidSid(pDomainSid))
{
dwSidSize = RtlLengthRequiredSid(pDomainSid->SubAuthorityCount + 1);
dwError = LwAllocateMemory(dwSidSize, OUT_PPVOID(&pSid));
BAIL_ON_WIN_ERROR(dwError);
ntStatus = RtlCopySid(dwSidSize, pSid, pDomainSid);
BAIL_ON_NT_STATUS(ntStatus);
ntStatus = RtlAppendRidSid(dwSidSize, pSid, dwRid);
BAIL_ON_NT_STATUS(ntStatus);
}
}
ASSERT_TEST_MSG(dwRid > 0,
("invalid RID = %u (i = %u)\n", dwRid, iSid));
ASSERT_TEST_MSG((dwType >= SID_TYPE_USE_NONE &&
dwType <= SID_TYPE_LABEL),
("invalid type = %u (i = %u)\n", dwType, iSid));
pdwTypes[iSid] = dwType;
ppSids[iSid] = pSid;
}
*pppSids = ppSids;
*ppdwTypes = pdwTypes;
cleanup:
if (pDomains)
{
LsaRpcFreeMemory(pDomains);
}
if (pTransSids)
{
LsaRpcFreeMemory(pTransSids);
}
if (ntStatus != STATUS_SUCCESS ||
dwError != ERROR_SUCCESS)
{
bRet = FALSE;
}
return bRet;
error:
for (iSid = 0; iSid < dwCount; iSid++)
{
RTL_FREE(&(ppSids[iSid]));
}
LW_SAFE_FREE_MEMORY(ppSids);
LW_SAFE_FREE_MEMORY(pdwTypes);
*pppSids = NULL;
*ppdwTypes = NULL;
goto cleanup;
}
static
BOOLEAN
CallLsaLookupNames2(
LSA_BINDING hBinding,
POLICY_HANDLE hPolicy,
DWORD dwNumNames,
PWSTR *ppwszNames,
DWORD dwLevel,
PSID **pppSids,
PDWORD *ppdwTypes
)
{
BOOLEAN bRet = TRUE;
NTSTATUS ntStatus = STATUS_SUCCESS;
DWORD dwError = ERROR_SUCCESS;
RefDomainList *pDomains = NULL;
TranslatedSid2 *pTransSids = NULL;
PSID *ppSids = NULL;
PDWORD pdwTypes = NULL;
DWORD dwCount = 0;
DWORD iSid = 0;
CALL_MSRPC(ntStatus, LsaLookupNames2(hBinding,
hPolicy,
dwNumNames,
ppwszNames,
&pDomains,
&pTransSids,
dwLevel,
&dwCount));
if (ntStatus == STATUS_SOME_NOT_MAPPED ||
ntStatus == STATUS_NONE_MAPPED)
{
ntStatus = STATUS_SUCCESS;
}
dwError = LwAllocateMemory(sizeof(PSID) * dwNumNames,
OUT_PPVOID(&ppSids));
BAIL_ON_WIN_ERROR(dwError);
dwError = LwAllocateMemory(sizeof(DWORD) * dwNumNames,
OUT_PPVOID(&pdwTypes));
BAIL_ON_WIN_ERROR(dwError);
for (iSid = 0; iSid < dwCount; iSid++)
{
DWORD iDomain = pTransSids[iSid].index;
DWORD dwRid = pTransSids[iSid].rid;
DWORD dwType = pTransSids[iSid].type;
PSID pDomainSid = NULL;
DWORD dwSidSize = 0;
PSID pSid = NULL;
if (dwType == SID_TYPE_USE_NONE ||
dwType == SID_TYPE_INVALID ||
dwType == SID_TYPE_UNKNOWN)
{
continue;
}
ASSERT_TEST_MSG(iDomain < pDomains->count,
("invalid domain index = %u (i = %u)\n",
iDomain, iSid));
if (iDomain >= 0 && iDomain < pDomains->count)
{
pDomainSid = pDomains->domains[iDomain].sid;
ASSERT_TEST_MSG(pDomainSid != NULL && RtlValidSid(pDomainSid),
("invalid domain SID (i = %u)\n", iSid));
if (RtlValidSid(pDomainSid))
{
dwSidSize = RtlLengthRequiredSid(pDomainSid->SubAuthorityCount + 1);
dwError = LwAllocateMemory(dwSidSize, OUT_PPVOID(&pSid));
BAIL_ON_WIN_ERROR(dwError);
ntStatus = RtlCopySid(dwSidSize, pSid, pDomainSid);
BAIL_ON_NT_STATUS(ntStatus);
ntStatus = RtlAppendRidSid(dwSidSize, pSid, dwRid);
BAIL_ON_NT_STATUS(ntStatus);
}
}
ASSERT_TEST_MSG(dwRid > 0,
("invalid RID = %u (i = %u)\n", dwRid, iSid));
ASSERT_TEST_MSG((dwType >= SID_TYPE_USE_NONE &&
dwType <= SID_TYPE_LABEL),
("invalid type = %u (i = %u)\n", dwType, iSid));
pdwTypes[iSid] = dwType;
ppSids[iSid] = pSid;
}
*pppSids = ppSids;
*ppdwTypes = pdwTypes;
cleanup:
if (pDomains)
{
LsaRpcFreeMemory(pDomains);
}
if (pTransSids)
{
LsaRpcFreeMemory(pTransSids);
}
if (ntStatus != STATUS_SUCCESS ||
dwError != ERROR_SUCCESS)
{
bRet = FALSE;
}
return bRet;
error:
for (iSid = 0; iSid < dwCount; iSid++)
{
RTL_FREE(&(ppSids[iSid]));
}
LW_SAFE_FREE_MEMORY(ppSids);
LW_SAFE_FREE_MEMORY(pdwTypes);
*pppSids = NULL;
*ppdwTypes = NULL;
goto cleanup;
}
static
BOOLEAN
CallLsaLookupNames3(
LSA_BINDING hBinding,
POLICY_HANDLE hPolicy,
DWORD dwNumNames,
PWSTR *ppwszNames,
DWORD dwLevel,
PSID **pppSids,
PDWORD *ppdwTypes
)
{
BOOLEAN bRet = TRUE;
NTSTATUS ntStatus = STATUS_SUCCESS;
DWORD dwError = ERROR_SUCCESS;
RefDomainList *pDomains = NULL;
TranslatedSid3 *pTransSids = NULL;
PSID *ppSids = NULL;
PDWORD pdwTypes = NULL;
DWORD dwCount = 0;
DWORD iSid = 0;
CALL_MSRPC(ntStatus, LsaLookupNames3(hBinding,
hPolicy,
dwNumNames,
ppwszNames,
&pDomains,
&pTransSids,
dwLevel,
&dwCount));
if (ntStatus == STATUS_SOME_NOT_MAPPED ||
ntStatus == STATUS_NONE_MAPPED)
{
ntStatus = STATUS_SUCCESS;
}
dwError = LwAllocateMemory(sizeof(PSID) * dwNumNames,
OUT_PPVOID(&ppSids));
BAIL_ON_WIN_ERROR(dwError);
dwError = LwAllocateMemory(sizeof(DWORD) * dwNumNames,
OUT_PPVOID(&pdwTypes));
BAIL_ON_WIN_ERROR(dwError);
for (iSid = 0; iSid < dwCount; iSid++)
{
DWORD iDomain = pTransSids[iSid].index;
DWORD dwType = pTransSids[iSid].type;
PSID pSid = pTransSids[iSid].sid;
PSID pDomainSid = NULL;
PSID pRetSid = NULL;
if (dwType == SID_TYPE_USE_NONE ||
dwType == SID_TYPE_INVALID ||
dwType == SID_TYPE_UNKNOWN)
{
continue;
}
ASSERT_TEST_MSG(iDomain < pDomains->count,
("invalid domain index = %u (i = %u)\n",
iDomain, iSid));
if (iDomain >= 0 && iDomain < pDomains->count)
{
pDomainSid = pDomains->domains[iDomain].sid;
ASSERT_TEST_MSG(pDomainSid != NULL && RtlValidSid(pDomainSid),
("invalid domain SID (i = %u)\n", iSid));
}
ASSERT_TEST_MSG(pSid != NULL && RtlValidSid(pSid),
("invalid SID (i = %u)\n", iSid));
if (RtlValidSid(pSid))
{
ntStatus = RtlDuplicateSid(&pRetSid, pSid);
BAIL_ON_NT_STATUS(ntStatus);
}
ASSERT_TEST_MSG((dwType >= SID_TYPE_USE_NONE &&
dwType <= SID_TYPE_LABEL),
("invalid type = %u (i = %u)\n", dwType, iSid));
pdwTypes[iSid] = dwType;
ppSids[iSid] = pRetSid;
}
*pppSids = ppSids;
*ppdwTypes = pdwTypes;
cleanup:
if (pDomains)
{
LsaRpcFreeMemory(pDomains);
}
if (pTransSids)
{
LsaRpcFreeMemory(pTransSids);
}
if (ntStatus != STATUS_SUCCESS ||
dwError != ERROR_SUCCESS)
{
bRet = FALSE;
}
return bRet;
error:
for (iSid = 0; iSid < dwCount; iSid++)
{
RTL_FREE(&(ppSids[iSid]));
}
LW_SAFE_FREE_MEMORY(ppSids);
LW_SAFE_FREE_MEMORY(pdwTypes);
*pppSids = NULL;
*ppdwTypes = NULL;
goto cleanup;
}
static
BOOLEAN
CallLsaLookupSids(
LSA_BINDING hBinding,
POLICY_HANDLE hPolicy,
DWORD dwNumSids,
PSID *ppSids,
DWORD dwLevel,
PWSTR **pppwszNames,
PDWORD *ppdwTypes
)
{
BOOLEAN bRet = TRUE;
NTSTATUS ntStatus = STATUS_SUCCESS;
DWORD dwError = ERROR_SUCCESS;
SID_ARRAY Sids = {0};
RefDomainList *pDomains = NULL;
TranslatedName *pTransNames = NULL;
PWSTR *ppwszNames = NULL;
PDWORD pdwTypes = NULL;
DWORD dwCount = 0;
DWORD iSid = 0;
DWORD iName = 0;
PSID pInvalidSid = NULL;
Sids.dwNumSids = dwNumSids;
dwError = LwAllocateMemory(sizeof(SID_PTR) * dwNumSids,
OUT_PPVOID(&Sids.pSids));
BAIL_ON_WIN_ERROR(dwError);
ntStatus = RtlAllocateSidFromCString(&pInvalidSid,
"S-1-5-32-0");
BAIL_ON_NT_STATUS(ntStatus);
for (iSid = 0; iSid < dwNumSids; iSid++)
{
/* Replace NULL SIDs with an invalid SID because CallLookupSids
may be called in sequence of other lookup calls, so keeping
"invalid" names/SIDs in the same indices is important for
further validation */
Sids.pSids[iSid].pSid = ppSids[iSid] ? ppSids[iSid] : pInvalidSid;
}
CALL_MSRPC(ntStatus, LsaLookupSids(hBinding,
hPolicy,
&Sids,
&pDomains,
&pTransNames,
dwLevel,
&dwCount));
if (ntStatus == STATUS_SOME_NOT_MAPPED ||
ntStatus == STATUS_NONE_MAPPED)
{
ntStatus = STATUS_SUCCESS;
}
dwError = LwAllocateMemory(sizeof(PWSTR) * dwNumSids,
OUT_PPVOID(&ppwszNames));
BAIL_ON_WIN_ERROR(dwError);
dwError = LwAllocateMemory(sizeof(DWORD) * dwNumSids,
OUT_PPVOID(&pdwTypes));
BAIL_ON_WIN_ERROR(dwError);
for (iName = 0; iName < dwCount; iName++)
{
DWORD iDomain = pTransNames[iName].sid_index;
DWORD dwType = pTransNames[iName].type;
PWSTR pwszDomainName = NULL;
PWSTR pwszTranslatedName = NULL;
PWSTR pwszName = NULL;
if (dwType == SID_TYPE_USE_NONE ||
dwType == SID_TYPE_INVALID ||
dwType == SID_TYPE_UNKNOWN)
{
continue;
}
ASSERT_TEST_MSG(iDomain < pDomains->count,
("invalid domain index = %u (i = %u)\n",
iDomain, iName));
ASSERT_TEST_MSG((dwType >= SID_TYPE_USE_NONE &&
dwType <= SID_TYPE_LABEL),
("invalid type = %u (i = %u)\n", dwType, iName));
if (iDomain >= 0 && iDomain < pDomains->count)
{
ASSERT_UNICODE_STRING_VALID_MSG(&(pDomains->domains[iDomain].name),
("invalid unicode name (i = %u)\n",
iName));
ASSERT_UNICODE_STRING_VALID_MSG(&(pTransNames[iName].name),
("invalid unicode name (i = %u)\n",
iName));
dwError = LwAllocateWc16StringFromUnicodeString(
&pwszDomainName,
(PUNICODE_STRING)&pDomains->domains[iDomain].name);
BAIL_ON_WIN_ERROR(dwError);
dwError = LwAllocateWc16StringFromUnicodeString(
&pwszTranslatedName,
(PUNICODE_STRING)&pTransNames[iName].name);
BAIL_ON_WIN_ERROR(dwError);
dwError = TestFormatNT4Name(&pwszName,
pwszDomainName, pwszTranslatedName);
BAIL_ON_WIN_ERROR(dwError);
}
ppwszNames[iName] = pwszName;
pdwTypes[iName] = dwType;
LW_SAFE_FREE_MEMORY(pwszDomainName);
LW_SAFE_FREE_MEMORY(pwszTranslatedName);
pwszDomainName = NULL;
pwszTranslatedName = NULL;
}
*pppwszNames = ppwszNames;
*ppdwTypes = pdwTypes;
cleanup:
if (pDomains)
{
LsaRpcFreeMemory(pDomains);
}
if (pTransNames)
{
LsaRpcFreeMemory(pTransNames);
}
LW_SAFE_FREE_MEMORY(Sids.pSids);
RTL_FREE(&pInvalidSid);
if (ntStatus != STATUS_SUCCESS ||
dwError != ERROR_SUCCESS)
{
bRet = FALSE;
}
return bRet;
error:
for (iName = 0; iName < dwCount; iName++)
{
LW_SAFE_FREE_MEMORY(ppwszNames[iName]);
}
LW_SAFE_FREE_MEMORY(ppwszNames);
LW_SAFE_FREE_MEMORY(pdwTypes);
*pppwszNames = NULL;
*ppdwTypes = NULL;
goto cleanup;
}
static
BOOLEAN
CallLsaOpenPolicy(
LSA_BINDING hBinding,
PWSTR pwszSysName,
DWORD dwAccessRights,
POLICY_HANDLE *phPolicy,
PWSTR *ppwszDomainName,
PWSTR *ppwszDnsDomainName,
PSID *ppDomainSid
)
{
BOOL bRet = TRUE;
NTSTATUS ntStatus = STATUS_SUCCESS;
DWORD dwError = ERROR_SUCCESS;
DWORD dwMaxAccessRights = LSA_ACCESS_LOOKUP_NAMES_SIDS |
LSA_ACCESS_ENABLE_LSA |
LSA_ACCESS_ADMIN_AUDIT_LOG_ATTRS |
LSA_ACCESS_CHANGE_SYS_AUDIT_REQS |
LSA_ACCESS_SET_DEFAULT_QUOTA |
LSA_ACCESS_CREATE_PRIVILEGE |
LSA_ACCESS_CREATE_SECRET_OBJECT |
LSA_ACCESS_CREATE_SPECIAL_ACCOUNTS |
LSA_ACCESS_CHANGE_DOMTRUST_RELATION |
LSA_ACCESS_GET_SENSITIVE_POLICY_INFO |
LSA_ACCESS_VIEW_SYS_AUDIT_REQS |
LSA_ACCESS_VIEW_POLICY_INFO;
DWORD dwMinAccessRights = LSA_ACCESS_LOOKUP_NAMES_SIDS;
DWORD dwDefAccessRights = LSA_ACCESS_LOOKUP_NAMES_SIDS |
LSA_ACCESS_VIEW_POLICY_INFO;
POLICY_HANDLE hPolicy = NULL;
LsaPolicyInformation *pPolicyInfo = NULL;
LsaPolicyInformation *pDomainInfo = NULL;
LsaPolicyInformation *pDnsDomainInfo = NULL;
DWORD i = 0;
DISPLAY_COMMENT(("Testing LsaOpenPolicy\n"));
CALL_MSRPC(ntStatus, LsaOpenPolicy2(hBinding,
pwszSysName,
NULL,
dwMaxAccessRights,
&hPolicy));
BAIL_ON_NT_STATUS(ntStatus);
for (i = 1; i <= 12; i++)
{
if (i == 1) continue;
DISPLAY_COMMENT(("Testing LsaQueryInfoPolicy (level = %u)\n", i));
CALL_MSRPC(ntStatus, LsaQueryInfoPolicy(hBinding,
hPolicy,
i,
&pPolicyInfo));
if (ntStatus != STATUS_SUCCESS) continue;
switch (i)
{
case LSA_POLICY_INFO_DOMAIN:
pDomainInfo = pPolicyInfo;
break;
case LSA_POLICY_INFO_DNS:
pDnsDomainInfo = pPolicyInfo;
break;
default:
if (pPolicyInfo)
{
LsaRpcFreeMemory(pPolicyInfo);
pPolicyInfo = NULL;
}
break;
}
}
ASSERT_UNICODE_STRING_EQUAL((PUNICODE_STRING)&pDomainInfo->domain.name,
(PUNICODE_STRING)&pDnsDomainInfo->dns.name);
ASSERT_SID_EQUAL(pDomainInfo->domain.sid, pDnsDomainInfo->dns.sid);
DISPLAY_COMMENT(("Testing LsaClose\n"));
CALL_MSRPC(ntStatus, LsaClose(hBinding, hPolicy));
hPolicy = NULL;
DISPLAY_COMMENT(("Testing LsaOpenPolicy2\n"));
CALL_MSRPC(ntStatus, LsaOpenPolicy2(hBinding,
pwszSysName,
NULL,
dwMinAccessRights,
&hPolicy));
BAIL_ON_NT_STATUS(ntStatus);
for (i = 1; i <= 12; i++)
{
if (i == 1) continue;
DISPLAY_COMMENT(("Testing LsaQueryInfoPolicy2 (level = %u)\n", i));
ntStatus = LsaQueryInfoPolicy2(hBinding, hPolicy, i, &pPolicyInfo);
if (i == LSA_POLICY_INFO_DB ||
i == LSA_POLICY_INFO_AUDIT_FULL_SET ||
i == LSA_POLICY_INFO_AUDIT_FULL_QUERY)
{
/* ignore audit-related info levels */
continue;
}
ASSERT_TEST_MSG((ntStatus == STATUS_ACCESS_DENIED),
("Expected: STATUS_ACCESS_DENIED, "
"Received: %s (0x%08x)\n",
LwNtStatusToName(ntStatus), ntStatus));
ASSERT_TEST((pPolicyInfo == NULL));
}
DISPLAY_COMMENT(("Testing LsaClose\n"));
CALL_MSRPC(ntStatus, LsaClose(hBinding, hPolicy));
hPolicy = NULL;
DISPLAY_COMMENT(("Testing LsaOpenPolicy2\n"));
if (dwAccessRights == 0)
{
dwAccessRights = dwDefAccessRights;
}
CALL_MSRPC(ntStatus, LsaOpenPolicy2(hBinding,
pwszSysName,
NULL,
dwAccessRights,
&hPolicy));
BAIL_ON_NT_STATUS(ntStatus);
*phPolicy = hPolicy;
if (ppwszDomainName)
{
dwError = LwAllocateWc16StringFromUnicodeString(
ppwszDomainName,
(PUNICODE_STRING)&pDomainInfo->domain.name);
BAIL_ON_WIN_ERROR(dwError);
}
if (ppwszDnsDomainName)
{
dwError = LwAllocateWc16StringFromUnicodeString(
ppwszDnsDomainName,
(PUNICODE_STRING)&pDnsDomainInfo->dns.name);
BAIL_ON_WIN_ERROR(dwError);
}
if (ppDomainSid)
{
ntStatus = RtlDuplicateSid(ppDomainSid, pDomainInfo->domain.sid);
BAIL_ON_NT_STATUS(ntStatus);
}
error:
if (pDomainInfo)
{
LsaRpcFreeMemory(pDomainInfo);
}
if (pDnsDomainInfo)
{
LsaRpcFreeMemory(pDnsDomainInfo);
}
if (dwError != ERROR_SUCCESS ||
ntStatus != STATUS_SUCCESS)
{
bRet = FALSE;
}
return bRet;
}
static
BOOLEAN
CallLsaClosePolicy(
LSA_BINDING hBinding,
POLICY_HANDLE *phPolicy
)
{
BOOLEAN bRet = TRUE;
NTSTATUS ntStatus = STATUS_SUCCESS;
POLICY_HANDLE hPolicy = NULL;
DISPLAY_COMMENT(("Testing LsaClose\n"));
hPolicy = *phPolicy;
CALL_MSRPC(ntStatus, LsaClose(hBinding, hPolicy));
BAIL_ON_NT_STATUS(ntStatus);
error:
return bRet;
}
static
DWORD
TestLsaInfoPolicy(
PTEST pTest,
PCWSTR pwszHostname,
PCWSTR pwszBindingString,
PCREDENTIALS pCreds,
PPARAMETER pOptions,
DWORD dwOptcount
)
{
PCSTR pszDefSysName = "";
BOOL bRet = TRUE;
enum param_err perr = perr_success;
LSA_BINDING hLsa = NULL;
POLICY_HANDLE hPolicy = NULL;
PWSTR pwszSysName = NULL;
perr = fetch_value(pOptions, dwOptcount, "systemname", pt_w16string,
&pwszSysName, &pszDefSysName);
if (!perr_is_ok(perr)) perr_fail(perr);
TESTINFO(pTest, pwszHostname);
bRet &= CreateRpcBinding(OUT_PPVOID(&hLsa),
RPC_LSA_BINDING,
pwszHostname,
pwszBindingString,
pCreds);
bRet &= CallLsaOpenPolicy(hLsa, pwszSysName, 0, &hPolicy, NULL, NULL, NULL);
bRet &= CallLsaClosePolicy(hLsa, &hPolicy);
LsaFreeBinding(&hLsa);
bRet &= CreateRpcBinding(OUT_PPVOID(&hLsa),
RPC_LSA_BINDING,
pwszHostname,
pwszBindingString,
pCreds);
bRet &= CallLsaOpenPolicy(hLsa, pwszSysName, 0, &hPolicy, NULL, NULL, NULL);
bRet &= CallLsaClosePolicy(hLsa, &hPolicy);
LsaFreeBinding(&hLsa);
LW_SAFE_FREE_MEMORY(pwszSysName);
return (int)bRet;
}
VOID
SetupLsaTests(PTEST t)
{
AddTest(t, "LSA-OPEN-POLICY", TestLsaOpenPolicy);
AddTest(t, "LSA-LOOKUP-NAMES", TestLsaLookupNames);
AddTest(t, "LSA-LOOKUP-NAMES2", TestLsaLookupNames2);
AddTest(t, "LSA-LOOKUP-NAMES3", TestLsaLookupNames3);
AddTest(t, "LSA-LOOKUP-SIDS", TestLsaLookupSids);
AddTest(t, "LSA-QUERY-INFO-POL", TestLsaQueryInfoPolicy);
AddTest(t, "LSA-QUERY-INFO-POL2", TestLsaQueryInfoPolicy2);
AddTest(t, "LSA-INFO-POLICY", TestLsaInfoPolicy);
}
/*
local variables:
mode: c
c-basic-offset: 4
indent-tabs-mode: nil
tab-width: 4
end:
*/
| 40,824 |
319 | <gh_stars>100-1000
/**
* Copyright (c) 2011, The University of Southampton and the individual contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the University of Southampton 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.openimaj.image.objectdetection.haar;
import java.io.IOException;
import org.junit.Test;
import org.openimaj.image.objectdetection.haar.OCVHaarLoader;
/**
* Tests for the OpenCV haar cascade loader
*
* @author <NAME> (<EMAIL>)
*
*/
public class OCVHaarLoaderTest {
String[] goodCascades = {
"haarcascade_eye_tree_eyeglasses.xml",
"haarcascade_eye.xml",
"haarcascade_frontalface_alt_tree.xml",
"haarcascade_frontalface_alt.xml",
"haarcascade_frontalface_alt2.xml",
"haarcascade_frontalface_default.xml",
"haarcascade_fullbody.xml",
"haarcascade_lefteye_2splits.xml",
"haarcascade_lowerbody.xml",
"haarcascade_mcs_eyepair_big.xml",
"haarcascade_mcs_eyepair_small.xml",
"haarcascade_mcs_lefteye.xml",
"haarcascade_mcs_mouth.xml",
"haarcascade_mcs_nose.xml",
"haarcascade_mcs_righteye.xml",
"haarcascade_mcs_upperbody.xml",
"haarcascade_profileface.xml",
"haarcascade_righteye_2splits.xml",
"haarcascade_upperbody.xml"
};
String badCascade = "lbpcascade_frontalface.xml";
/**
* Test the internal read method
*
* @throws IOException
*/
@Test
public void testReadNode() throws IOException {
for (final String c : goodCascades) {
OCVHaarLoader.readXPP(OCVHaarLoader.class.getResourceAsStream(c));
}
}
/**
* Test the conversion to proper objects
*
* @throws IOException
*/
@Test
public void testRead() throws IOException {
for (final String c : goodCascades) {
OCVHaarLoader.read(OCVHaarLoader.class.getResourceAsStream(c));
}
}
/**
* Test that reading the new style cascade throws an exception
*
* @throws IOException
*/
@Test(expected = IOException.class)
public void testReadNodeBad() throws IOException {
OCVHaarLoader.readXPP(OCVHaarLoader.class.getResourceAsStream(badCascade));
}
}
| 1,186 |
777 | <filename>tools/clang/blink_gc_plugin/tests/member_in_offheap_class.cpp
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "member_in_offheap_class.h"
namespace blink {
void OffHeapObject::trace(Visitor* visitor)
{
visitor->trace(m_obj);
}
void PartObject::trace(Visitor* visitor)
{
visitor->trace(m_obj);
}
void InlineObject::trace(Visitor* visitor)
{
visitor->trace(m_obj);
}
}
| 186 |
362 | package subreddit.android.appstore.screens.list;
import android.content.SharedPreferences;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import subreddit.android.appstore.backend.data.AppInfo;
import subreddit.android.appstore.backend.data.AppTags;
import subreddit.android.appstore.backend.reddit.wiki.WikiRepository;
import subreddit.android.appstore.screens.navigation.CategoryFilter;
import subreddit.android.appstore.screens.settings.SettingsActivity;
import timber.log.Timber;
public class AppListPresenter implements AppListContract.Presenter {
final WikiRepository repository;
final CategoryFilter categoryFilter;
private SharedPreferences sharedPreferences;
private Disposable listUpdater;
private Disposable tagUpdater;
AppListContract.View view;
public AppListPresenter(WikiRepository repository, CategoryFilter categoryFilter, SharedPreferences preferences) {
this.repository = repository;
this.categoryFilter = categoryFilter;
this.sharedPreferences = preferences;
}
@Override
public void onCreate(Bundle bundle) {
}
@Override
public void onAttachView(final AppListContract.View view) {
this.view = view;
view.showLoadingScreen();
Observable<List<AppInfo>> filteredData = repository.getAppList()
.observeOn(Schedulers.computation())
.map(appInfos -> {
ArrayList<AppInfo> data = new ArrayList<>(appInfos);
List<AppInfo> filteredData1 = new ArrayList<>();
Timber.d("Filtering to %s %s %s %s",categoryFilter.getPrimaryCategory(), categoryFilter.getSecondaryCategory(), categoryFilter.getTertiaryCategory(), categoryFilter.isNewlyAdded());
for (AppInfo app : data) {
if (app.getTags().contains(AppTags.NEW) && categoryFilter.isNewlyAdded() != null) {
filteredData1.add(app);
continue;
}
if ((app.getPrimaryCategory().equals(categoryFilter.getPrimaryCategory()) || categoryFilter.getPrimaryCategory() == null) &&
(app.getSecondaryCategory().equals(categoryFilter.getSecondaryCategory()) || categoryFilter.getSecondaryCategory() == null) &&
(app.getTertiaryCategory().equals(categoryFilter.getTertiaryCategory()) || categoryFilter.getTertiaryCategory() == null)) {
filteredData1.add(app);
}
}
Collections.sort(filteredData1);
return filteredData1;
}).replay().refCount();
listUpdater = filteredData
.observeOn(AndroidSchedulers.mainThread())
.subscribe(appInfos -> {
Timber.d("showAppList(%s items)", appInfos.size());
AppListPresenter.this.view.showAppList(appInfos);
if (saveTagFiltersSelected()) {
AppListPresenter.this.view.restoreSelectedTags(getSavedTagFilters());
}
});
tagUpdater = filteredData
.observeOn(Schedulers.computation())
.map(new Function<Collection<AppInfo>, TagMap>() {
@Override
public TagMap apply(Collection<AppInfo> appInfos) throws Exception {
return new TagMap(appInfos);
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(tagMap -> {
Timber.d("updateTagCount(%s)", tagMap);
AppListPresenter.this.view.updateTagCount(tagMap);
});
filteredData
.observeOn(AndroidSchedulers.mainThread())
.subscribe(appInfos -> {
if (appInfos.size()<1) {
view.showError();
}
});
}
@Override
public void onDetachView() {
if (saveTagFiltersSelected()) {
saveSelectedTags(AppListPresenter.this.view.getSelectedTags());
}
listUpdater.dispose();
tagUpdater.dispose();
view = null;
}
@Override
public void onSaveInstanceState(Bundle bundle) {
}
@Override
public void onDestroy() {
}
@Override
public void refreshData() {
view.showLoadingScreen();
repository.refresh();
}
private boolean saveTagFiltersSelected() {
return sharedPreferences.getBoolean(SettingsActivity.PREF_KEY_SAVE_TAG_FILTERS, false);
}
private Collection<AppTags> getSavedTagFilters() {
List<AppTags> data = Arrays.asList(AppTags.values());
Collection<AppTags> appTags = new ArrayList<>();
for (int i = 0; i < data.size(); i++) {
if (sharedPreferences.getBoolean("savedTags_" + i, false)) {
appTags.add(data.get(i));
}
}
return appTags;
}
public void saveSelectedTags(Collection<AppTags> appTags) {
List<AppTags> data = Arrays.asList(AppTags.values());
SharedPreferences.Editor editor = sharedPreferences.edit();
for (int i = 0; i < data.size(); i++) {
if (appTags.contains(data.get(i))) {
editor.putBoolean("savedTags_" + i, true);
}
}
editor.commit();
}
}
| 2,674 |
675 | <gh_stars>100-1000
/*
* Copyright 2018 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.java;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.idea.blaze.base.model.primitives.Kind;
import com.google.idea.blaze.base.model.primitives.LanguageClass;
import com.google.idea.blaze.base.model.primitives.RuleType;
import java.util.Arrays;
import java.util.Collection;
/**
* Android-specific blaze rules. This class is in the java module because android support is
* provided for both IntelliJ and Android Studio.
*/
public final class AndroidBlazeRules implements Kind.Provider {
/** Android-specific blaze rules. */
public enum RuleTypes {
ANDROID_BINARY("android_binary", LanguageClass.ANDROID, RuleType.BINARY),
ANDROID_LIBRARY("android_library", LanguageClass.ANDROID, RuleType.LIBRARY),
ANDROID_TEST("android_test", LanguageClass.ANDROID, RuleType.TEST),
ANDROID_ROBOLECTRIC_TEST("android_robolectric_test", LanguageClass.ANDROID, RuleType.TEST),
ANDROID_LOCAL_TEST("android_local_test", LanguageClass.ANDROID, RuleType.TEST),
ANDROID_INSTRUMENTATION_TEST(
"android_instrumentation_test", LanguageClass.ANDROID, RuleType.TEST),
ANDROID_SDK("android_sdk", LanguageClass.ANDROID, RuleType.UNKNOWN),
AAR_IMPORT("aar_import", LanguageClass.ANDROID, RuleType.UNKNOWN),
ANDROID_RESOURCES("android_resources", LanguageClass.ANDROID, RuleType.UNKNOWN),
KT_ANDROID_LIBRARY_HELPER(
"kt_android_library_helper",
ImmutableSet.of(LanguageClass.ANDROID, LanguageClass.KOTLIN),
RuleType.LIBRARY),
;
private final String name;
private final ImmutableSet<LanguageClass> languageClasses;
private final RuleType ruleType;
RuleTypes(String name, Collection<LanguageClass> languageClasses, RuleType ruleType) {
this.name = name;
this.languageClasses = ImmutableSet.copyOf(languageClasses);
this.ruleType = ruleType;
}
RuleTypes(String name, LanguageClass languageClass, RuleType ruleType) {
this(name, ImmutableSet.of(languageClass), ruleType);
}
public Kind getKind() {
return Preconditions.checkNotNull(Kind.fromRuleName(name));
}
}
@Override
public ImmutableSet<Kind> getTargetKinds() {
return Arrays.stream(RuleTypes.values())
.map(e -> Kind.Provider.create(e.name, e.languageClasses, e.ruleType))
.collect(toImmutableSet());
}
}
| 1,050 |
1,405 | package com.tendcloud.tenddata;
final class ac implements Runnable {
ac() {
}
public void run() {
TCAgent.c(TCAgent.f());
if (TCAgent.j() == 0) {
TCAgent.c(System.currentTimeMillis());
}
if (TCAgent.b()) {
TCAgent.f = u.u();
}
TCAgent.b(0);
TCAgent.a(7, 1000);
}
}
| 203 |
432 | <gh_stars>100-1000
import json
import os
import random
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_cytoscape as cyto
asset_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'..', 'assets'
)
app = dash.Dash(__name__, assets_folder=asset_path)
server = app.server
random.seed(2019)
nodes = [
{'data': {'id': str(i), 'label': 'Node {}'.format(i)}}
for i in range(1, 21)
]
edges = [
{'data': {'source': str(random.randint(1, 20)), 'target': str(random.randint(1, 20))}}
for _ in range(30)
]
default_elements = nodes + edges
styles = {
'json-output': {
'overflow-y': 'scroll',
'height': 'calc(50% - 25px)',
'border': 'thin lightgrey solid'
},
'tab': {'height': 'calc(98vh - 115px)'}
}
app.layout = html.Div([
html.Div(className='eight columns', children=[
cyto.Cytoscape(
id='cytoscape',
elements=default_elements,
layout={
'name': 'grid'
},
style={
'height': '95vh',
'width': '100%'
}
)
]),
html.Div(className='four columns', children=[
dcc.Tabs(id='tabs', children=[
dcc.Tab(label='Actions', children=[
html.Button("Remove Selected Node", id='remove-button')
]),
dcc.Tab(label='Tap Data', children=[
html.Div(style=styles['tab'], children=[
html.P('Node Data JSON:'),
html.Pre(
id='tap-node-data-json-output',
style=styles['json-output']
),
html.P('Edge Data JSON:'),
html.Pre(
id='tap-edge-data-json-output',
style=styles['json-output']
)
])
]),
dcc.Tab(label='Selected Data', children=[
html.Div(style=styles['tab'], children=[
html.P('Node Data JSON:'),
html.Pre(
id='selected-node-data-json-output',
style=styles['json-output']
),
html.P('Edge Data JSON:'),
html.Pre(
id='selected-edge-data-json-output',
style=styles['json-output']
)
])
])
]),
])
])
@app.callback(Output('cytoscape', 'elements'),
[Input('remove-button', 'n_clicks')],
[State('cytoscape', 'elements'),
State('cytoscape', 'selectedNodeData')])
def remove_selected_nodes(_, elements, data):
if elements and data:
ids_to_remove = {ele_data['id'] for ele_data in data}
print("Before:", elements)
new_elements = [ele for ele in elements if ele['data']['id'] not in ids_to_remove]
print("After:", new_elements)
return new_elements
return elements
@app.callback(Output('tap-node-data-json-output', 'children'),
[Input('cytoscape', 'tapNodeData')])
def displayTapNodeData(data):
return json.dumps(data, indent=2)
@app.callback(Output('tap-edge-data-json-output', 'children'),
[Input('cytoscape', 'tapEdgeData')])
def displayTapEdgeData(data):
return json.dumps(data, indent=2)
@app.callback(Output('selected-node-data-json-output', 'children'),
[Input('cytoscape', 'selectedNodeData')])
def displaySelectedNodeData(data):
return json.dumps(data, indent=2)
@app.callback(Output('selected-edge-data-json-output', 'children'),
[Input('cytoscape', 'selectedEdgeData')])
def displaySelectedEdgeData(data):
return json.dumps(data, indent=2)
if __name__ == '__main__':
app.run_server(debug=True)
| 2,012 |
1,122 | <filename>Algorithms/Strings/Mars Exploration/Solution.java
//Problem: https://www.hackerrank.com/challenges/mars-exploration
//Java 8
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String S = in.next();
int count = 0;
int currentPos = 0;
for(char letter : S.toCharArray())
{
if(currentPos % 3 == 1)
{
count += (letter != 'O') ? 1 : 0;
}
else
{
count += (letter != 'S') ? 1 : 0;
}
currentPos++;
}
System.out.println(count);
}
}
| 427 |
343 | from django import template
register = template.Library()
@register.filter(is_safe=True)
def ListToStr(l,nu):
return l[nu]
| 52 |
13,846 | <gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#include "precomp.h"
class ADMINISTRATION_CONFIG_PATH_MAPPER : public IAppHostPathMapper
{
public:
ADMINISTRATION_CONFIG_PATH_MAPPER(
VOID
) : _cRefs( 1 )
{
}
~ADMINISTRATION_CONFIG_PATH_MAPPER(
VOID
)
{
}
HRESULT
Initialize()
{
// TODO this could be more reliable.
HRESULT hr = NOERROR;
DWORD cch;
cch = ExpandEnvironmentStringsW(
L"%windir%\\system32\\inetsrv\\config\\administration.config",
_strMappedPath.QueryStr(),
_strMappedPath.QuerySizeCCH()
);
if( !cch )
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto exit;
}
if( cch > _strMappedPath.QuerySizeCCH() )
{
hr = _strMappedPath.Resize( cch );
if( FAILED(hr) )
{
goto exit;
}
cch = ExpandEnvironmentStringsW(
L"%windir%\\system32\\inetsrv\\config\\administration.config",
_strMappedPath.QueryStr(),
_strMappedPath.QuerySizeCCH()
);
if( !cch ||
cch > _strMappedPath.QuerySizeCCH() )
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto exit;
}
}
_strMappedPath.SyncWithBuffer();
exit:
return hr;
}
ULONG
STDMETHODCALLTYPE
AddRef(
VOID
)
{
return InterlockedIncrement( &_cRefs );
}
ULONG
STDMETHODCALLTYPE
Release(
VOID
)
{
ULONG ulRet = 0;
ulRet = InterlockedDecrement( &_cRefs );
if ( ulRet == 0 )
{
delete this;
}
return ulRet;
}
HRESULT
STDMETHODCALLTYPE
QueryInterface(
REFIID riid,
void ** ppObject
)
{
if ( riid == __uuidof(IUnknown) ||
riid == __uuidof(IAppHostPathMapper) )
{
AddRef();
*ppObject = (IAppHostPathMapper*) this;
return S_OK;
}
else
{
*ppObject = NULL;
return E_NOINTERFACE;
}
}
HRESULT
STDMETHODCALLTYPE
MapPath(
BSTR bstrConfigPath,
BSTR bstrMappedPhysicalPath,
BSTR * pbstrNewPhysicalPath
)
{
BSTR bstrNewPhysicalPath = NULL;
if ( wcscmp( bstrConfigPath, L"MACHINE/WEBROOT" ) == 0 )
{
bstrNewPhysicalPath = SysAllocString( _strMappedPath.QueryStr() );
}
else
{
bstrNewPhysicalPath = SysAllocString( bstrMappedPhysicalPath );
}
if ( bstrNewPhysicalPath == NULL )
{
return HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY );
}
*pbstrNewPhysicalPath = bstrNewPhysicalPath;
return S_OK;
}
private:
LONG _cRefs;
STRU _strMappedPath;
};
HRESULT
InitAdminMgrForAdminConfig(
IN IAppHostWritableAdminManager * pAdminMgr,
IN CONST WCHAR * szCommitPath
)
{
HRESULT hr = NOERROR;
VARIANT varPathMapper;
VariantInit( &varPathMapper );
BSTR bstrPathMapperName = SysAllocString( L"pathMapper" );
BSTR bstrCommitPath = SysAllocString( szCommitPath );
ADMINISTRATION_CONFIG_PATH_MAPPER * pPathMapper = NULL;
if( !bstrPathMapperName || !bstrCommitPath)
{
hr = E_OUTOFMEMORY;
DBGERROR_HR(hr);
goto exit;
}
hr = pAdminMgr->put_CommitPath( bstrCommitPath );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
pPathMapper = new ADMINISTRATION_CONFIG_PATH_MAPPER();
if( !pPathMapper )
{
hr = E_OUTOFMEMORY;
DBGERROR_HR(hr);
goto exit;
}
hr = pPathMapper->Initialize();
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
varPathMapper.vt = VT_UNKNOWN;
varPathMapper.punkVal = pPathMapper;
pPathMapper = NULL;
hr = pAdminMgr->SetMetadata( bstrPathMapperName, varPathMapper );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
exit:
SysFreeString( bstrPathMapperName );
SysFreeString( bstrCommitPath );
VariantClear( &varPathMapper );
if( pPathMapper )
{
pPathMapper->Release();
pPathMapper = NULL;
}
return hr;
}
HRESULT
RegisterUIModule(
IN CONST WCHAR * szModuleName,
IN CONST WCHAR * szModuleTypeInfo,
IN OPTIONAL CONST WCHAR * szRegisterInModulesSection,
IN OPTIONAL CONST WCHAR * szPrependToList
)
{
HRESULT hr = NOERROR;
CComPtr<IAppHostWritableAdminManager> pAdminMgr;
CComPtr<IAppHostElement> pProvidersSection;
CComPtr<IAppHostElementCollection> pProvidersCollection;
CComPtr<IAppHostElement> pNewModuleElement;
CComPtr<IAppHostElement> pModulesSection;
CComPtr<IAppHostElementCollection> pModulesCollection;
CComPtr<IAppHostElement> pModulesCollectionElement;
VARIANT varValue;
VariantInit( &varValue );
DWORD dwIndex;
BOOL fAddElement = FALSE;
INT cIndex;
BSTR bstrCommitPath = SysAllocString( L"MACHINE/WEBROOT" );
BSTR bstrModuleProvidersName = SysAllocString( L"moduleProviders" );
BSTR bstrAdd = SysAllocString( L"add" );
BSTR bstrModulesSectionName = SysAllocString( L"modules" );
if( !bstrCommitPath ||
!bstrModuleProvidersName ||
!bstrAdd ||
!bstrModulesSectionName )
{
hr = E_OUTOFMEMORY;
DBGERROR_HR(hr);
goto exit;
}
hr = CoCreateInstance( __uuidof( AppHostWritableAdminManager ),
NULL,
CLSCTX_INPROC_SERVER,
__uuidof( IAppHostWritableAdminManager ),
(VOID **)&pAdminMgr );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
hr = InitAdminMgrForAdminConfig( pAdminMgr,
bstrCommitPath );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
hr = pAdminMgr->GetAdminSection( bstrModuleProvidersName,
bstrCommitPath,
&pProvidersSection );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
hr = pProvidersSection->get_Collection( &pProvidersCollection );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
hr = FindElementInCollection(
pProvidersCollection,
L"name",
szModuleName,
FIND_ELEMENT_CASE_SENSITIVE,
&dwIndex);
if (FAILED(hr))
{
DBGERROR_HR(hr);
goto exit;
}
if (hr == S_OK)
{
VARIANT vtIndex;
vtIndex.vt = VT_UI4;
vtIndex.ulVal = dwIndex;
hr = pProvidersCollection->get_Item(
vtIndex,
&pNewModuleElement);
if (FAILED(hr))
{
DBGERROR_HR(hr);
goto exit;
}
}
else
{
hr = pProvidersCollection->CreateNewElement( bstrAdd,
&pNewModuleElement );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
fAddElement = TRUE;
}
hr = VariantAssign( &varValue, szModuleName );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
hr = SetElementProperty( pNewModuleElement,
L"name",
&varValue );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
hr = VariantAssign( &varValue, szModuleTypeInfo );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
hr = SetElementProperty( pNewModuleElement,
L"type",
&varValue );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
if (fAddElement)
{
cIndex = -1;
if (szPrependToList && *szPrependToList)
{
cIndex = 0;
}
hr = pProvidersCollection->AddElement( pNewModuleElement,
cIndex );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
}
if( szRegisterInModulesSection && *szRegisterInModulesSection )
{
// register global <modules> section
hr = pAdminMgr->GetAdminSection( bstrModulesSectionName,
bstrCommitPath,
&pModulesSection );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
hr = pModulesSection->get_Collection( &pModulesCollection );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
hr = pModulesCollection->CreateNewElement( bstrAdd,
&pModulesCollectionElement );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
hr = VariantAssign( &varValue, szModuleName );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
hr = SetElementProperty( pModulesCollectionElement,
L"name",
&varValue );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
cIndex = -1;
if (szPrependToList && *szPrependToList)
{
cIndex = 0;
}
hr = pModulesCollection->AddElement( pModulesCollectionElement,
cIndex );
if (hr == HRESULT_FROM_WIN32(ERROR_ALREADY_EXISTS))
{
hr = S_OK;
}
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
}
hr = pAdminMgr->CommitChanges();
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
exit:
SysFreeString( bstrCommitPath );
SysFreeString( bstrModuleProvidersName );
SysFreeString( bstrAdd );
SysFreeString( bstrModulesSectionName );
VariantClear( &varValue );
return hr;
}
HRESULT
UnRegisterUIModule(
IN CONST WCHAR * szModuleName,
IN CONST WCHAR * szModuleTypeInfo
)
{
HRESULT hr = NOERROR;
CComPtr<IAppHostWritableAdminManager> pAdminMgr;
CComPtr<IAppHostElement> pProvidersSection;
CComPtr<IAppHostElementCollection> pProvidersCollection;
CComPtr<IAppHostElement> pProviderElement;
CComPtr<IAppHostElement> pModulesSection;
CComPtr<IAppHostElementCollection> pModulesCollection;
BSTR bstrCommitPath = SysAllocString( L"MACHINE/WEBROOT" );
BSTR bstrModuleProvidersName = SysAllocString( L"moduleProviders" );
BSTR bstrModulesSectionName = SysAllocString( L"modules" );
BSTR bstrType = NULL;
DWORD dwIndex;
if( !bstrCommitPath ||
!bstrModuleProvidersName ||
!bstrModulesSectionName )
{
hr = E_OUTOFMEMORY;
DBGERROR_HR(hr);
goto exit;
}
hr = CoCreateInstance( __uuidof( AppHostWritableAdminManager ),
NULL,
CLSCTX_INPROC_SERVER,
__uuidof( IAppHostWritableAdminManager ),
(VOID **)&pAdminMgr );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
hr = InitAdminMgrForAdminConfig( pAdminMgr, bstrCommitPath );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
hr = pAdminMgr->GetAdminSection( bstrModuleProvidersName,
bstrCommitPath,
&pProvidersSection );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
hr = pProvidersSection->get_Collection( &pProvidersCollection );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
BOOL fProvidersDeleted = FALSE;
hr = FindElementInCollection(
pProvidersCollection,
L"name",
szModuleName,
FIND_ELEMENT_CASE_SENSITIVE,
&dwIndex);
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
if (hr == S_OK)
{
VARIANT vtIndex;
vtIndex.vt = VT_UI4;
vtIndex.ulVal = dwIndex;
hr = pProvidersCollection->get_Item(
vtIndex,
&pProviderElement);
if (FAILED(hr))
{
DBGERROR_HR(hr);
goto exit;
}
hr = GetElementStringProperty(
pProviderElement,
L"type",
&bstrType);
if (FAILED(hr))
{
DBGERROR_HR(hr);
goto exit;
}
if (wcscmp(bstrType, szModuleTypeInfo) == 0)
{
hr = pProvidersCollection->DeleteElement(vtIndex);
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
fProvidersDeleted = TRUE;
}
else
{
goto exit;
}
}
// now remove from global <modules> section if present
hr = pAdminMgr->GetAdminSection( bstrModulesSectionName,
bstrCommitPath,
&pModulesSection );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
hr = pModulesSection->get_Collection( &pModulesCollection );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
BOOL fModulesDeleted = FALSE;
hr = DeleteElementFromCollection( pModulesCollection,
L"name",
szModuleName,
FIND_ELEMENT_CASE_SENSITIVE,
&fModulesDeleted );
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
if( fProvidersDeleted || fModulesDeleted )
{
hr = pAdminMgr->CommitChanges();
if( FAILED(hr) )
{
DBGERROR_HR(hr);
goto exit;
}
}
exit:
SysFreeString( bstrCommitPath );
SysFreeString( bstrModuleProvidersName );
SysFreeString( bstrModulesSectionName );
SysFreeString( bstrType );
return hr;
}
| 8,538 |
2,721 | /*
* ******************************************************************************
* Copyright (c) 2013-2014 <NAME>.
*
* 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 it.gmariotti.cardslib.library.recyclerview.view;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.LayoutRes;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import it.gmariotti.cardslib.library.recyclerview.R;
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.recyclerview.internal.BaseRecyclerViewAdapter;
import it.gmariotti.cardslib.library.view.base.CardViewWrapper;
/**
*
* RecyclerView for Cards.
* It uses a {@link BaseRecyclerViewAdapter} to populate items.
* </p>
* Usage:
* <pre><code>
* <it.gmariotti.cardslib.library.recyclerview.view.CardRecyclerView
* android:layout_width="match_parent"
* android:layout_height="match_parent"
* android:id="@+id/listId"
* card:list_card_layout_resourceID="@layout/list_card_thumbnail_layout" /> *
* </code></pre>
* It provides a default layout id for each row @layout/list_card_layout
* Use can easily customize it using card:list_card_layout_resourceID attr in your xml layout.
* </p>
*
* @author <NAME> (<EMAIL>)
*/
public class CardRecyclerView extends RecyclerView implements CardViewWrapper.OnExpandListAnimatorListener {
/**
* Card Adapter
*/
protected BaseRecyclerViewAdapter mAdapter;
//--------------------------------------------------------------------------
// Custom Attrs
//--------------------------------------------------------------------------
/**
* Default layout to apply to card
*/
protected @LayoutRes
int list_card_layout_resourceID = R.layout.list_card_layout;
/**
* Layouts to apply to card
*/
protected @LayoutRes int[] list_card_layout_resourceIDs;
//--------------------------------------------------------------------------
// Constructors
//--------------------------------------------------------------------------
public CardRecyclerView(Context context) {
super(context);
init(context, null, 0);
}
public CardRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public CardRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
//--------------------------------------------------------------------------
// Init
//--------------------------------------------------------------------------
/**
* Initialize
*
* @param attrs
* @param defStyle
*/
protected void init(Context context,AttributeSet attrs, int defStyle){
//Init attrs
initAttrs(context,attrs,defStyle);
}
/**
* Init custom attrs.
*
* @param attrs
* @param defStyle
*/
protected void initAttrs(Context context,AttributeSet attrs, int defStyle) {
list_card_layout_resourceID = R.layout.list_card_layout;
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs, R.styleable.card_options, defStyle, defStyle);
try {
list_card_layout_resourceID = a.getResourceId(R.styleable.card_options_list_card_layout_resourceID, this.list_card_layout_resourceID);
int arrayIds = a.getResourceId(R.styleable.card_options_list_card_layout_resourceIDs, 0);
if (arrayIds > 0 ) {
TypedArray layouts = context.getResources().obtainTypedArray(arrayIds);
if (layouts != null){
list_card_layout_resourceIDs = new int[layouts.length()];
for (int i=0; i<layouts.length();i++){
list_card_layout_resourceIDs[i] = layouts.getResourceId(i, R.layout.list_card_layout);
}
}
layouts.recycle();
}
} finally {
a.recycle();
}
}
//--------------------------------------------------------------------------
// Adapter
//--------------------------------------------------------------------------
/**
* Set {@link it.gmariotti.cardslib.library.recyclerview.internal.BaseRecyclerViewAdapter} and layout used by items in RecyclerView
*
* @param adapter {@link it.gmariotti.cardslib.library.recyclerview.internal.BaseRecyclerViewAdapter}
*/
public void setAdapter(BaseRecyclerViewAdapter adapter) {
super.setAdapter(adapter);
//Set Layout used by items
adapter.setRowLayoutId(list_card_layout_resourceID);
adapter.setRowLayoutIds(list_card_layout_resourceIDs);
adapter.setCardRecyclerView(this);
mAdapter=adapter;
setRecyclerListener(new RecyclerView.RecyclerListener() {
@Override
public void onViewRecycled(RecyclerView.ViewHolder viewHolder) {
if (viewHolder instanceof BaseRecyclerViewAdapter.CardViewHolder){
((BaseRecyclerViewAdapter.CardViewHolder)viewHolder).recycled = true;
}
}
});
}
//--------------------------------------------------------------------------
// Expand and Collapse animator
//--------------------------------------------------------------------------
@Override
public void onExpandStart(CardViewWrapper viewCard,View expandingLayout) {
ExpandCollapseHelper.animateExpanding(expandingLayout,viewCard,this);
}
@Override
public void onCollapseStart(CardViewWrapper viewCard,View expandingLayout) {
ExpandCollapseHelper.animateCollapsing(expandingLayout,viewCard,this);
}
/**
* Helper to animate collapse and expand animation
*/
private static class ExpandCollapseHelper {
/**
* This method expandes the view that was clicked.
*
* @param expandingLayout layout to expand
* @param cardView cardView
* @param recyclerView recyclerView
*/
public static void animateCollapsing(final View expandingLayout, final CardViewWrapper cardView,final RecyclerView recyclerView) {
int origHeight = expandingLayout.getHeight();
ValueAnimator animator = createHeightAnimator(expandingLayout, origHeight, 0);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animator) {
expandingLayout.setVisibility(View.GONE);
cardView.setExpanded(false);//card.setExpanded(true);
notifyAdapter(recyclerView,recyclerView.getLayoutManager().getPosition((View)cardView));
Card card = cardView.getCard();
if (card.getOnCollapseAnimatorEndListener()!=null)
card.getOnCollapseAnimatorEndListener().onCollapseEnd(card);
}
});
animator.start();
}
/**
* This method collapse the view that was clicked.
*
* @param expandingLayout layout to collapse
* @param cardView cardView
* @param recyclerView recyclerView
*/
public static void animateExpanding(final View expandingLayout, final CardViewWrapper cardView,final RecyclerView recyclerView) {
/* Update the layout so the extra content becomes visible.*/
expandingLayout.setVisibility(View.VISIBLE);
View parent = (View) expandingLayout.getParent();
final int widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth() - parent.getPaddingLeft() - parent.getPaddingRight(), View.MeasureSpec.AT_MOST);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
expandingLayout.measure(widthSpec, heightSpec);
ValueAnimator animator = createHeightAnimator(expandingLayout, 0, expandingLayout.getMeasuredHeight());
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
final int listViewHeight = recyclerView.getHeight();
final int listViewBottomPadding = recyclerView.getPaddingBottom();
final View v = findDirectChild(expandingLayout, recyclerView);
@Override
public void onAnimationUpdate(final ValueAnimator valueAnimator) {
if (recyclerView.getLayoutManager().canScrollVertically()) {
final int bottom = v.getBottom();
if (bottom > listViewHeight) {
final int top = v.getTop();
if (top > 0) {
//recyclerView.scrollBy(0,Math.min(bottom - listViewHeight + listViewBottomPadding, top));
recyclerView.smoothScrollBy(0,Math.min(bottom - listViewHeight + listViewBottomPadding + 4, top));
}
}
}
}
});
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
cardView.setExpanded(true);//card.setExpanded(true);
notifyAdapter(recyclerView,recyclerView.getLayoutManager().getPosition((View)cardView));
Card card = cardView.getCard();
if (card.getOnExpandAnimatorEndListener()!=null)
card.getOnExpandAnimatorEndListener().onExpandEnd(card);
}
});
animator.start();
}
private static View findDirectChild(final View view, final RecyclerView recyclerView) {
View result = view;
View parent = (View) result.getParent();
while (parent != recyclerView) {
result = parent;
parent = (View) result.getParent();
}
return result;
}
public static ValueAnimator createHeightAnimator(final View view, final int start, final int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(final ValueAnimator valueAnimator) {
int value = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.height = value;
view.setLayoutParams(layoutParams);
}
});
return animator;
}
/**
* This method notifies the adapter after setting expand value inside cards
*
* @param recyclerView
*/
public static void notifyAdapter(RecyclerView recyclerView,int position){
if (recyclerView instanceof CardRecyclerView){
CardRecyclerView cardRecyclerView = (CardRecyclerView) recyclerView;
if (cardRecyclerView.mAdapter!=null){
cardRecyclerView.mAdapter.notifyItemChanged(position);
}
}
}
}
}
| 4,978 |
1,738 | <gh_stars>1000+
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Component/Component.h>
#include <LmbrCentral/Animation/MannequinAsset.h>
#include <LmbrCentral/Rendering/MeshComponentBus.h>
class IActionController;
namespace LmbrCentral
{
/* The mannequin scope component allows for associating a runtime character instance with a given scope
* context, along with an adb file. This component complements the Mannequin component but it cannot
* function without the same. The mannequin component on the other hand, could use other means to set scope
* contexts thereby eliminating its dependence on the scope context component.
*/
class MannequinScopeComponent
: public AZ::Component
, private MeshComponentNotificationBus::Handler
{
public:
friend class EditorMannequinScopeComponent;
AZ_COMPONENT(MannequinScopeComponent, "{AB4FDB4A-D742-4EF8-B36E-9A1775FA6FA5}");
//////////////////////////////////////////////////////////////////////////
// AZ::Component interface implementation
void Activate() override;
void Deactivate() override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// MeshComponentNotificationBus implementation
void OnMeshCreated(const AZ::Data::Asset<AZ::Data::AssetData>& asset) override;
void OnMeshDestroyed() override;
//////////////////////////////////////////////////////////////////////////
protected:
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("MannequinScopeService", 0x7adf3115));
}
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
required.push_back(AZ_CRC("AnimationService", 0x553f5760));
required.push_back(AZ_CRC("MannequinService", 0x424b0eea));
}
static void Reflect(AZ::ReflectContext* context);
private:
/**
* \brief Resets / Sets up this component to the indicated mannequin scope
*/
void ResetMannequinScopeContext();
/**
* \brief Clears any mannequin scope context settings for this component
*/
void ClearMannequinScopeContext();
//////////////////////////////////////////////////////////////////////////
// Serialized Data
// Name of the scope context that this anim database is to be attached to
AZStd::string m_scopeContextName;
// The animation database file that is to be attached to this scope context
AzFramework::SimpleAssetReference<MannequinAnimationDatabaseAsset> m_animationDatabase;
// Entity Id for the target of this scope context setting
AZ::EntityId m_targetEntityId;
//////////////////////////////////////////////////////////////////////////
};
} // namespace LmbrCentral
| 1,114 |
721 | <filename>enderio-machines/src/main/java/crazypants/enderio/machines/machine/generator/lava/GuiLavaGenerator.java
package crazypants.enderio.machines.machine.generator.lava;
import java.awt.Rectangle;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.enderio.core.client.gui.widget.GhostSlot;
import com.enderio.core.client.gui.widget.GuiToolTip;
import com.enderio.core.client.render.RenderUtil;
import com.enderio.core.common.util.NNList;
import crazypants.enderio.base.lang.LangFluid;
import crazypants.enderio.base.lang.LangPower;
import crazypants.enderio.base.lang.LangTemperature;
import crazypants.enderio.base.machine.gui.GenericBar;
import crazypants.enderio.base.machine.gui.GuiCapMachineBase;
import crazypants.enderio.base.machine.gui.PowerBar;
import crazypants.enderio.machines.lang.Lang;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.player.InventoryPlayer;
import static crazypants.enderio.base.lang.Lang.GUI_GENERIC_EFFICIENCY;
import static crazypants.enderio.machines.lang.Lang.GUI_LAVAGEN_HEAT;
public class GuiLavaGenerator extends GuiCapMachineBase<TileLavaGenerator> {
private static final int POWERX = 12;
private static final int POWERY = 14;
private static final int POWER_HEIGHT = 42;
private static final @Nonnull Rectangle RECTANGLE_TANK = new Rectangle(70, 21, 16, 47);
private static final @Nonnull Rectangle RECTANGLE_HEAT = new Rectangle(91, 21, 16, 47);
public GuiLavaGenerator(@Nonnull InventoryPlayer playerInv, @Nonnull TileLavaGenerator te) {
super(te, new ContainerLavaGenerator<>(playerInv, te), "lava_generator");
addDrawingElement(new PowerBar(te.getEnergy(), this, POWERX + 4, POWERY, POWER_HEIGHT));
addToolTip(new GuiToolTip(RECTANGLE_TANK, "") {
@Override
protected void updateText() {
text.clear();
text.add(Lang.GUI_TANK_TANK_TANK_TANK.get());
text.add(LangFluid.MB(getTileEntity().tank));
}
});
addDrawingElement(new GenericBar(this, RECTANGLE_HEAT, -1, new GuiToolTip(RECTANGLE_HEAT, "") {
@Override
protected void updateText() {
text.clear();
text.add(GUI_LAVAGEN_HEAT.get());
text.add(LangTemperature.degK(getTileEntity().getHeatDisplayValue())); // #.# °C
text.add(GUI_GENERIC_EFFICIENCY.get((int) (getTileEntity().getHeatFactor() * 100))); // ##% efficiency
text.add(LangPower.RFt(getTileEntity().getPowerGenPerTick())); // # µI/t
}
}) {
@Override
protected float getLevel() {
return getTileEntity().getHeat();
}
@Override
protected int getColor() {
return getLevel() < .5 ? 0xB02ECB19 : getLevel() < .75 ? 0xB0FFD21F : 0xB0F21818;
}
});
}
@Override
protected boolean showRecipeButton() {
return false; // TODO JEI recipe
}
@Override
public void initGui() {
super.initGui();
final NNList<GhostSlot> ghostSlots = getGhostSlotHandler().getGhostSlots();
ghostSlots.clear();
((ContainerLavaGenerator<?>) inventorySlots).createGhostSlots(ghostSlots);
}
@Override
@Nullable
public Object getIngredientUnderMouse(int mouseX, int mouseY) {
if (RECTANGLE_TANK.contains(mouseX, mouseY)) {
return getTileEntity().tank.getFluid();
}
return super.getIngredientUnderMouse(mouseX, mouseY);
}
@Override
protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) {
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
bindGuiTexture();
int sx = (width - xSize) / 2;
int sy = (height - ySize) / 2;
drawTexturedModalRect(sx, sy, 0, 0, xSize, ySize);
super.drawGuiContainerBackgroundLayer(par1, par2, par3);
RenderUtil.renderGuiTank(getTileEntity().tank, guiLeft + RECTANGLE_TANK.x, guiTop + RECTANGLE_TANK.y, zLevel, RECTANGLE_TANK.width, RECTANGLE_TANK.height);
}
}
| 1,513 |
11,664 | <filename>packages/translator-default/test/fixtures/custom-element-tag/components/hello/marko-tag.json<gh_stars>1000+
{
"html": true,
"htmlType": "custom-element",
"parseOptions": {
"import": "./init.js"
}
}
| 85 |
1,570 | // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "Config.hpp"
#include "Common/Thread.hpp"
#include "Common/Timer.hpp"
namespace sw
{
Profiler profiler;
Profiler::Profiler()
{
reset();
}
void Profiler::reset()
{
framesSec = 0;
framesTotal = 0;
FPS = 0;
#if PERF_PROFILE
for(int i = 0; i < PERF_TIMERS; i++)
{
cycles[i] = 0;
}
ropOperations = 0;
ropOperationsTotal = 0;
ropOperationsFrame = 0;
texOperations = 0;
texOperationsTotal = 0;
texOperationsFrame = 0;
compressedTex = 0;
compressedTexTotal = 0;
compressedTexFrame = 0;
#endif
}
void Profiler::nextFrame()
{
#if PERF_PROFILE
ropOperationsFrame = sw::atomicExchange(&ropOperations, 0);
texOperationsFrame = sw::atomicExchange(&texOperations, 0);
compressedTexFrame = sw::atomicExchange(&compressedTex, 0);
ropOperationsTotal += ropOperationsFrame;
texOperationsTotal += texOperationsFrame;
compressedTexTotal += compressedTexFrame;
#endif
static double fpsTime = sw::Timer::seconds();
double time = sw::Timer::seconds();
double delta = time - fpsTime;
framesSec++;
if(delta > 1.0)
{
FPS = framesSec / delta;
fpsTime = time;
framesTotal += framesSec;
framesSec = 0;
}
}
} | 653 |
739 | #!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
class ComboBoxEntryExample:
def __init__(self):
window = gtk.Window()
window.connect('destroy', lambda w: gtk.main_quit())
comboboxentry = gtk.combo_box_entry_new_text()
window.add(comboboxentry)
comboboxentry.append_text('Apple')
comboboxentry.append_text('Cherry')
comboboxentry.append_text('Blueberry')
comboboxentry.append_text('Grape')
comboboxentry.append_text('Peach')
comboboxentry.append_text('Raisin')
comboboxentry.child.connect('changed', self.changed_cb)
comboboxentry.set_active(0)
window.show_all()
return
def changed_cb(self, entry):
print 'I like', entry.get_text(), 'pie'
return
def main():
gtk.main()
return
if __name__ == "__main__":
bcb = ComboBoxEntryExample()
main()
| 412 |
2,201 | <gh_stars>1000+
// Copyright (C) 2021-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <stddef.h>
#include <algorithm>
#include <cmath>
#include <memory>
#include <string>
#include <vector>
#include <opencv2/core.hpp>
#include "face_reid.hpp"
#include "tracker.hpp"
namespace {
float ComputeReidDistance(const cv::Mat& descr1, const cv::Mat& descr2) {
float xy = static_cast<float>(descr1.dot(descr2));
float xx = static_cast<float>(descr1.dot(descr1));
float yy = static_cast<float>(descr2.dot(descr2));
float norm = sqrt(xx * yy) + 1e-6f;
return 1.0f - xy / norm;
}
} // namespace
const char EmbeddingsGallery::unknown_label[] = "Unknown";
const int EmbeddingsGallery::unknown_id = TrackedObject::UNKNOWN_LABEL_IDX;
std::vector<int> EmbeddingsGallery::GetIDsByEmbeddings(const std::vector<cv::Mat>& embeddings) const {
if (embeddings.empty() || idx_to_id.empty())
return std::vector<int>(embeddings.size(), unknown_id);
cv::Mat distances(static_cast<int>(embeddings.size()), static_cast<int>(idx_to_id.size()), CV_32F);
for (int i = 0; i < distances.rows; i++) {
int k = 0;
for (size_t j = 0; j < identities.size(); j++) {
for (const auto& reference_emb : identities[j].embeddings) {
distances.at<float>(i, k) = ComputeReidDistance(embeddings[i], reference_emb);
k++;
}
}
}
KuhnMunkres matcher(use_greedy_matcher);
auto matched_idx = matcher.Solve(distances);
std::vector<int> output_ids;
for (auto col_idx : matched_idx) {
if (distances.at<float>(output_ids.size(), col_idx) > reid_threshold)
output_ids.push_back(unknown_id);
else
output_ids.push_back(idx_to_id[col_idx]);
}
return output_ids;
}
std::string EmbeddingsGallery::GetLabelByID(int id) const {
if (id >= 0 && id < static_cast<int>(identities.size()))
return identities[id].label;
else
return unknown_label;
}
size_t EmbeddingsGallery::size() const {
return identities.size();
}
std::vector<std::string> EmbeddingsGallery::GetIDToLabelMap() const {
std::vector<std::string> map;
map.reserve(identities.size());
for (const auto& item : identities) {
map.emplace_back(item.label);
}
return map;
}
bool EmbeddingsGallery::LabelExists(const std::string& label) const {
return identities.end() != std::find_if(identities.begin(), identities.end(), [label](const GalleryObject& o) {
return o.label == label;
});
}
| 1,095 |
23,901 | # coding=utf-8
# Copyright 2021 The Google Research 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.
# Lint as: python3
"""Implements different squashing strategies before applying the Sinkhorn algorithm.
The main purpose of those functions is to map the numbers we wish to sort into
the [0, 1] segment using an increasing function, such as a logistic map.
This logistic map, when applied on the output of a neural network,
redistributes the activations into [0,1] in a smooth adaptative way, helping
the numerical stability of the Sinkhorn algorithm while maintaining a
well behaved back propagation.
In case of a logistic sigmoid, this map is exactly the CDF of a logistic
distribution. See https://en.wikipedia.org/wiki/Logistic_distribution for
details, in particular the variance of the distribution. In case of an atan
sigmoid, it is somewhat related to the CDF of a Cauchy
distribution and presents the advantage to have better behaved gradients.
In a such a logistic map, the points lying in the linear part of the map will
be well spread out on the [0, 1] segment, which will make them easier to sort.
Therefore, depending on which part of the distribution is of interest, we might
want to focus on one part of another, hence leading to different translations
before applying a squashing function.
"""
import math
import gin
import tensorflow.compat.v2 as tf
@gin.configurable
def reduce_softmax(x, tau, axis = -1):
"""Computes the softmax of a tensor along a given axis.
Args:
x: (tf.Tensor<float>) the input tensor of any shape.
tau: (float) the value of the inverse softmax temperature.
When tau is very big the obtained value is close to the maximum, when 0
it coincides with the mean and when very negative it converges to the
minimum.
axis: (int) the axis along which we want to compute the softmax.
Returns:
a tf.Tensor<float> that has the same shape than the input tensor except for
the reduction axis which is gone.
"""
return tf.math.reduce_sum(tf.nn.softmax(x * tau, axis=axis) * x, axis=axis)
@gin.configurable
def whiten(x, axis = -1, min_std=1e-10):
"""Makes the input tensor zero mean and unit variance along the axis.
Args:
x: (tf.Tensor<float>) of any shape to be whitened.
axis: (int) the axis along which to compute the statistics.
min_std: (float) a minimum value of the standard deviation along the axis to
prevent degenerated cases.
Returns:
A tf.Tensor<float> of the same shape as the input tensor.
"""
mu = tf.expand_dims(tf.math.reduce_mean(x, axis=axis), axis=axis)
min_std = 1e-6
sigma = tf.expand_dims(
tf.maximum(tf.math.reduce_std(x, axis=axis), min_std), axis=axis)
return (x - mu) / sigma
@gin.configurable
def soft_stretch(
x, axis = -1, extreme_tau = 1e12):
"""Softly rescales the values of `x` along the axis to the [0, 1] segment.
Args:
x: (tf.Tensor<float> of any shape) the input tensor to rescale the values of.
axis: (int) the axis along which we want to rescale.
extreme_tau: (float) the value of the inverse temperature to compute the
softmax and softmin. This must be big for the output values to
really lie in the [0, 1] segment.
Returns:
A tf.Tensor<float> of the same shape as the input.
"""
min_x = tf.expand_dims(
reduce_softmax(x, tau=-extreme_tau, axis=axis), axis=axis)
max_x = tf.expand_dims(
reduce_softmax(x, tau=extreme_tau, axis=axis), axis=axis)
return (x - min_x) / (max_x - min_x)
@gin.configurable
def group_rescale(
x,
is_logistic = True,
tau = 0.0,
stretch = False):
"""Applies a sigmoid map on standardized inputs.
By default, the inputs is centered, but it can be uncentered by playing with
the parameters `tau` and `uncenter_towards_max`.
Args:
x: Tensor<float>[batch, n]
is_logistic: (bool) uses either a logistic sigmoid or an arctan.
tau: (float or None) inverse temperature parameter that, if not None,
controls how much deviation we want from the mean. The bigger the closer to
the maximum and the more negative to the minimum
stretch: (bool) if True, stretches the values to the the full [0, 1] segment.
Returns:
A Tensor<float>[batch, n] after application of the sigmoid map.
"""
x = whiten(x, axis=1)
if is_logistic:
x /= math.sqrt(3.0) / math.pi
if tau != 0:
center = reduce_softmax(x, tau=tau, axis=1)
x = x - center[:, tf.newaxis]
squashing_fn = tf.math.sigmoid if is_logistic else tf.math.atan
squashed_x = squashing_fn(x)
if stretch:
return soft_stretch(squashed_x)
return squashed_x
| 1,652 |
9,491 | <reponame>divinity76/hhvm<gh_stars>1000+
#include "hphp/runtime/base/array-init.h"
#include "hphp/runtime/ext/icu/icu.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/base/tv-refcount.h"
#include "hphp/runtime/vm/vm-regs.h"
#include <unicode/uchar.h>
namespace HPHP { namespace Intl {
/////////////////////////////////////////////////////////////////////////////
static bool parseUChar32(const Variant& vcp, UChar32& cp) {
if (vcp.isInteger()) {
cp = vcp.toInt64();
} else if (vcp.isString()) {
String strval = vcp.toString();
auto cstr = strval.c_str();
auto cstr_len = strval.size();
int i = 0;
U8_NEXT(cstr, i, cstr_len, cp);
if (i != cstr_len) {
s_intl_error->setError(
U_ILLEGAL_ARGUMENT_ERROR,
"Passing a UTF-8 character for codepoint requires a string which is "
"exactly one UTF-8 codepoint long."
);
return false;
}
} else {
s_intl_error->setError(
U_ILLEGAL_ARGUMENT_ERROR,
"Invalid parameter for unicode point. "
"Must be either integer or UTF-8 sequence."
);
return false;
}
if ((cp < UCHAR_MIN_VALUE) || (cp > UCHAR_MAX_VALUE)) {
s_intl_error->setError(U_ILLEGAL_ARGUMENT_ERROR, "Codepoint out of range");
return false;
}
return true;
}
#define GETCP(arg, cp) \
UChar32 cp; if (!parseUChar32(arg, cp)) { return init_null(); }
#define GETCP_VOID(arg, cp) \
UChar32 cp; if (!parseUChar32(arg, cp)) { return; }
Variant HHVM_STATIC_METHOD(IntlChar, chr, const Variant& arg) {
GETCP(arg, cp);
/* We can use unsafe because we know the codepoint is in valid range
* and that 4 bytes is enough for any unicode point
*/
char buffer[5];
int buffer_len = 0;
U8_APPEND_UNSAFE(buffer, buffer_len, cp);
buffer[buffer_len] = 0;
return String(buffer, buffer_len, CopyString);
}
Variant HHVM_STATIC_METHOD(IntlChar, ord, const Variant& arg) {
GETCP(arg, cp);
return cp;
}
Variant HHVM_STATIC_METHOD(IntlChar, hasBinaryProperty,
const Variant& arg, int64_t prop) {
GETCP(arg, cp);
return (bool)u_hasBinaryProperty(cp, (UProperty)prop);
}
Variant HHVM_STATIC_METHOD(IntlChar, getIntPropertyValue,
const Variant& arg, int64_t prop) {
GETCP(arg, cp);
return u_getIntPropertyValue(cp, (UProperty)prop);
}
int64_t HHVM_STATIC_METHOD(IntlChar, getIntPropertyMinValue, int64_t prop) {
return u_getIntPropertyMinValue((UProperty)prop);
}
int64_t HHVM_STATIC_METHOD(IntlChar, getIntPropertyMaxValue, int64_t prop) {
return u_getIntPropertyMaxValue((UProperty)prop);
}
Variant HHVM_STATIC_METHOD(IntlChar, getNumericValue, const Variant& arg) {
GETCP(arg, cp);
return u_getNumericValue(cp);
}
static UBool enumCharType_callback(CallCtx* ctx,
UChar32 start, UChar32 limit,
UCharCategory type) {
TypedValue args[3];
args[0].m_type = args[1].m_type = args[2].m_type = KindOfInt64;
args[0].m_data.num = start;
args[1].m_data.num = limit;
args[2].m_data.num = type;
tvDecRefGen(
g_context->invokeFuncFew(*ctx, 3, args, RuntimeCoeffects::fixme())
);
return true;
}
void HHVM_STATIC_METHOD(IntlChar, enumCharTypes, const Variant& callback) {
CallCtx ctx;
ctx.func = nullptr;
if (!callback.isNull()) {
vm_decode_function(callback, ctx);
}
if (!ctx.func) {
s_intl_error->setError(U_INTERNAL_PROGRAM_ERROR,
"enumCharTypes callback failed");
return;
}
u_enumCharTypes((UCharEnumTypeRange*)enumCharType_callback, &ctx);
}
Variant HHVM_STATIC_METHOD(IntlChar, getBlockCode, const Variant& arg) {
GETCP(arg, cp);
return ublock_getCode(cp);
}
Variant HHVM_STATIC_METHOD(IntlChar, charName,
const Variant& arg, int64_t choice) {
GETCP(arg, cp);
UErrorCode error = U_ZERO_ERROR;
int32_t buffer_len = u_charName(cp, (UCharNameChoice)choice,
nullptr, 0, &error);
String buffer(buffer_len, ReserveString);
error = U_ZERO_ERROR;
buffer_len = u_charName(cp, (UCharNameChoice)choice,
buffer.bufferSlice().data(), buffer_len + 1, &error);
if (U_FAILURE(error)) {
s_intl_error->setError(error, "Failure getting character name");
return init_null();
}
buffer.setSize(buffer_len);
return buffer;
}
Variant HHVM_STATIC_METHOD(IntlChar, charFromName,
const String& name, int64_t choice) {
UErrorCode error = U_ZERO_ERROR;
auto ret = u_charFromName((UCharNameChoice)choice, name.c_str(), &error);
if (U_FAILURE(error)) {
s_intl_error->setError(error);
return init_null();
}
return ret;
}
static UBool enumCharNames_callback(CallCtx *ctx,
UChar32 code, UCharNameChoice nameChoice,
const char *name, int32_t length) {
TypedValue args[3];
args[0].m_type = args[1].m_type = KindOfInt64;
args[0].m_data.num = code;
args[1].m_data.num = nameChoice;
Variant charName = String(name, length, CopyString);
tvCopy(*charName.asTypedValue(), args[2]);
tvDecRefGen(
g_context->invokeFuncFew(*ctx, 3, args, RuntimeCoeffects::fixme())
);
return true;
}
void HHVM_STATIC_METHOD(IntlChar, enumCharNames,
const Variant& vStart, const Variant& vLimit,
const Variant& callback, int64_t choice) {
GETCP_VOID(vStart, start);
GETCP_VOID(vLimit, limit);
CallCtx ctx;
ctx.func = nullptr;
if (!callback.isNull()) {
vm_decode_function(callback, ctx);
}
if (!ctx.func) {
s_intl_error->setError(U_INTERNAL_PROGRAM_ERROR,
"enumCharNames callback failed");
return;
}
UErrorCode error = U_ZERO_ERROR;
u_enumCharNames(start, limit, (UEnumCharNamesFn*)enumCharNames_callback, &ctx,
(UCharNameChoice)choice, &error);
if (U_FAILURE(error)) {
s_intl_error->setError(error);
}
}
Variant HHVM_STATIC_METHOD(IntlChar, getPropertyName,
int64_t prop, int64_t choice) {
auto ret = u_getPropertyName((UProperty)prop, (UPropertyNameChoice)choice);
if (ret) {
return String(ret, CopyString);
} else {
s_intl_error->setError(U_ILLEGAL_ARGUMENT_ERROR,
"Failed to get property name");
return false;
}
}
int64_t HHVM_STATIC_METHOD(IntlChar, getPropertyEnum, const String& alias) {
return u_getPropertyEnum(alias.c_str());
}
Variant HHVM_STATIC_METHOD(IntlChar, getPropertyValueName,
int64_t prop, int64_t value, int64_t choice) {
auto ret = u_getPropertyValueName((UProperty)prop, value,
(UPropertyNameChoice)choice);
if (ret) {
return String(ret, CopyString);
} else {
s_intl_error->setError(U_ILLEGAL_ARGUMENT_ERROR,
"Failed to get property value name");
return false;
}
}
int64_t HHVM_STATIC_METHOD(IntlChar, getPropertyValueEnum,
int64_t prop, const String& name) {
return u_getPropertyValueEnum((UProperty)prop, name.c_str());
}
Variant HHVM_STATIC_METHOD(IntlChar, foldCase,
const Variant& arg, int64_t options) {
GETCP(arg, cp);
auto ret = u_foldCase(cp, options);
if (arg.isString()) {
char buffer[5];
int buffer_len = 0;
U8_APPEND_UNSAFE(buffer, buffer_len, ret);
return String(buffer, buffer_len, CopyString);
} else {
return ret;
}
}
Variant HHVM_STATIC_METHOD(IntlChar, digit, const Variant& arg, int64_t radix) {
GETCP(arg, cp);
auto ret = u_digit(cp, radix);
if (ret < 0) {
s_intl_error->setError(U_ILLEGAL_ARGUMENT_ERROR, "Invalid digit");
return false;
}
return ret;
}
int64_t HHVM_STATIC_METHOD(IntlChar, forDigit, int64_t digit, int64_t radix) {
return u_forDigit(digit, radix);
}
Variant HHVM_STATIC_METHOD(IntlChar, charAge, const Variant& arg) {
GETCP(arg, cp);
UVersionInfo version;
u_charAge(cp, version);
Array ret = Array::CreateVec();
for(int i = 0; i < U_MAX_VERSION_LENGTH; ++i) {
ret.append(version[i]);
}
return ret;
}
Array HHVM_STATIC_METHOD(IntlChar, getUnicodeVersion) {
UVersionInfo version;
u_getUnicodeVersion(version);
VecInit ret(U_MAX_VERSION_LENGTH);
for(int i = 0; i < U_MAX_VERSION_LENGTH; ++i) {
ret.append(version[i]);
}
return ret.toArray();
}
Variant HHVM_STATIC_METHOD(IntlChar, getFC_NFKC_Closure, const Variant& arg) {
GETCP(arg, cp);
UErrorCode error = U_ZERO_ERROR;
auto closure_len = u_getFC_NFKC_Closure(cp, nullptr, 0, &error);
if (closure_len == 0) {
return empty_string();
}
icu::UnicodeString closure;
auto out = closure.getBuffer(closure_len + 1);
error = U_ZERO_ERROR;
closure_len = u_getFC_NFKC_Closure(cp, out, closure_len + 1, &error);
if (U_FAILURE(error)) {
s_intl_error->setError(error, "Failed getting closure");
return false;
}
closure.releaseBuffer(closure_len);
error = U_ZERO_ERROR;
String ret(u8(closure, error));
if (U_FAILURE(error)) {
s_intl_error->setError(error, "Failed converting output to UTF8");
return false;
}
return ret;
}
/* These four methods all have the same(ish) signature,
* but don't fit nearly into a template, so I went hacky...
*/
#define IC_INT_METHOD_CHAR(name) \
Variant HHVM_STATIC_METHOD(IntlChar, name, const Variant& arg) { \
GETCP(arg, cp); \
return (int64_t)u_##name(cp); \
}
IC_INT_METHOD_CHAR(charDirection)
IC_INT_METHOD_CHAR(charType)
IC_INT_METHOD_CHAR(getCombiningClass)
IC_INT_METHOD_CHAR(charDigitValue)
#undef IC_INT_METHOD_CHAR
/* All methods which take one UChar32 argument and return bool */
template <UBool (*T)(UChar32)>
Variant uchar_method(const Class* /*self_*/, const Variant& arg) {
GETCP(arg, cp);
return (bool)T(cp);
}
/* All methods which take one UChar32 argument and return same */
template <UChar32 (*T)(UChar32)>
Variant uchar_method(const Class* /*self_*/, const Variant& arg) {
GETCP(arg, cp);
auto ret = T(cp);
if (arg.isString()) {
String buf(5, ReserveString);
auto s = buf.bufferSlice().data();
int s_len = 0;
U8_APPEND_UNSAFE(s, s_len, ret);
s[s_len] = 0;
buf.setSize(s_len);
return buf;
} else {
return ret;
}
}
const StaticString s_IntlChar("IntlChar");
void IntlExtension::initUChar() {
HHVM_RCC_STR(IntlChar, UNICODE_VERSION, U_UNICODE_VERSION);
HHVM_RCC_INT(IntlChar, CODEPOINT_MIN, UCHAR_MIN_VALUE);
HHVM_RCC_INT(IntlChar, CODEPOINT_MAX, UCHAR_MAX_VALUE);
HHVM_RCC_INT(IntlChar, FOLD_CASE_DEFAULT, U_FOLD_CASE_DEFAULT);
HHVM_RCC_INT(IntlChar, FOLD_CASE_EXCLUDE_SPECIAL_I,
U_FOLD_CASE_EXCLUDE_SPECIAL_I);
HHVM_RCC_DBL(IntlChar, NO_NUMERIC_VALUE, U_NO_NUMERIC_VALUE);
/* All enums used by the uchar APIs. There are a LOT of them,
* so they're separated out into include files,
* leaving this source file for actual implementation.
*
* Note that these includes are shared between PHP and HHVM
*/
#define IC_CONSTL(name, val) HHVM_RCC_INT(IntlChar, name, val);
#define UPROPERTY(name) IC_CONSTL(PROPERTY_##name, UCHAR_##name)
#define UCHARCATEGORY(name) IC_CONSTL(CHAR_CATEGORY_##name, U_##name)
#define UCHARDIRECTION(name) IC_CONSTL(CHAR_DIRECTION_##name, U_##name)
#define UBLOCKCODE(name) IC_CONSTL(BLOCK_CODE_##name, UBLOCK_##name)
#define UOTHER(name) IC_CONSTL(name, U_##name)
#include "hphp/runtime/ext/icu/uproperty-enum.h"
#include "hphp/runtime/ext/icu/ucharcategory-enum.h"
#include "hphp/runtime/ext/icu/uchardirection-enum.h"
#include "hphp/runtime/ext/icu/ublockcode-enum.h"
/* Smaller, self-destribing enums */
#include "hphp/runtime/ext/icu/uother-enum.h"
#undef UPROPERTY
#undef UCHARCATEGORY
#undef UCHARDIRECTION
#undef UBLOCKCODE
#undef UOTHER
#undef IC_CONSTL
// Methods returning bool/UChar32 and taking a single UChar32 argument
#define UCHAR_ME(name) \
HHVM_NAMED_STATIC_ME(IntlChar, name, uchar_method<u_##name>)
UCHAR_ME(isUAlphabetic);
UCHAR_ME(isULowercase);
UCHAR_ME(isUUppercase);
UCHAR_ME(isUWhiteSpace);
UCHAR_ME(islower);
UCHAR_ME(isupper);
UCHAR_ME(istitle);
UCHAR_ME(isdigit);
UCHAR_ME(isalpha);
UCHAR_ME(isalnum);
UCHAR_ME(isxdigit);
UCHAR_ME(ispunct);
UCHAR_ME(isgraph);
UCHAR_ME(isblank);
UCHAR_ME(isdefined);
UCHAR_ME(isspace);
UCHAR_ME(isJavaSpaceChar);
UCHAR_ME(isWhitespace);
UCHAR_ME(iscntrl);
UCHAR_ME(isISOControl);
UCHAR_ME(isprint);
UCHAR_ME(isbase);
UCHAR_ME(isMirrored);
UCHAR_ME(isIDStart);
UCHAR_ME(isIDPart);
UCHAR_ME(isIDIgnorable);
UCHAR_ME(isJavaIDStart);
UCHAR_ME(isJavaIDPart);
UCHAR_ME(charMirror);
UCHAR_ME(tolower);
UCHAR_ME(toupper);
UCHAR_ME(totitle);
#if U_ICU_VERSION_MAJOR_NUM >= 52
UCHAR_ME(getBidiPairedBracket);
#endif /* ICU >= 52 */
#undef UCHAR_ME
// Methods with unique signatures
#define ICS_ME(name) HHVM_STATIC_ME(IntlChar, name)
ICS_ME(chr);
ICS_ME(ord);
ICS_ME(hasBinaryProperty);
ICS_ME(getIntPropertyValue);
ICS_ME(getIntPropertyMinValue);
ICS_ME(getIntPropertyMaxValue);
ICS_ME(getNumericValue);
ICS_ME(enumCharTypes);
ICS_ME(getBlockCode);
ICS_ME(getBlockCode);
ICS_ME(charName);
ICS_ME(charFromName);
ICS_ME(enumCharNames);
ICS_ME(getPropertyName);
ICS_ME(getPropertyEnum);
ICS_ME(getPropertyValueName);
ICS_ME(getPropertyValueEnum);
ICS_ME(foldCase);
ICS_ME(digit);
ICS_ME(forDigit);
ICS_ME(charAge);
ICS_ME(getUnicodeVersion);
ICS_ME(getFC_NFKC_Closure);
ICS_ME(charDirection);
ICS_ME(charType);
ICS_ME(getCombiningClass);
ICS_ME(charDigitValue);
#undef ICS_ME
loadSystemlib("icu_uchar");
}
/////////////////////////////////////////////////////////////////////////////
}} // namespace HPHP::Intl
| 5,947 |
1,175 | #ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "SwiftyOnboard.h"
FOUNDATION_EXPORT double SwiftyOnboardVersionNumber;
FOUNDATION_EXPORT const unsigned char SwiftyOnboardVersionString[];
| 127 |
592 | /*
* Copyright 2016 LinkedIn Corp.
*
* 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.linkedin.gradle.python.extension;
import org.gradle.api.GradleException;
import org.gradle.api.Project;
import org.gradle.process.ExecResult;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Collections;
public class PythonVersionParser {
private PythonVersionParser() {
// noop
}
public static PythonVersion parsePythonVersion(final Project project, final File pythonInterpreter) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ExecResult execResult = project.exec(execSpec -> {
execSpec.setExecutable(pythonInterpreter.getAbsolutePath());
execSpec.setArgs(Collections.singletonList("--version"));
execSpec.setStandardOutput(outputStream);
execSpec.setErrorOutput(outputStream);
execSpec.setIgnoreExitValue(true);
});
String output = outputStream.toString();
if (execResult.getExitValue() != 0) {
throw new GradleException(output);
}
String versionString = output.trim().split(" ")[1];
return new PythonVersion(versionString);
}
}
| 581 |
982 | #ifndef __win_sys_time_h__
#define __win_sys_time_h__
#define clock_gettime(x, data) ((timespec_get(data, TIME_UTC) != 0) ? 0 : 1)
#endif | 62 |
12,718 | <filename>lib/libc/mingw/secapi/_mktemp_s.c
#include <windows.h>
#include <malloc.h>
#include <errno.h>
#include <msvcrt.h>
#include <io.h>
static errno_t __cdecl _int_mktemp_s (char *, size_t);
static errno_t __cdecl _stub (char *, size_t);
errno_t __cdecl (*__MINGW_IMP_SYMBOL(_mktemp_s))(char *, size_t) =
_stub;
static errno_t __cdecl
_stub (char *d, size_t dn)
{
errno_t __cdecl (*f)(char *, size_t) = __MINGW_IMP_SYMBOL(_mktemp_s);
if (f == _stub)
{
f = (errno_t __cdecl (*)(char *, size_t))
GetProcAddress (__mingw_get_msvcrt_handle (), "_mktemp_s");
if (!f)
f = _int_mktemp_s;
__MINGW_IMP_SYMBOL(_mktemp_s) = f;
}
return (*f)(d, dn);
}
errno_t __cdecl
_mktemp_s (char *d, size_t dn)
{
return _stub (d, dn);
}
static errno_t __cdecl
_int_mktemp_s (char *d, size_t dn)
{
size_t sz;
if (!d || !dn)
{
_mktemp (NULL);
return EINVAL;
}
sz = strnlen (d, dn);
if (sz >= dn || sz < 6)
{
d[0] = 0;
_mktemp (NULL);
return EINVAL;
}
if (_mktemp (d) != NULL)
return 0;
return errno;
}
| 566 |
686 | <gh_stars>100-1000
/*
* base64 encoder/decoder
*
* Copyright 2005 by <NAME>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "windef.h"
#include "winerror.h"
#include "sspi.h"
#include "wine/debug.h"
WINE_DEFAULT_DEBUG_CHANNEL(ntlm);
static const char b64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
SECURITY_STATUS encodeBase64(PBYTE in_buf, int in_len, char* out_buf,
int max_len, int *out_len)
{
int div, i;
PBYTE d = in_buf;
int bytes = (in_len*8 + 5)/6, pad_bytes = (bytes % 4) ? 4 - (bytes % 4) : 0;
TRACE("bytes is %d, pad bytes is %d\n", bytes, pad_bytes);
*out_len = bytes + pad_bytes;
if(bytes + pad_bytes + 1 > max_len)
return SEC_E_BUFFER_TOO_SMALL;
/* Three bytes of input give 4 chars of output */
div = in_len / 3;
i = 0;
while(div > 0)
{
/* first char is the first 6 bits of the first byte*/
out_buf[i + 0] = b64[ ( d[0] >> 2) & 0x3f ];
/* second char is the last 2 bits of the first byte and the first 4
* bits of the second byte */
out_buf[i + 1] = b64[ ((d[0] << 4) & 0x30) | (d[1] >> 4 & 0x0f)];
/* third char is the last 4 bits of the second byte and the first 2
* bits of the third byte */
out_buf[i + 2] = b64[ ((d[1] << 2) & 0x3c) | (d[2] >> 6 & 0x03)];
/* fourth char is the remaining 6 bits of the third byte */
out_buf[i + 3] = b64[ d[2] & 0x3f];
i += 4;
d += 3;
div--;
}
switch(pad_bytes)
{
case 1:
/* first char is the first 6 bits of the first byte*/
out_buf[i + 0] = b64[ ( d[0] >> 2) & 0x3f ];
/* second char is the last 2 bits of the first byte and the first 4
* bits of the second byte */
out_buf[i + 1] = b64[ ((d[0] << 4) & 0x30) | (d[1] >> 4 & 0x0f)];
/* third char is the last 4 bits of the second byte padded with
* two zeroes */
out_buf[i + 2] = b64[ ((d[1] << 2) & 0x3c) ];
/* fourth char is a = to indicate one byte of padding */
out_buf[i + 3] = '=';
out_buf[i + 4] = 0;
break;
case 2:
/* first char is the first 6 bits of the first byte*/
out_buf[i + 0] = b64[ ( d[0] >> 2) & 0x3f ];
/* second char is the last 2 bits of the first byte padded with
* four zeroes*/
out_buf[i + 1] = b64[ ((d[0] << 4) & 0x30)];
/* third char is = to indicate padding */
out_buf[i + 2] = '=';
/* fourth char is = to indicate padding */
out_buf[i + 3] = '=';
out_buf[i + 4] = 0;
break;
default:
out_buf[i] = 0;
}
return SEC_E_OK;
}
static inline BYTE decode(char c)
{
if( c >= 'A' && c <= 'Z')
return c - 'A';
if( c >= 'a' && c <= 'z')
return c - 'a' + 26;
if( c >= '0' && c <= '9')
return c - '0' + 52;
if( c == '+')
return 62;
if( c == '/')
return 63;
else
return 64;
}
SECURITY_STATUS decodeBase64(char *in_buf, int in_len, PBYTE out_buf,
int max_len, int *out_len)
{
int len = in_len, i;
char *d = in_buf;
int ip0, ip1, ip2, ip3;
TRACE("in_len: %d\n", in_len);
if((in_len % 4) != 0)
return SEC_E_INVALID_TOKEN;
if(in_len > max_len)
return SEC_E_BUFFER_TOO_SMALL;
i = 0;
while(len > 4)
{
if((ip0 = decode(d[0])) > 63)
return SEC_E_INVALID_TOKEN;
if((ip1 = decode(d[1])) > 63)
return SEC_E_INVALID_TOKEN;
if((ip2 = decode(d[2])) > 63)
return SEC_E_INVALID_TOKEN;
if((ip3 = decode(d[3])) > 63)
return SEC_E_INVALID_TOKEN;
out_buf[i + 0] = (ip0 << 2) | (ip1 >> 4);
out_buf[i + 1] = (ip1 << 4) | (ip2 >> 2);
out_buf[i + 2] = (ip2 << 6) | ip3;
len -= 4;
i += 3;
d += 4;
}
if(d[2] == '=')
{
if((ip0 = decode(d[0])) > 63)
return SEC_E_INVALID_TOKEN;
if((ip1 = decode(d[1])) > 63)
return SEC_E_INVALID_TOKEN;
out_buf[i] = (ip0 << 2) | (ip1 >> 4);
i++;
}
else if(d[3] == '=')
{
if((ip0 = decode(d[0])) > 63)
return SEC_E_INVALID_TOKEN;
if((ip1 = decode(d[1])) > 63)
return SEC_E_INVALID_TOKEN;
if((ip2 = decode(d[2])) > 63)
return SEC_E_INVALID_TOKEN;
out_buf[i + 0] = (ip0 << 2) | (ip1 >> 4);
out_buf[i + 1] = (ip1 << 4) | (ip2 >> 2);
i += 2;
}
else
{
if((ip0 = decode(d[0])) > 63)
return SEC_E_INVALID_TOKEN;
if((ip1 = decode(d[1])) > 63)
return SEC_E_INVALID_TOKEN;
if((ip2 = decode(d[2])) > 63)
return SEC_E_INVALID_TOKEN;
if((ip3 = decode(d[3])) > 63)
return SEC_E_INVALID_TOKEN;
out_buf[i + 0] = (ip0 << 2) | (ip1 >> 4);
out_buf[i + 1] = (ip1 << 4) | (ip2 >> 2);
out_buf[i + 2] = (ip2 << 6) | ip3;
i += 3;
}
*out_len = i;
return SEC_E_OK;
}
| 3,003 |
705 | <gh_stars>100-1000
# Copyright 2019-2020 Spotify AB
#
# 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 os
from unittest import mock
import pytest
from google.api_core import exceptions as gapi_exceptions
from klio_core import utils
def test_set_global():
utils.set_global("set-a-value", "a-value")
actual = getattr(utils, "klio_global_state_set-a-value", None)
assert "a-value" == actual
delattr(utils, "klio_global_state_set-a-value")
def test_get_global():
setattr(utils, "klio_global_state_get-a-value", "a-value")
actual = utils.get_global("get-a-value")
assert "a-value" == actual
delattr(utils, "klio_global_state_get-a-value")
@pytest.mark.parametrize("exists", (True, False))
def test_delete_global(exists):
if exists:
setattr(utils, "klio_global_state_delete-a-value", "a-value")
utils.delete_global("delete-a-value")
actual = getattr(utils, "klio_global_state_delete-a-value", None)
assert not actual
@pytest.mark.parametrize(
"set_value,callable_init", ((True, False), (False, True), (False, False))
)
def test_get_or_initialize_global(set_value, callable_init, mocker):
if set_value:
setattr(utils, "klio_global_state_get-or-init-value", "a-value")
if callable_init:
initializer = mocker.Mock(return_value="a-value")
else:
initializer = "a-value"
actual = utils.get_or_initialize_global("get-or-init-value", initializer)
assert "a-value" == actual
if not isinstance(initializer, str):
initializer.assert_called_once_with()
delattr(utils, "klio_global_state_get-or-init-value")
@pytest.fixture
def mock_publisher(mocker, monkeypatch):
mock = mocker.Mock()
monkeypatch.setattr(utils.pubsub, "PublisherClient", mock)
return mock
def test_private_get_publisher(mock_publisher):
ret_publisher = utils._get_publisher("a-topic")
mock_publisher.assert_called_once_with()
mock_publisher.return_value.create_topic.assert_called_once_with("a-topic")
assert mock_publisher.return_value == ret_publisher
def test_private_get_publisher_topic_exists(mock_publisher):
client = mock_publisher.return_value
client.create_topic.side_effect = gapi_exceptions.AlreadyExists("foo")
ret_publisher = utils._get_publisher("a-topic")
mock_publisher.assert_called_once_with()
client.create_topic.assert_called_once_with("a-topic")
assert client == ret_publisher
def test_private_get_publisher_raises(mock_publisher):
client = mock_publisher.return_value
client.create_topic.side_effect = Exception("foo")
with pytest.raises(Exception, match="foo"):
utils._get_publisher("a-topic")
mock_publisher.assert_called_once_with()
client.create_topic.assert_called_once_with("a-topic")
@pytest.mark.parametrize("in_globals", (True, False))
def test_get_publisher(in_globals, mock_publisher):
client = mock_publisher.return_value
if in_globals:
setattr(utils, "klio_global_state_publisher_a-topic", client)
ret_publisher = utils.get_publisher("a-topic")
assert client == ret_publisher
delattr(utils, "klio_global_state_publisher_a-topic")
#########################
# Config Utils tests
#########################
@pytest.fixture
def patch_os_getcwd(monkeypatch, tmpdir):
test_dir = str(tmpdir.mkdir("testing"))
monkeypatch.setattr(os, "getcwd", lambda: test_dir)
return test_dir
def test_get_config_by_path(mocker, monkeypatch):
m_open = mocker.mock_open()
mock_open = mocker.patch("klio_core.utils.open", m_open)
mock_safe_load = mocker.Mock()
monkeypatch.setattr(utils.yaml, "safe_load", mock_safe_load)
path = "path/to/a/file"
utils.get_config_by_path(path)
mock_open.assert_called_once_with(path)
def test_get_config_by_path_error(mocker, monkeypatch, caplog):
m_open = mocker.mock_open()
mock_open = mocker.patch("klio_core.utils.open", m_open)
mock_open.side_effect = IOError
with pytest.raises(SystemExit):
path = "path/to/a/file"
utils.get_config_by_path(path)
assert 1 == len(caplog.records)
#########################
# Cli/exec command tests
#########################
@pytest.mark.parametrize(
"image",
(
"dataflow.gcr.io/v1beta3/python",
"dataflow.gcr.io/v1beta3/python-base",
"dataflow.gcr.io/v1beta3/python-fnapi",
),
)
def test_warn_if_py2_job(image, patch_os_getcwd, mocker):
dockerfile = (
'## -*- docker-image-name: "gcr.io/foo/bar" -*-\n'
"FROM {image}:1.2.3\n"
'LABEL maintainer "<EMAIL>"\n'
).format(image=image)
m_open = mock.mock_open(read_data=dockerfile)
mock_open = mocker.patch("klio_core.utils.open", m_open)
m_is_file = mocker.Mock()
m_is_file.return_value = True
mock_is_file = mocker.patch("klio_core.utils.os.path.isfile", m_is_file)
warn_msg = (
"Python 2 support in Klio is deprecated. "
"Please upgrade to Python 3.5+"
)
with pytest.warns(UserWarning, match=warn_msg):
utils.warn_if_py2_job(patch_os_getcwd)
exp_read_file = os.path.join(patch_os_getcwd, "Dockerfile")
mock_is_file.assert_called_once_with(exp_read_file)
mock_open.assert_called_once_with(exp_read_file, "r")
@pytest.mark.parametrize("has_from_line", (True, False))
@pytest.mark.parametrize("file_exists", (True, False))
def test_warn_if_py2_job_no_warn(
has_from_line, file_exists, patch_os_getcwd, mocker
):
from_line = "\n"
if has_from_line:
from_line = "FROM dataflow.gcr.io/v1beta3/python36-fnapi:1.2.3\n"
dockerfile = (
'## -*- docker-image-name: "gcr.io/foo/bar" -*-\n'
+ from_line
+ 'LABEL maintainer "<EMAIL>"\n'
)
m_open = mock.mock_open(read_data=dockerfile)
mock_open = mocker.patch("klio_core.utils.open", m_open)
m_is_file = mocker.Mock()
m_is_file.return_value = file_exists
mock_is_file = mocker.patch("klio_core.utils.os.path.isfile", m_is_file)
utils.warn_if_py2_job(patch_os_getcwd)
exp_read_file = os.path.join(patch_os_getcwd, "Dockerfile")
mock_is_file.assert_called_once_with(exp_read_file)
if file_exists:
mock_open.assert_called_once_with(exp_read_file, "r")
@pytest.mark.parametrize(
"job_dir,conf_file",
(
(None, None),
(None, "klio-job2.yaml"),
("foo/bar", None),
("foo/bar", "klio-job2.yaml"),
),
)
def test_get_config_job_dir(job_dir, conf_file, patch_os_getcwd):
exp_job_dir = patch_os_getcwd
if job_dir:
exp_job_dir = os.path.abspath(os.path.join(patch_os_getcwd, job_dir))
exp_conf_file = conf_file or os.path.join(exp_job_dir, "klio-job.yaml")
if job_dir and conf_file:
exp_conf_file = os.path.join(job_dir, conf_file)
ret_job_dir, ret_conf_file = utils.get_config_job_dir(job_dir, conf_file)
assert exp_job_dir == ret_job_dir
assert exp_conf_file == ret_conf_file
| 3,103 |
305 | <filename>gtests/Base.Log.test.cpp
#include "Saba/Base/Log.h"
#include <string>
#include <vector>
#include <gtest/gtest.h>
class TestSink : public spdlog::sinks::sink
{
public:
void log(const spdlog::details::log_msg& msg) override
{
m_buffer.push_back(msg.formatted.str());
}
void flush() override
{
}
std::vector<std::string> m_buffer;
};
TEST(BaseTest, LogTest)
{
auto logger = saba::Singleton<saba::Logger>::Get();
auto testSink = logger->AddSink<TestSink>();
EXPECT_NE(nullptr, testSink.get());
SABA_INFO("test1");
SABA_WARN("test2");
SABA_ERROR("test3");
EXPECT_EQ(3, testSink->m_buffer.size());
EXPECT_EQ(2, logger->GetLogger()->sinks().size());
logger->RemoveSink(testSink.get());
EXPECT_EQ(1, logger->GetLogger()->sinks().size());
SABA_INFO("test4");
EXPECT_EQ(3, testSink->m_buffer.size());
}
| 357 |
5,926 | import functools
import importlib
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib.__import__(*args, **kwargs)
def importlib_only(fxn):
"""Decorator to skip a test if using __builtins__.__import__."""
return unittest.skipIf(using___import__, "importlib-specific test")(fxn)
def mock_path_hook(*entries, importer):
"""A mock sys.path_hooks entry."""
def hook(entry):
if entry not in entries:
raise ImportError
return importer
return hook
| 257 |
754 | /*-
* <<
* UAVStack
* ==
* Copyright (C) 2016 - 2017 UAVStack
* ==
* 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.creditease.uav.grafana;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import javax.ws.rs.container.AsyncResponse;
import com.creditease.agent.log.SystemLogger;
import com.creditease.agent.log.api.ISystemLogger;
import com.creditease.uav.httpasync.HttpClientCallback;
import com.creditease.uav.httpasync.HttpClientCallbackResult;
@SuppressWarnings("rawtypes")
public class GrafanaHttpCallBack implements HttpClientCallback {
protected ISystemLogger logger = SystemLogger.getLogger(GrafanaHttpCallBack.class);
protected String requestType = null;
protected String requestUrl = null;
protected String requestData = null;
protected CountDownLatch latch = null;
protected Map params = new HashMap();
protected AsyncResponse response;
public void setResponse(AsyncResponse response) {
this.response = response;
}
public AsyncResponse getResponse() {
return this.response;
}
public GrafanaHttpCallBack() {
}
@SuppressWarnings("unchecked")
public GrafanaHttpCallBack(Map _params) {
if (null != _params && !_params.isEmpty()) {
this.params.putAll(_params);
}
}
@SuppressWarnings("unchecked")
public GrafanaHttpCallBack(Map _params, CountDownLatch latch) {
if (null != _params && !_params.isEmpty()) {
this.params.putAll(_params);
}
this.latch = latch;
}
public String getRequestType() {
return requestType;
}
public void setRequestType(String requestType) {
this.requestType = requestType;
}
public String getRequestUrl() {
return requestUrl;
}
public void setRequestUrl(String requestUrl) {
this.requestUrl = requestUrl;
}
public String getRequestData() {
return requestData;
}
public void setRequestData(String requestData) {
this.requestData = requestData;
}
@SuppressWarnings("unchecked")
public void appendParams(Map _params) {
if (null != _params && !_params.isEmpty()) {
this.params.putAll(_params);
}
}
public Map getParams() {
return params;
}
@Override
public void completed(HttpClientCallbackResult result) {
String resp = result.getReplyDataAsString();// 此方法是流读取,只能获取一次
completedLog(result, resp);
}
@Override
public void failed(HttpClientCallbackResult result) {
String resp = result.getReplyDataAsString();
String resultMsg = "{\"code\":\"00\",\"msg\":\"操作失败\"}";
failedLog(result, resp);
if (latch != null) {
latch.countDown();
}
if (this.response != null) {
this.response.resume(resultMsg);
}
}
protected void completedLog(HttpClientCallbackResult result, String respStr) {
logger.info(this, getLogFormat(result, respStr));
}
protected void failedLog(HttpClientCallbackResult result, String respStr) {
logger.err(this, getLogFormat(result, respStr), result.getException());
}
private String getLogFormat(HttpClientCallbackResult result, String respStr) {
return "GrafanaHttpCallBack. " + " returnCode:" + result.getRetCode() + " requestType:" + requestType
+ " requestUrl:" + requestUrl + " requestData:" + requestData + " requestResp:" + respStr;
}
} | 1,513 |
964 | [
{
"queryName": "Schema Object Properties With Duplicated Keys (v3)",
"severity": "INFO",
"line": 19,
"filename": "positive1.json"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v3)",
"severity": "INFO",
"line": 38,
"filename": "positive1.json"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v3)",
"severity": "INFO",
"line": 53,
"filename": "positive1.json"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v3)",
"severity": "INFO",
"line": 16,
"filename": "positive2.yaml"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v3)",
"severity": "INFO",
"line": 28,
"filename": "positive2.yaml"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v3)",
"severity": "INFO",
"line": 37,
"filename": "positive2.yaml"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v3)",
"severity": "INFO",
"line": 28,
"filename": "positive3.json"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v3)",
"severity": "INFO",
"line": 44,
"filename": "positive3.json"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v3)",
"severity": "INFO",
"line": 57,
"filename": "positive3.json"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v3)",
"severity": "INFO",
"line": 24,
"filename": "positive4.yaml"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v3)",
"severity": "INFO",
"line": 34,
"filename": "positive4.yaml"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v3)",
"severity": "INFO",
"line": 41,
"filename": "positive4.yaml"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v2)",
"severity": "INFO",
"line": 28,
"filename": "positive5.json"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v2)",
"severity": "INFO",
"line": 44,
"filename": "positive5.json"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v2)",
"severity": "INFO",
"line": 57,
"filename": "positive5.json"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v2)",
"severity": "INFO",
"line": 24,
"filename": "positive6.yaml"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v2)",
"severity": "INFO",
"line": 34,
"filename": "positive6.yaml"
},
{
"queryName": "Schema Object Properties With Duplicated Keys (v2)",
"severity": "INFO",
"line": 41,
"filename": "positive6.yaml"
}
]
| 1,093 |
652 | //
// LogConst.h
// WLForm
//
// Created by 刘光强 on 2018/5/5.
// Copyright © 2018年 quangqiang. All rights reserved.
//
#ifndef LogConst_h
#define LogConst_h
#ifdef DEBUG
#define NSLog(FORMAT, ...) fprintf(stderr, "%s:%d\t%s\n", [[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat:FORMAT, ## __VA_ARGS__] UTF8String]);
#else
#define NSLog(FORMAT, ...) nil
#endif
#endif /* LogConst_h */
| 191 |
552 | // Data structures for the layout of a package
#pragma once
#include <EtCore/Hashing/Hash.h>
namespace et {
namespace core {
//---------------------------------
// E_CompressionType
//
// List of supported compression types
//
enum class E_CompressionType : uint8
{
Store,
//Brotli, - will be implemented
COUNT
};
//---------------------------------
// PkgHeader
//
// Minimal file data for the central directory
//
struct PkgHeader
{
uint64 numEntries;
};
//---------------------------------
// PkgFileInfo
//
// Minimal file data for the central directory
//
struct PkgFileInfo
{
HashString fileId;
uint64 offset;
};
//---------------------------------
// PkgEntry
//
// Meta info for a package file entry
//
struct PkgEntry
{
HashString fileId;
E_CompressionType compressionType;
uint16 nameLength;
uint64 size;
};
} // namespace core
} // namespace et
| 262 |
3,200 | # Copyright 2021 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
""" test call inner net attr"""
import numpy as np
import mindspore.nn as nn
from mindspore import Tensor, Parameter
from mindspore import context
from mindspore.ops import composite as C
context.set_context(mode=context.GRAPH_MODE)
class InnerInNet(nn.Cell):
def __init__(self, init_data, const):
super(InnerInNet, self).__init__()
self.weight = Parameter(init_data, name="weight_s")
self.t = init_data
self.const = const
def construct(self, input_x):
if self.const:
return input_x * self.t
return input_x * self.weight
class InnerNet(nn.Cell):
def __init__(self, init_data, const):
super(InnerNet, self).__init__()
self.inner_in_net = InnerInNet(init_data, const)
self.t = init_data
self.const = const
def construct(self, input_x):
if self.const:
return self.inner_in_net.t / self.inner_in_net(input_x)
return self.inner_in_net.weight / self.inner_in_net(input_x)
class Net(nn.Cell):
def __init__(self, init_data, const):
super(Net, self).__init__()
self.inner_net = InnerNet(init_data, const)
self.x = Tensor(np.ones((2, 3)) * 5)
self.y = Tensor(np.ones((2, 3)) * 6)
self.const = const
self.weight = Parameter(init_data, name="weight_s")
def construct(self, input_x, input_y):
if self.const:
return self.inner_net.t + self.inner_net(self.x) - self.y
return self.inner_net.t + self.inner_net(input_x) - input_y
class OuterMostNet(nn.Cell):
def __init__(self, init_data, const):
super(OuterMostNet, self).__init__()
self.net = Net(init_data, const)
def construct(self, input_x, input_y):
return self.net.inner_net.inner_in_net.t
class GradNet(nn.Cell):
def __init__(self, net):
super(GradNet, self).__init__()
self.forward_net = net
self.sens = Tensor(np.ones((2, 2), np.float32) * 5)
self.grad_all = C.GradOperation(get_all=True)
def construct(self, input_x, input_y):
return self.grad_all(self.forward_net)(input_x, input_y)
def test_inner_net_attr():
input_x = Tensor(np.ones((2, 3)) * 2)
input_y = Tensor(np.ones((2, 3)) * 3)
init_data = Tensor(np.ones((2, 3)) * 4)
test_var_net = Net(init_data, False)
test_var_net(input_x, input_y)
grad_net = GradNet(test_var_net)
grad_net(input_x, input_y)
test_const_net = Net(init_data, True)
ret = test_const_net(input_x, input_y)
expect = -1.8 * np.ones((2, 3))
assert np.allclose(ret.asnumpy(), expect)
test_outer_net = OuterMostNet(init_data, True)
ret = test_outer_net(input_x, input_y)
assert np.allclose(ret.asnumpy(), init_data.asnumpy())
| 1,389 |
1,056 | <filename>ide/parsing.indexing/src/org/netbeans/modules/parsing/impl/indexing/InjectedTasksSupport.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.parsing.impl.indexing;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.netbeans.api.annotations.common.CheckForNull;
import org.netbeans.api.annotations.common.NonNull;
import org.openide.util.Parameters;
/**
*
* @author <NAME>
*/
class InjectedTasksSupport {
private static final Queue<Callable<?>> tasks = new ConcurrentLinkedQueue<Callable<?>>();
static void enqueueTask(@NonNull final Callable<?> task) {
Parameters.notNull("task", task); //NOI18N
tasks.offer(task);
}
static void clear() {
if (!TransientUpdateSupport.isTransientUpdate()) {
tasks.clear();
}
}
@CheckForNull
static Callable<?> nextTask() {
return TransientUpdateSupport.isTransientUpdate()?
null:
tasks.poll();
}
static void execute() throws IOException {
for (Callable<?> task = nextTask(); task != null; task = nextTask()) {
try {
task.call();
} catch (RuntimeException re) {
throw re;
} catch (IOException ioe) {
throw ioe;
} catch (Exception e) {
throw new IOException(e);
}
}
}
}
| 821 |
648 | {"category":"measurement","id":"example","identifier":{"system":"http://goodcare.org/devicemetric/id","value":"345675"},"resourceType":"DeviceMetric","text":{"div":"<div><p><b>Generated Narrative with Details</b></p><p><b>id</b>: example</p><p><b>type</b>: MDC_PULS_OXIM_SAT_O2 <span>(Details : {https://rtmms.nist.gov code '150456' = '??', given as 'MDC_PULS_OXIM_SAT_O2'})</span></p><p><b>identifier</b>: 345675</p><p><b>unit</b>: MDC_DIM_PERCENT <span>(Details : {https://rtmms.nist.gov code '262688' = '??', given as 'MDC_DIM_PERCENT'})</span></p><p><b>category</b>: measurement</p></div>","status":"generated"},"type":{"coding":[{"code":"150456","display":"MDC_PULS_OXIM_SAT_O2","system":"https://rtmms.nist.gov"}]},"unit":{"coding":[{"code":"262688","display":"MDC_DIM_PERCENT","system":"https://rtmms.nist.gov"}]}} | 320 |
3,486 | <reponame>rafaelmotaalves/titan
package com.thinkaurelius.titan.graphdb.database.serialize.attribute;
import com.thinkaurelius.titan.diskstorage.ScanBuffer;
import com.thinkaurelius.titan.diskstorage.WriteBuffer;
import com.thinkaurelius.titan.graphdb.database.serialize.OrderPreservingSerializer;
public class ShortSerializer implements OrderPreservingSerializer<Short> {
private static final long serialVersionUID = 117423419862504186L;
@Override
public Short read(ScanBuffer buffer) {
return Short.valueOf((short)(buffer.getShort() + Short.MIN_VALUE));
}
@Override
public void write(WriteBuffer out, Short object) {
out.putShort((short)(object.shortValue() - Short.MIN_VALUE));
}
@Override
public Short readByteOrder(ScanBuffer buffer) {
return read(buffer);
}
@Override
public void writeByteOrder(WriteBuffer buffer, Short attribute) {
write(buffer,attribute);
}
/*
====== These methods apply to all whole numbers with minor modifications ========
====== byte, short, int, long ======
*/
@Override
public Short convert(Object value) {
if (value instanceof Number) {
double d = ((Number)value).doubleValue();
if (Double.isNaN(d) || Math.round(d)!=d) throw new IllegalArgumentException("Not a valid short: " + value);
long l = ((Number)value).longValue();
if (l>=Short.MIN_VALUE && l<=Short.MAX_VALUE) return Short.valueOf((short)l);
else throw new IllegalArgumentException("Value too large for short: " + value);
} else if (value instanceof String) {
return Short.parseShort((String)value);
} else return null;
}
}
| 635 |
1,151 | from sklearn.base import ClusterMixin, TransformerMixin
from sklearn.metrics.pairwise import pairwise_kernels
from sklearn.utils import check_random_state
from sklearn.utils.extmath import stable_cumsum
from sklearn.utils.validation import _check_sample_weight
from scipy.spatial.distance import cdist
import numpy
import warnings
try:
from sklearn.cluster._kmeans import _kmeans_plusplus
except:
try:
from sklearn.cluster._kmeans import _k_init
warnings.warn(
"Scikit-learn <0.24 will be deprecated in a "
"future release of tslearn"
)
except:
from sklearn.cluster.k_means_ import _k_init
warnings.warn(
"Scikit-learn <0.24 will be deprecated in a "
"future release of tslearn"
)
# sklearn < 0.24: _k_init only returns centroids, not indices
# So we need to add a second (fake) return value to make it match
# _kmeans_plusplus' signature
def _kmeans_plusplus(*args, **kwargs):
return _k_init(*args, **kwargs), None
from tslearn.metrics import cdist_gak, cdist_dtw, cdist_soft_dtw, sigma_gak
from tslearn.barycenters import euclidean_barycenter, \
dtw_barycenter_averaging, softdtw_barycenter
from sklearn.utils import check_array
from sklearn.utils.validation import check_is_fitted
from tslearn.utils import (to_time_series_dataset, to_sklearn_dataset,
check_dims)
from tslearn.bases import BaseModelPackage, TimeSeriesBaseEstimator
from .utils import (EmptyClusterError, _check_initial_guess,
_check_no_empty_cluster, _check_full_length,
TimeSeriesCentroidBasedClusteringMixin, _compute_inertia)
__author__ = '<NAME> <EMAIL>'
# Kernel k-means is derived from https://gist.github.com/mblondel/6230787 by
# <NAME>, under BSD 3 clause license
def _k_init_metric(X, n_clusters, cdist_metric, random_state,
n_local_trials=None):
"""Init n_clusters seeds according to k-means++ with a custom distance
metric.
Parameters
----------
X : array, shape (n_samples, n_timestamps, n_features)
The data to pick seeds for.
n_clusters : integer
The number of seeds to choose
cdist_metric : function
Function to be called for cross-distance computations
random_state : RandomState instance
Generator used to initialize the centers.
n_local_trials : integer, optional
The number of seeding trials for each center (except the first),
of which the one reducing inertia the most is greedily chosen.
Set to None to make the number of trials depend logarithmically
on the number of seeds (2+log(k)); this is the default.
Notes
-----
Selects initial cluster centers for k-mean clustering in a smart way
to speed up convergence. see: <NAME>. and <NAME>.
"k-means++: the advantages of careful seeding". ACM-SIAM symposium
on Discrete algorithms. 2007
Version adapted from scikit-learn for use with a custom metric in place of
Euclidean distance.
"""
n_samples, n_timestamps, n_features = X.shape
centers = numpy.empty((n_clusters, n_timestamps, n_features),
dtype=X.dtype)
# Set the number of local seeding trials if none is given
if n_local_trials is None:
# This is what Arthur/Vassilvitskii tried, but did not report
# specific results for other than mentioning in the conclusion
# that it helped.
n_local_trials = 2 + int(numpy.log(n_clusters))
# Pick first center randomly
center_id = random_state.randint(n_samples)
centers[0] = X[center_id]
# Initialize list of closest distances and calculate current potential
closest_dist_sq = cdist_metric(centers[0, numpy.newaxis], X) ** 2
current_pot = closest_dist_sq.sum()
# Pick the remaining n_clusters-1 points
for c in range(1, n_clusters):
# Choose center candidates by sampling with probability proportional
# to the squared distance to the closest existing center
rand_vals = random_state.random_sample(n_local_trials) * current_pot
candidate_ids = numpy.searchsorted(stable_cumsum(closest_dist_sq),
rand_vals)
# XXX: numerical imprecision can result in a candidate_id out of range
numpy.clip(candidate_ids, None, closest_dist_sq.size - 1,
out=candidate_ids)
# Compute distances to center candidates
distance_to_candidates = cdist_metric(X[candidate_ids], X) ** 2
# update closest distances squared and potential for each candidate
numpy.minimum(closest_dist_sq, distance_to_candidates,
out=distance_to_candidates)
candidates_pot = distance_to_candidates.sum(axis=1)
# Decide which candidate is the best
best_candidate = numpy.argmin(candidates_pot)
current_pot = candidates_pot[best_candidate]
closest_dist_sq = distance_to_candidates[best_candidate]
best_candidate = candidate_ids[best_candidate]
# Permanently add best center candidate found in local tries
centers[c] = X[best_candidate]
return centers
class KernelKMeans(ClusterMixin, BaseModelPackage, TimeSeriesBaseEstimator):
"""Kernel K-means.
Parameters
----------
n_clusters : int (default: 3)
Number of clusters to form.
kernel : string, or callable (default: "gak")
The kernel should either be "gak", in which case the Global Alignment
Kernel from [2]_ is used or a value that is accepted as a metric
by `scikit-learn's pairwise_kernels
<https://scikit-learn.org/stable/modules/generated/\
sklearn.metrics.pairwise.pairwise_kernels.html>`_
max_iter : int (default: 50)
Maximum number of iterations of the k-means algorithm for a single run.
tol : float (default: 1e-6)
Inertia variation threshold. If at some point, inertia varies less than
this threshold between two consecutive
iterations, the model is considered to have converged and the algorithm
stops.
n_init : int (default: 1)
Number of time the k-means algorithm will be run with different
centroid seeds. The final results will be the
best output of n_init consecutive runs in terms of inertia.
kernel_params : dict or None (default: None)
Kernel parameters to be passed to the kernel function.
None means no kernel parameter is set.
For Global Alignment Kernel, the only parameter of interest is `sigma`.
If set to 'auto', it is computed based on a sampling of the training
set
(cf :ref:`tslearn.metrics.sigma_gak <fun-tslearn.metrics.sigma_gak>`).
If no specific value is set for `sigma`, its defaults to 1.
sigma : float or "auto" (default: "auto")
Bandwidth parameter for the Global Alignment kernel. If set to 'auto',
it is computed based on a sampling of the training set
(cf :ref:`tslearn.metrics.sigma_gak <fun-tslearn.metrics.sigma_gak>`)
.. deprecated:: 0.4
Setting `sigma` directly as a parameter for KernelKMeans and
GlobalAlignmentKernelKMeans is deprecated in version 0.4 and will
be removed in 0.6. Use `kernel_params` instead.
n_jobs : int or None, optional (default=None)
The number of jobs to run in parallel for GAK cross-similarity matrix
computations.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See scikit-learns'
`Glossary <https://scikit-learn.org/stable/glossary.html#term-n-jobs>`_
for more details.
verbose : int (default: 0)
If nonzero, joblib progress messages are printed.
random_state : integer or numpy.RandomState, optional
Generator used to initialize the centers. If an integer is given, it
fixes the seed. Defaults to the global
numpy random number generator.
Attributes
----------
labels_ : numpy.ndarray
Labels of each point
inertia_ : float
Sum of distances of samples to their closest cluster center (computed
using the kernel trick).
sample_weight_ : numpy.ndarray
The weight given to each sample from the data provided to fit.
n_iter_ : int
The number of iterations performed during fit.
Notes
-----
The training data are saved to disk if this model is
serialized and may result in a large model file if the training
dataset is large.
Examples
--------
>>> from tslearn.generators import random_walks
>>> X = random_walks(n_ts=50, sz=32, d=1)
>>> gak_km = KernelKMeans(n_clusters=3, kernel="gak", random_state=0)
>>> gak_km.fit(X) # doctest: +ELLIPSIS
KernelKMeans(...)
>>> print(numpy.unique(gak_km.labels_))
[0 1 2]
References
----------
.. [1] Kernel k-means, Spectral Clustering and Normalized Cuts.
<NAME>, <NAME>, <NAME>. KDD 2004.
.. [2] Fast Global Alignment Kernels. <NAME>. ICML 2011.
"""
def __init__(self, n_clusters=3, kernel="gak", max_iter=50, tol=1e-6,
n_init=1, kernel_params=None, sigma=1., n_jobs=None,
verbose=0, random_state=None):
self.n_clusters = n_clusters
self.kernel = kernel
self.max_iter = max_iter
self.tol = tol
self.n_init = n_init
self.kernel_params = kernel_params
self.sigma = sigma
self.n_jobs = n_jobs
self.verbose = verbose
self.random_state = random_state
def _is_fitted(self):
check_is_fitted(self, '_X_fit')
return True
def _get_model_params(self):
params = super()._get_model_params()
params.update({'_X_fit': self._X_fit})
return params
def _get_kernel_params(self):
if self.kernel_params is None:
kernel_params = {}
else:
kernel_params = self.kernel_params
if self.kernel == "gak":
if hasattr(self, "sigma_gak_"):
kernel_params["sigma"] = self.sigma_gak_
elif "sigma" not in kernel_params.keys():
kernel_params["sigma"] = self.sigma
return kernel_params
def _get_kernel(self, X, Y=None):
kernel_params = self._get_kernel_params()
if self.kernel == "gak":
return cdist_gak(X, Y, n_jobs=self.n_jobs, verbose=self.verbose,
**kernel_params)
else:
X_sklearn = to_sklearn_dataset(X)
if Y is not None:
Y_sklearn = to_sklearn_dataset(Y)
else:
Y_sklearn = Y
return pairwise_kernels(X_sklearn, Y_sklearn, metric=self.kernel,
n_jobs=self.n_jobs, **kernel_params)
def _fit_one_init(self, K, rs):
n_samples = K.shape[0]
self.labels_ = rs.randint(self.n_clusters, size=n_samples)
dist = numpy.empty((n_samples, self.n_clusters))
old_inertia = numpy.inf
for it in range(self.max_iter):
dist.fill(0)
self._compute_dist(K, dist)
self.labels_ = dist.argmin(axis=1)
_check_no_empty_cluster(self.labels_, self.n_clusters)
self.inertia_ = self._compute_inertia(dist)
if self.verbose:
print("%.3f" % self.inertia_, end=" --> ")
if numpy.abs(old_inertia - self.inertia_) < self.tol:
break
old_inertia = self.inertia_
if self.verbose:
print("")
self._iter = it + 1
return self
def fit(self, X, y=None, sample_weight=None):
"""Compute kernel k-means clustering.
Parameters
----------
X : array-like of shape=(n_ts, sz, d)
Time series dataset.
y
Ignored
sample_weight : array-like of shape=(n_ts, ) or None (default: None)
Weights to be given to time series in the learning process. By
default, all time series weights are equal.
"""
if self.sigma != 1.:
warnings.warn(
"Setting `sigma` directly as a parameter for KernelKMeans "
"and GlobalAlignmentKernelKMeans is deprecated in version "
"0.4 and will be removed in 0.6. Use `kernel_params` "
"instead.",
DeprecationWarning, stacklevel=2)
X = check_array(X, allow_nd=True, force_all_finite=False)
X = check_dims(X)
sample_weight = _check_sample_weight(sample_weight=sample_weight, X=X)
max_attempts = max(self.n_init, 10)
kernel_params = self._get_kernel_params()
if self.kernel == "gak":
self.sigma_gak_ = kernel_params.get("sigma", 1.)
if self.sigma_gak_ == "auto":
self.sigma_gak_ = sigma_gak(X)
else:
self.sigma_gak_ = None
self.labels_ = None
self.inertia_ = None
self.sample_weight_ = None
self._X_fit = None
# n_iter_ will contain the number of iterations the most
# successful run required.
self.n_iter_ = 0
n_samples = X.shape[0]
K = self._get_kernel(X)
sw = (sample_weight if sample_weight is not None
else numpy.ones(n_samples))
self.sample_weight_ = sw
rs = check_random_state(self.random_state)
last_correct_labels = None
min_inertia = numpy.inf
n_attempts = 0
n_successful = 0
while n_successful < self.n_init and n_attempts < max_attempts:
try:
if self.verbose and self.n_init > 1:
print("Init %d" % (n_successful + 1))
n_attempts += 1
self._fit_one_init(K, rs)
if self.inertia_ < min_inertia:
last_correct_labels = self.labels_
min_inertia = self.inertia_
self.n_iter_ = self._iter
n_successful += 1
except EmptyClusterError:
if self.verbose:
print("Resumed because of empty cluster")
if n_successful > 0:
self.labels_ = last_correct_labels
self.inertia_ = min_inertia
self._X_fit = X
return self
def _compute_dist(self, K, dist):
"""Compute a n_samples x n_clusters distance matrix using the kernel
trick."""
sw = self.sample_weight_
for j in range(self.n_clusters):
mask = (self.labels_ == j)
if numpy.sum(mask) == 0:
raise EmptyClusterError("try smaller n_cluster or better "
"kernel parameters")
# NB: we use a normalized kernel so k(x,x) = 1 for all x
# (including the centroid)
dist[:, j] = 2 - 2 * numpy.sum(sw[mask] * K[:, mask],
axis=1) / sw[mask].sum()
@staticmethod
def _compute_inertia(dist_sq):
return dist_sq.min(axis=1).sum()
def fit_predict(self, X, y=None):
"""Fit kernel k-means clustering using X and then predict the closest
cluster each time series in X belongs to.
It is more efficient to use this method than to sequentially call fit
and predict.
Parameters
----------
X : array-like of shape=(n_ts, sz, d)
Time series dataset to predict.
y
Ignored
Returns
-------
labels : array of shape=(n_ts, )
Index of the cluster each sample belongs to.
"""
return self.fit(X, y).labels_
def predict(self, X):
"""Predict the closest cluster each time series in X belongs to.
Parameters
----------
X : array-like of shape=(n_ts, sz, d)
Time series dataset to predict.
Returns
-------
labels : array of shape=(n_ts, )
Index of the cluster each sample belongs to.
"""
X = check_array(X, allow_nd=True, force_all_finite=False)
check_is_fitted(self, '_X_fit')
X = check_dims(X, X_fit_dims=self._X_fit.shape,
check_n_features_only=True)
K = self._get_kernel(X, self._X_fit)
n_samples = X.shape[0]
dist = numpy.zeros((n_samples, self.n_clusters))
self._compute_dist(K, dist)
return dist.argmin(axis=1)
def _more_tags(self):
return {'allow_nan': True, 'allow_variable_length': True}
class GlobalAlignmentKernelKMeans(KernelKMeans):
def __init__(self, **kwargs):
warnings.warn(
"`GlobalAlignmentKernelKMeans` is deprecated in version "
"0.4 and will be removed in 0.6. Use `KernelKMeans` "
"instead.",
DeprecationWarning, stacklevel=2)
super().__init__(**kwargs)
self.kernel = "gak"
class TimeSeriesKMeans(TransformerMixin, ClusterMixin,
TimeSeriesCentroidBasedClusteringMixin,
BaseModelPackage, TimeSeriesBaseEstimator):
"""K-means clustering for time-series data.
Parameters
----------
n_clusters : int (default: 3)
Number of clusters to form.
max_iter : int (default: 50)
Maximum number of iterations of the k-means algorithm for a single run.
tol : float (default: 1e-6)
Inertia variation threshold. If at some point, inertia varies less than
this threshold between two consecutive
iterations, the model is considered to have converged and the algorithm
stops.
n_init : int (default: 1)
Number of time the k-means algorithm will be run with different
centroid seeds. The final results will be the best output of n_init
consecutive runs in terms of inertia.
metric : {"euclidean", "dtw", "softdtw"} (default: "euclidean")
Metric to be used for both cluster assignment and barycenter
computation. If "dtw", DBA is used for barycenter
computation.
max_iter_barycenter : int (default: 100)
Number of iterations for the barycenter computation process. Only used
if `metric="dtw"` or `metric="softdtw"`.
metric_params : dict or None (default: None)
Parameter values for the chosen metric.
For metrics that accept parallelization of the cross-distance matrix
computations, `n_jobs` key passed in `metric_params` is overridden by
the `n_jobs` argument.
n_jobs : int or None, optional (default=None)
The number of jobs to run in parallel for cross-distance matrix
computations.
Ignored if the cross-distance matrix cannot be computed using
parallelization.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See scikit-learns'
`Glossary <https://scikit-learn.org/stable/glossary.html#term-n-jobs>`_
for more details.
dtw_inertia: bool (default: False)
Whether to compute DTW inertia even if DTW is not the chosen metric.
verbose : int (default: 0)
If nonzero, print information about the inertia while learning
the model and joblib progress messages are printed.
random_state : integer or numpy.RandomState, optional
Generator used to initialize the centers. If an integer is given, it
fixes the seed. Defaults to the global
numpy random number generator.
init : {'k-means++', 'random' or an ndarray} (default: 'k-means++')
Method for initialization:
'k-means++' : use k-means++ heuristic. See `scikit-learn's k_init_
<https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/\
cluster/k_means_.py>`_ for more.
'random': choose k observations (rows) at random from data for the
initial centroids.
If an ndarray is passed, it should be of shape (n_clusters, ts_size, d)
and gives the initial centers.
Attributes
----------
labels_ : numpy.ndarray
Labels of each point.
cluster_centers_ : numpy.ndarray of shape (n_clusters, sz, d)
Cluster centers.
`sz` is the size of the time series used at fit time if the init method
is 'k-means++' or 'random', and the size of the longest initial
centroid if those are provided as a numpy array through init parameter.
inertia_ : float
Sum of distances of samples to their closest cluster center.
n_iter_ : int
The number of iterations performed during fit.
Notes
-----
If `metric` is set to `"euclidean"`, the algorithm expects a dataset of
equal-sized time series.
Examples
--------
>>> from tslearn.generators import random_walks
>>> X = random_walks(n_ts=50, sz=32, d=1)
>>> km = TimeSeriesKMeans(n_clusters=3, metric="euclidean", max_iter=5,
... random_state=0).fit(X)
>>> km.cluster_centers_.shape
(3, 32, 1)
>>> km_dba = TimeSeriesKMeans(n_clusters=3, metric="dtw", max_iter=5,
... max_iter_barycenter=5,
... random_state=0).fit(X)
>>> km_dba.cluster_centers_.shape
(3, 32, 1)
>>> km_sdtw = TimeSeriesKMeans(n_clusters=3, metric="softdtw", max_iter=5,
... max_iter_barycenter=5,
... metric_params={"gamma": .5},
... random_state=0).fit(X)
>>> km_sdtw.cluster_centers_.shape
(3, 32, 1)
>>> X_bis = to_time_series_dataset([[1, 2, 3, 4],
... [1, 2, 3],
... [2, 5, 6, 7, 8, 9]])
>>> km = TimeSeriesKMeans(n_clusters=2, max_iter=5,
... metric="dtw", random_state=0).fit(X_bis)
>>> km.cluster_centers_.shape
(2, 6, 1)
"""
def __init__(self, n_clusters=3, max_iter=50, tol=1e-6, n_init=1,
metric="euclidean", max_iter_barycenter=100,
metric_params=None, n_jobs=None, dtw_inertia=False,
verbose=0, random_state=None, init='k-means++'):
self.n_clusters = n_clusters
self.max_iter = max_iter
self.tol = tol
self.n_init = n_init
self.metric = metric
self.max_iter_barycenter = max_iter_barycenter
self.metric_params = metric_params
self.n_jobs = n_jobs
self.dtw_inertia = dtw_inertia
self.verbose = verbose
self.random_state = random_state
self.init = init
def _is_fitted(self):
check_is_fitted(self, ['cluster_centers_'])
return True
def _get_metric_params(self):
if self.metric_params is None:
metric_params = {}
else:
metric_params = self.metric_params.copy()
if "n_jobs" in metric_params.keys():
del metric_params["n_jobs"]
return metric_params
def _fit_one_init(self, X, x_squared_norms, rs):
metric_params = self._get_metric_params()
n_ts, sz, d = X.shape
if hasattr(self.init, '__array__'):
self.cluster_centers_ = self.init.copy()
elif isinstance(self.init, str) and self.init == "k-means++":
if self.metric == "euclidean":
self.cluster_centers_ = _kmeans_plusplus(
X.reshape((n_ts, -1)),
self.n_clusters,
x_squared_norms=x_squared_norms,
random_state=rs
)[0].reshape((-1, sz, d))
else:
if self.metric == "dtw":
def metric_fun(x, y):
return cdist_dtw(x, y, n_jobs=self.n_jobs,
verbose=self.verbose, **metric_params)
elif self.metric == "softdtw":
def metric_fun(x, y):
return cdist_soft_dtw(x, y, **metric_params)
else:
raise ValueError(
"Incorrect metric: %s (should be one of 'dtw', "
"'softdtw', 'euclidean')" % self.metric
)
self.cluster_centers_ = _k_init_metric(X, self.n_clusters,
cdist_metric=metric_fun,
random_state=rs)
elif self.init == "random":
indices = rs.choice(X.shape[0], self.n_clusters)
self.cluster_centers_ = X[indices].copy()
else:
raise ValueError("Value %r for parameter 'init'"
"is invalid" % self.init)
self.cluster_centers_ = _check_full_length(self.cluster_centers_)
old_inertia = numpy.inf
for it in range(self.max_iter):
self._assign(X)
if self.verbose:
print("%.3f" % self.inertia_, end=" --> ")
self._update_centroids(X)
if numpy.abs(old_inertia - self.inertia_) < self.tol:
break
old_inertia = self.inertia_
if self.verbose:
print("")
self._iter = it + 1
return self
def _transform(self, X):
metric_params = self._get_metric_params()
if self.metric == "euclidean":
return cdist(X.reshape((X.shape[0], -1)),
self.cluster_centers_.reshape((self.n_clusters, -1)),
metric="euclidean")
elif self.metric == "dtw":
return cdist_dtw(X, self.cluster_centers_, n_jobs=self.n_jobs,
verbose=self.verbose, **metric_params)
elif self.metric == "softdtw":
return cdist_soft_dtw(X, self.cluster_centers_, **metric_params)
else:
raise ValueError("Incorrect metric: %s (should be one of 'dtw', "
"'softdtw', 'euclidean')" % self.metric)
def _assign(self, X, update_class_attributes=True):
dists = self._transform(X)
matched_labels = dists.argmin(axis=1)
if update_class_attributes:
self.labels_ = matched_labels
_check_no_empty_cluster(self.labels_, self.n_clusters)
if self.dtw_inertia and self.metric != "dtw":
inertia_dists = cdist_dtw(X, self.cluster_centers_,
n_jobs=self.n_jobs,
verbose=self.verbose)
else:
inertia_dists = dists
self.inertia_ = _compute_inertia(inertia_dists,
self.labels_,
self._squared_inertia)
return matched_labels
def _update_centroids(self, X):
metric_params = self._get_metric_params()
for k in range(self.n_clusters):
if self.metric == "dtw":
self.cluster_centers_[k] = dtw_barycenter_averaging(
X=X[self.labels_ == k],
barycenter_size=None,
init_barycenter=self.cluster_centers_[k],
metric_params=metric_params,
verbose=False)
elif self.metric == "softdtw":
self.cluster_centers_[k] = softdtw_barycenter(
X=X[self.labels_ == k],
max_iter=self.max_iter_barycenter,
init=self.cluster_centers_[k],
**metric_params)
else:
self.cluster_centers_[k] = euclidean_barycenter(
X=X[self.labels_ == k])
def fit(self, X, y=None):
"""Compute k-means clustering.
Parameters
----------
X : array-like of shape=(n_ts, sz, d)
Time series dataset.
y
Ignored
"""
X = check_array(X, allow_nd=True, force_all_finite='allow-nan')
if hasattr(self.init, '__array__'):
X = check_dims(X, X_fit_dims=self.init.shape,
extend=True,
check_n_features_only=(self.metric != "euclidean"))
self.labels_ = None
self.inertia_ = numpy.inf
self.cluster_centers_ = None
self._X_fit = None
self._squared_inertia = True
self.n_iter_ = 0
max_attempts = max(self.n_init, 10)
X_ = to_time_series_dataset(X)
rs = check_random_state(self.random_state)
if isinstance(self.init, str) and self.init == "k-means++" and \
self.metric == "euclidean":
n_ts, sz, d = X_.shape
x_squared_norms = cdist(X_.reshape((n_ts, -1)),
numpy.zeros((1, sz * d)),
metric="sqeuclidean").reshape((1, -1))
else:
x_squared_norms = None
_check_initial_guess(self.init, self.n_clusters)
best_correct_centroids = None
min_inertia = numpy.inf
n_successful = 0
n_attempts = 0
while n_successful < self.n_init and n_attempts < max_attempts:
try:
if self.verbose and self.n_init > 1:
print("Init %d" % (n_successful + 1))
n_attempts += 1
self._fit_one_init(X_, x_squared_norms, rs)
if self.inertia_ < min_inertia:
best_correct_centroids = self.cluster_centers_.copy()
min_inertia = self.inertia_
self.n_iter_ = self._iter
n_successful += 1
except EmptyClusterError:
if self.verbose:
print("Resumed because of empty cluster")
self._post_fit(X_, best_correct_centroids, min_inertia)
return self
def fit_predict(self, X, y=None):
"""Fit k-means clustering using X and then predict the closest cluster
each time series in X belongs to.
It is more efficient to use this method than to sequentially call fit
and predict.
Parameters
----------
X : array-like of shape=(n_ts, sz, d)
Time series dataset to predict.
y
Ignored
Returns
-------
labels : array of shape=(n_ts, )
Index of the cluster each sample belongs to.
"""
X = check_array(X, allow_nd=True, force_all_finite='allow-nan')
return self.fit(X, y).labels_
def predict(self, X):
"""Predict the closest cluster each time series in X belongs to.
Parameters
----------
X : array-like of shape=(n_ts, sz, d)
Time series dataset to predict.
Returns
-------
labels : array of shape=(n_ts, )
Index of the cluster each sample belongs to.
"""
X = check_array(X, allow_nd=True, force_all_finite='allow-nan')
check_is_fitted(self, 'cluster_centers_')
X = check_dims(X, X_fit_dims=self.cluster_centers_.shape,
extend=True,
check_n_features_only=(self.metric != "euclidean"))
return self._assign(X, update_class_attributes=False)
def transform(self, X):
"""Transform X to a cluster-distance space.
In the new space, each dimension is the distance to the cluster
centers.
Parameters
----------
X : array-like of shape=(n_ts, sz, d)
Time series dataset
Returns
-------
distances : array of shape=(n_ts, n_clusters)
Distances to cluster centers
"""
X = check_array(X, allow_nd=True, force_all_finite='allow-nan')
check_is_fitted(self, 'cluster_centers_')
X = check_dims(X, X_fit_dims=self.cluster_centers_.shape,
extend=True,
check_n_features_only=(self.metric != "euclidean"))
return self._transform(X)
def _more_tags(self):
return {'allow_nan': True, 'allow_variable_length': True}
| 15,380 |
1,056 | <filename>org-netbeans-modules-db/src/main/java/org/netbeans/modules/db/explorer/node/DDLHelper.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.db.explorer.node;
import org.netbeans.lib.ddl.CommandNotSupportedException;
import org.netbeans.lib.ddl.DDLException;
import org.netbeans.lib.ddl.impl.AbstractCommand;
import org.netbeans.lib.ddl.impl.DropIndex;
import org.netbeans.lib.ddl.impl.SetDefaultDatabase;
import org.netbeans.lib.ddl.impl.SetDefaultSchema;
import org.netbeans.lib.ddl.impl.Specification;
/**
* This class factors out interaction with the DDL package. This allows
* us to unit test this interaction
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class DDLHelper {
public static void deleteTable(Specification spec,
String schema, String tablename) throws Exception {
AbstractCommand cmd = spec.createCommandDropTable(tablename);
cmd.setObjectOwner(schema);
cmd.execute();
}
public static void setDefaultDatabase(Specification spec, String dbname) throws CommandNotSupportedException, DDLException {
SetDefaultDatabase cmd = spec.createSetDefaultDatabase(dbname);
cmd.execute();
}
public static void setDefaultSchema(Specification spec, String schemaName) throws CommandNotSupportedException, DDLException {
SetDefaultSchema cmd = spec.createSetDefaultSchema(schemaName);
cmd.execute();
}
public static void deleteIndex(Specification spec,
String schema, String tablename, String indexname) throws CommandNotSupportedException, DDLException
{
DropIndex cmd = spec.createCommandDropIndex(indexname);
cmd.setTableName(tablename);
cmd.setObjectOwner(schema);
cmd.execute();
}
public static void deleteView(Specification spec,
String schema, String viewname) throws CommandNotSupportedException, DDLException {
AbstractCommand cmd = spec.createCommandDropView(viewname);
cmd.setObjectOwner(schema);
cmd.execute();
}
}
| 921 |
366 | <filename>include/networkit/community/OverlappingCommunityDetectionAlgorithm.hpp<gh_stars>100-1000
/*
* OverlappingCommunityDetectionAlgorithm.hpp
*
* Created on: 14.12.2020
* Author: <NAME>
*/
#ifndef NETWORKIT_COMMUNITY_OVERLAPPING_COMMUNITY_DETECTION_ALGORITHM_HPP_
#define NETWORKIT_COMMUNITY_OVERLAPPING_COMMUNITY_DETECTION_ALGORITHM_HPP_
#include <networkit/base/Algorithm.hpp>
#include <networkit/graph/Graph.hpp>
#include <networkit/structures/Cover.hpp>
namespace NetworKit {
/**
* @ingroup community
* Abstract base class for overlapping community detection/graph clustering algorithms.
*/
class OverlappingCommunityDetectionAlgorithm : public Algorithm {
public:
/**
* An overlapping community detection algorithm operates on a graph, so the constructor expects
* a graph.
*
* @param[in] G input graph
*/
OverlappingCommunityDetectionAlgorithm(const Graph &G);
/** Default destructor */
~OverlappingCommunityDetectionAlgorithm() override = default;
/**
* Apply algorithm to graph
*/
void run() override = 0;
/**
* Returns the result of the run method or throws an error, if the algorithm hasn't run yet.
* @return cover of the node set
*/
const Cover &getCover() const;
protected:
const Graph *G;
Cover result;
};
} /* namespace NetworKit */
#endif // NETWORKIT_COMMUNITY_OVERLAPPING_COMMUNITY_DETECTION_ALGORITHM_HPP_
| 507 |
517 | <gh_stars>100-1000
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=======================================================================*/
package org.tensorflow.framework.regularizers;
/**
* A regularizer that applies a L2 (Ridge Regression) regularization penalty.
*
* <p>The L2 regularization penalty is computed as: <code>loss = l2 * reduceSum(square(x))</code>
*/
public class L2 extends L1L2 {
/**
* Create a regularizer that applies an L2 regularization penalty of {@link
* #DEFAULT_REGULARIZATION_PENALTY} and a name based on the class name.
*/
public L2() {
this(null, DEFAULT_REGULARIZATION_PENALTY);
}
/**
* Create a regularizer that applies an L2 regularization penalty of {@link
* #DEFAULT_REGULARIZATION_PENALTY}
*
* @param name the name for this AbstractRegularizer
*/
public L2(String name) {
this(name, DEFAULT_REGULARIZATION_PENALTY);
}
/**
* Create a regularizer that applies an L1 regularization penalty and a name based on the class
* name.
*
* @param l2 the L2 regularization penalty
* @throws IllegalArgumentException if the l2 regularization factor is NaN or is infinite.
*/
public L2(float l2) {
this(null, l2);
}
/**
* Create a regularizer that applies an L1 regularization penalty
*
* @param name the name for this AbstractRegularizer
* @param l2 the L2 regularization penalty
* @throws IllegalArgumentException if the l2 regularization factor is NaN or is infinite.
*/
public L2(String name, float l2) {
super(name, 0f, l2);
}
}
| 644 |
5,893 | # Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from logging import getLogger
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Input, GlobalMaxPooling1D, Lambda, Dense, GRU
from tensorflow.keras.models import Model
from deeppavlov.core.common.registry import register
from deeppavlov.models.ranking.bilstm_siamese_network import BiLSTMSiameseNetwork
log = getLogger(__name__)
@register('bilstm_gru_nn')
class BiLSTMGRUSiameseNetwork(BiLSTMSiameseNetwork):
"""The class implementing a siamese neural network with BiLSTM, GRU and max pooling.
GRU is used to take into account multi-turn dialogue ``context``.
Args:
len_vocab: A size of the vocabulary to build embedding layer.
seed: Random seed.
shared_weights: Whether to use shared weights in the model to encode ``contexts`` and ``responses``.
embedding_dim: Dimensionality of token (word) embeddings.
reccurent: A type of the RNN cell. Possible values are ``lstm`` and ``bilstm``.
hidden_dim: Dimensionality of the hidden state of the RNN cell. If ``reccurent`` equals ``bilstm``
``hidden_dim`` should be doubled to get the actual dimensionality.
max_pooling: Whether to use max-pooling operation to get ``context`` (``response``) vector representation.
If ``False``, the last hidden state of the RNN will be used.
triplet_loss: Whether to use a model with triplet loss.
If ``False``, a model with crossentropy loss will be used.
margin: A margin parameter for triplet loss. Only required if ``triplet_loss`` is set to ``True``.
hard_triplets: Whether to use hard triplets sampling to train the model
i.e. to choose negative samples close to positive ones.
If set to ``False`` random sampling will be used.
Only required if ``triplet_loss`` is set to ``True``.
"""
def create_model(self) -> Model:
input = []
if self.use_matrix:
for i in range(self.num_context_turns + 1):
input.append(Input(shape=(self.max_sequence_length,)))
context = input[:self.num_context_turns]
response = input[-1]
emb_layer = self.embedding_layer()
emb_c = [emb_layer(el) for el in context]
emb_r = emb_layer(response)
else:
for i in range(self.num_context_turns + 1):
input.append(Input(shape=(self.max_sequence_length, self.embedding_dim,)))
context = input[:self.num_context_turns]
response = input[-1]
emb_c = context
emb_r = response
lstm_layer = self.lstm_layer()
lstm_c = [lstm_layer(el) for el in emb_c]
lstm_r = lstm_layer(emb_r)
pooling_layer = GlobalMaxPooling1D(name="pooling")
lstm_c = [pooling_layer(el) for el in lstm_c]
lstm_r = pooling_layer(lstm_r)
lstm_c = [Lambda(lambda x: K.expand_dims(x, 1))(el) for el in lstm_c]
lstm_c = Lambda(lambda x: K.concatenate(x, 1))(lstm_c)
gru_layer = GRU(2 * self.hidden_dim, name="gru")
gru_c = gru_layer(lstm_c)
if self.triplet_mode:
dist = Lambda(self._pairwise_distances)([gru_c, lstm_r])
else:
dist = Lambda(self._diff_mult_dist)([gru_c, lstm_r])
dist = Dense(1, activation='sigmoid', name="score_model")(dist)
model = Model(context + [response], dist)
return model
def create_score_model(self) -> Model:
cr = self.model.inputs
if self.triplet_mode:
emb_c = self.model.get_layer("gru").output
emb_r = self.model.get_layer("pooling").get_output(-1)
dist_score = Lambda(lambda x: self.euclidian_dist(x), name="score_model")
score = dist_score([emb_c, emb_r])
else:
score = self.model.get_layer("score_model").output
score = Lambda(lambda x: 1. - K.squeeze(x, -1))(score)
score = Lambda(lambda x: 1. - x)(score)
model = Model(cr, score)
return model
def create_context_model(self) -> Model:
m = Model(self.model.inputs[:-1],
self.model.get_layer("gru").output)
return m
def create_response_model(self) -> Model:
m = Model(self.model.inputs[-1],
self.model.get_layer("pooling").get_output_at(-1))
return m
| 2,099 |
458 | <reponame>niranjanchintu/hyscale<filename>image-builder/builder-services/src/main/java/io/hyscale/builder/services/docker/impl/DockerBinaryClient.java
/**
* Copyright 2019 <NAME>, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hyscale.builder.services.docker.impl;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.hyscale.commons.commands.provider.ImageCommandProvider;
import io.hyscale.builder.services.util.DockerImageUtil;
import io.hyscale.builder.services.util.ImageLogUtil;
import io.hyscale.builder.services.spring.DockerBinaryCondition;
import io.hyscale.commons.config.SetupConfig;
import io.hyscale.commons.constants.ToolConstants;
import io.hyscale.commons.models.CommandResult;
import io.hyscale.commons.models.ImageRegistry;
import io.hyscale.commons.utils.ImageMetadataProvider;
import io.hyscale.commons.utils.ObjectMapperFactory;
import io.hyscale.servicespec.commons.model.service.Image;
import io.hyscale.servicespec.commons.util.ImageUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
import io.hyscale.builder.services.config.ImageBuilderConfig;
import io.hyscale.builder.services.docker.HyscaleDockerClient;
import io.hyscale.builder.services.exception.ImageBuilderErrorCodes;
import io.hyscale.builder.core.models.DockerImage;
import io.hyscale.builder.core.models.ImageBuilderActivity;
import io.hyscale.commons.commands.CommandExecutor;
import io.hyscale.commons.exception.HyscaleException;
import io.hyscale.commons.logger.WorkflowLogger;
import io.hyscale.servicespec.commons.model.service.Dockerfile;
import io.hyscale.commons.models.Status;
import javax.annotation.PostConstruct;
@Component
@Conditional(DockerBinaryCondition.class)
public class DockerBinaryClient implements HyscaleDockerClient {
private static final Logger logger = LoggerFactory.getLogger(DockerBinaryClient.class);
@Autowired
private ImageCommandProvider imageCommandProvider;
@Autowired
private ImageMetadataProvider imageMetadataProvider;
@Autowired
private DockerImageUtil dockerImageUtil;
@Autowired
private ImageLogUtil imageLogUtil;
@Autowired
private ImageBuilderConfig imageBuilderConfig;
@PostConstruct
public void init() {
logger.debug("Using Docker Binary for Image Building");
}
@Override
public boolean isDockerRunning() {
String command = imageCommandProvider.dockerImages();
logger.debug("Docker Daemon running check command: {}", command);
return CommandExecutor.execute(command);
}
@Override
public boolean checkForDocker() {
String command = imageCommandProvider.dockerVersion();
logger.debug("Docker Installed check command: {}", command);
return CommandExecutor.execute(command);
}
@Override
public void deleteImages(List<String> imageIds, boolean force) {
if (imageIds == null || imageIds.isEmpty()) {
return;
}
boolean isSuccess = CommandExecutor
.execute(imageCommandProvider.removeDockerImages(imageIds.stream().collect(Collectors.toSet()), force));
logger.debug("Image clean up {}", isSuccess ? Status.DONE.getMessage() : Status.FAILED.getMessage());
}
@Override
public void deleteImage(String imageId, boolean force) {
if (StringUtils.isBlank(imageId)) {
return;
}
deleteImages(Arrays.asList(imageId), force);
}
@Override
public DockerImage build(Dockerfile dockerfile, String imageName, String tag,
Map<String, ImageRegistry> registryMap, String logfile, boolean isVerbose) throws HyscaleException {
WorkflowLogger.startActivity(ImageBuilderActivity.IMAGE_BUILD);
String buildPath = dockerfile.getPath() != null ? SetupConfig.getAbsolutePath(dockerfile.getPath()) : null;
String dockerfilePath = dockerfile.getDockerfilePath();
String dockerBuildCommand = imageCommandProvider.dockerBuildCommand(imageName, tag, dockerfilePath, buildPath,
dockerfile.getTarget(), dockerfile.getArgs());
logger.debug("Docker build command {}", dockerBuildCommand);
boolean status = logfile != null
? CommandExecutor.executeInDir(dockerBuildCommand, new File(logfile), buildPath)
: CommandExecutor.executeInDir(dockerBuildCommand, buildPath);
if (!status) {
WorkflowLogger.endActivity(Status.FAILED);
logger.error("Failed to build docker image");
} else {
WorkflowLogger.endActivity(Status.DONE);
}
if (isVerbose) {
imageLogUtil.readLogs(logfile, ImageBuilderActivity.BUILD_LOGS);
}
if (!status) {
throw new HyscaleException(ImageBuilderErrorCodes.FAILED_TO_BUILD_IMAGE);
}
DockerImage dockerImage = new DockerImage();
dockerImage.setName(imageName);
dockerImage.setTag(tag);
return dockerImage;
}
@Override
public String push(Image image, ImageRegistry imageRegistry, String logfile, boolean isVerbose)
throws HyscaleException {
String shaSum = null;
WorkflowLogger.startActivity(ImageBuilderActivity.IMAGE_PUSH);
String imageFullPath = ImageUtil.getImage(image);
String pushImageCommand = imageCommandProvider.dockerPush(imageFullPath);
boolean status = logfile == null ? CommandExecutor.execute(pushImageCommand)
: CommandExecutor.execute(pushImageCommand, new File(logfile));
if (!status) {
WorkflowLogger.endActivity(Status.FAILED);
logger.error("Failed to push docker image");
} else {
String inspectCommand = imageCommandProvider.dockerInspect(imageFullPath);
CommandResult result = CommandExecutor.executeAndGetResults(inspectCommand);
shaSum = getImageDigest(result);
WorkflowLogger.endActivity(Status.DONE);
}
if (isVerbose) {
imageLogUtil.readLogs(logfile, ImageBuilderActivity.IMAGE_PUSH_LOG);
}
if (!status) {
throw new HyscaleException(ImageBuilderErrorCodes.FAILED_TO_PUSH_IMAGE);
}
return shaSum;
}
@Override
public void pull(String image, ImageRegistry imageRegistry) throws HyscaleException {
WorkflowLogger.startActivity(ImageBuilderActivity.IMAGE_PULL);
if (StringUtils.isBlank(image)) {
WorkflowLogger.endActivity(Status.SKIPPING);
return;
}
try {
dockerImageUtil.pullImage(image);
} catch (HyscaleException e) {
WorkflowLogger.endActivity(Status.FAILED);
logger.error(e.toString());
throw e;
}
WorkflowLogger.endActivity(Status.DONE);
}
@Override
public void tag(String source, Image dest) throws HyscaleException {
WorkflowLogger.startActivity(ImageBuilderActivity.IMAGE_TAG);
if (StringUtils.isBlank(source)) {
WorkflowLogger.endActivity(Status.SKIPPING);
return;
}
try {
dockerImageUtil.tagImage(source, ImageUtil.getImage(dest));
} catch (HyscaleException e) {
WorkflowLogger.endActivity(Status.FAILED);
logger.error(e.toString());
throw e;
}
WorkflowLogger.endActivity(Status.DONE);
}
/**
* Gets latest digest from inspect image command result.
*
* @param result CommandResult obtained after executing docker inspect command.
* 1.result is null - null
* 2.result not null - null if no digests
* - last digest if digests exist
* @return digest latest digest from image command result.
*/
private String getImageDigest(CommandResult result) {
if (result == null || result.getExitCode() > 0 || StringUtils.isBlank(result.getCommandOutput())) {
return null;
}
ObjectMapper mapper = ObjectMapperFactory.jsonMapper();
try {
JsonNode node = mapper.readTree(result.getCommandOutput());
JsonNode digestNode = null;
if (node.isArray()) {
digestNode = node.get(0).get("RepoDigests");
} else {
digestNode = node.get("RepoDigests");
}
if (digestNode == null) {
return null;
}
List<String> digestList = mapper.convertValue(digestNode, new TypeReference<List<String>>() {
});
String latestRepoDigest = digestList.get(digestList.size() - 1);
if (StringUtils.isNotBlank(latestRepoDigest) && latestRepoDigest.contains(ToolConstants.AT_SIGN)) {
return latestRepoDigest.split(ToolConstants.AT_SIGN)[1];
}
} catch (IOException e) {
logger.debug("Error while processing image inspect results ", e);
}
return null;
}
@Override
public List<String> getImageIds(String imageName, Map<String, String> labels) throws HyscaleException {
String imageIdsAsString = CommandExecutor
.executeAndGetResults(imageCommandProvider.dockerImageIds(imageName, labels))
.getCommandOutput();
String[] imageIds = StringUtils.isNotBlank(imageIdsAsString) ? imageIdsAsString.split("\\s+") : null;
if (imageIds == null || imageIds.length == 0) {
logger.debug("No images found to clean from the host machine");
return Collections.emptyList();
}
// Need to preserve the order of output, hence a LinkedHashset
return new LinkedList<>(Arrays.asList(imageIds));
}
@Override
public void login(ImageRegistry imageRegistry) throws HyscaleException {
dockerImageUtil.dockerLogin(imageRegistry);
}
@Override
public boolean isLoginRequired() {
return true;
}
@Override
public boolean isCleanUpRequired(){
return true;
}
}
| 4,345 |
2,941 | <gh_stars>1000+
package software.amazon.awscdk.examples;
import java.util.Arrays;
import java.util.List;
import software.amazon.awscdk.core.Construct;
import software.amazon.awscdk.services.sns.Topic;
import software.amazon.awscdk.services.sns.subscriptions.SqsSubscription;
import software.amazon.awscdk.services.sqs.Queue;
import software.amazon.awscdk.services.sqs.QueueProps;
/** A sink queue is a queue aggregates messages published to any number of SNS topics. */
public class SinkQueue extends Construct {
private final Queue queue;
private final int expectedTopicCount;
private int actualTopicCount = 0;
/**
* Defines a SinkQueue.
*
* @param parent Parent construct
* @param name Logical name
* @param props Props
*/
public SinkQueue(final Construct parent, final String name, SinkQueueProps props) {
super(parent, name);
// ensure props is non-null
props = props != null ? props : SinkQueueProps.builder().build();
// defaults
QueueProps queueProps = props.getQueueProps();
this.expectedTopicCount =
props.getRequiredTopicCount() != null ? props.getRequiredTopicCount().intValue() : 0;
// WORKAROUND: https://github.com/awslabs/aws-cdk/issues/157
if (queueProps == null) {
queueProps = QueueProps.builder().build();
}
this.queue = new Queue(this, "Resource", queueProps);
}
/**
* Defines a SinkQueue with default props.
*
* @param parent Parent construct
* @param name Logical name
*/
public SinkQueue(final Construct parent, final String name) {
this(parent, name, null);
}
/**
* Subscribes this queue to receive messages published to the specified topics.
*
* @param topics The topics to subscribe to
*/
public void subscribe(final Topic... topics) {
for (Topic topic : topics) {
if (expectedTopicCount != 0 && actualTopicCount >= expectedTopicCount) {
throw new RuntimeException(
"Cannot add more topics to the sink. Maximum topics is configured to "
+ this.expectedTopicCount);
}
topic.addSubscription(new SqsSubscription(this.queue));
actualTopicCount++;
}
}
@Override
public List<String> validate() {
if (actualTopicCount < expectedTopicCount) {
return Arrays.asList(
"There are not enough subscribers to the sink. Expecting "
+ this.expectedTopicCount
+ ", actual is "
+ this.actualTopicCount);
}
return super.validate();
}
}
| 877 |
310 | {
"name": "Burp",
"description": "Software for vulnerability scanning and traffic interception.",
"url": "https://portswigger.net/burp/"
} | 43 |
348 | {"nom":"Lodes","circ":"8ème circonscription","dpt":"Haute-Garonne","inscrits":226,"abs":124,"votants":102,"blancs":8,"nuls":8,"exp":86,"res":[{"nuance":"REM","nom":"<NAME>","voix":53},{"nuance":"SOC","nom":"M. <NAME>","voix":33}]} | 94 |
3,083 | <filename>src/main/java/com/google/security/zynamics/binnavi/Gui/MainWindow/ProjectTree/Actions/CInsertTagAction.java<gh_stars>1000+
// Copyright 2011-2016 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Actions;
import com.google.security.zynamics.binnavi.Gui.MainWindow.Implementations.CTagFunctions;
import com.google.security.zynamics.binnavi.Tagging.CTag;
import com.google.security.zynamics.binnavi.Tagging.ITagManager;
import com.google.security.zynamics.zylib.types.trees.TreeNode;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
/**
* Action that can be used to insert new tags into a new tag manager.
*/
public final class CInsertTagAction extends AbstractAction {
/**
* Used for serialization.
*/
private static final long serialVersionUID = -8649696035201341391L;
/**
* Parent window used for dialogs.
*/
private final JFrame m_parent;
/**
* Tag manager where the tag is inserted.
*/
private final ITagManager m_tagManager;
/**
* Parent tag of the new tag.
*/
private final TreeNode<CTag> m_parentTag;
/**
* Name of the new tag.
*/
private final String m_name;
/**
* Creates a new action object.
*
* @param parent Parent window used for dialogs.
* @param tagManager Tag manager where the tag is inserted.
* @param tag Parent tag of the new tag.
* @param name Name of the new tag.
*/
public CInsertTagAction(final JFrame parent, final ITagManager tagManager,
final TreeNode<CTag> tag, final String name) {
super("Insert Tag");
m_parent = parent;
m_tagManager = tagManager;
m_parentTag = tag;
m_name = name;
putValue(MNEMONIC_KEY, (int) "HK_MENU_INSERT_TAG".charAt(0));
}
@Override
public void actionPerformed(final ActionEvent event) {
CTagFunctions.insertTag(m_parent, m_tagManager, m_parentTag, m_name);
}
}
| 814 |
671 | /*
* Copyright 2016 Copyright 2016 <NAME>
*
* 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 rx_activity_result2;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import androidx.annotation.Nullable;
public class RequestIntentSender extends Request {
private final IntentSender intentSender;
private final Intent fillInIntent;
private final int flagsMask, flagsValues, extraFlags;
private final Bundle options;
public RequestIntentSender(IntentSender intentSender, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, @Nullable Bundle options) {
super(null);
this.intentSender = intentSender;
this.fillInIntent = fillInIntent;
this.flagsMask = flagsMask;
this.flagsValues = flagsValues;
this.extraFlags = extraFlags;
this.options = options;
}
public IntentSender getIntentSender() {
return intentSender;
}
public Intent getFillInIntent() {
return fillInIntent;
}
public int getFlagsMask() {
return flagsMask;
}
public int getFlagsValues() {
return flagsValues;
}
public int getExtraFlags() {
return extraFlags;
}
public Bundle getOptions() {
return options;
}
}
| 610 |
5,169 | <reponame>Gantios/Specs
{
"name": "YLDragView",
"version": "0.0.1",
"summary": "YLDragView.",
"description": "拖拽视图、可移动视图、悬浮可拖动视图",
"homepage": "https://github.com/jianghat/YLDragView",
"license": "MIT",
"authors": {
"jiang": "<EMAIL>"
},
"platforms": {
"ios": "9.0"
},
"source": {
"git": "https://github.com/jianghat/YLDragView.git",
"tag": "0.0.1"
},
"source_files": "YLDragView.{swift}",
"frameworks": "UIKit",
"requires_arc": true
}
| 251 |
1,056 | <reponame>arusinha/incubator-netbeans
/*
* 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.netbeans.modules.websvc.saas.codegen.model;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.netbeans.modules.websvc.saas.model.CustomSaasMethod;
import org.netbeans.modules.websvc.saas.codegen.Constants.HttpMethodType;
import org.netbeans.modules.websvc.saas.codegen.Constants.MimeType;
import org.netbeans.modules.websvc.saas.codegen.model.ParameterInfo.ParamStyle;
import org.netbeans.modules.websvc.saas.codegen.util.Inflector;
import org.netbeans.modules.websvc.saas.codegen.util.Util;
import org.netbeans.modules.websvc.saas.model.jaxb.Artifact;
import org.netbeans.modules.websvc.saas.model.jaxb.Artifacts;
import org.netbeans.modules.websvc.saas.model.jaxb.Method.Input;
import org.netbeans.modules.websvc.saas.model.jaxb.Method.Output;
import org.netbeans.modules.websvc.saas.model.jaxb.Params.Param;
import org.netbeans.modules.websvc.saas.model.jaxb.SaasMetadata.CodeGen;
/**
*
* @author ayubkhan
*/
public class CustomClientSaasBean extends SaasBean {
public static final String ARTIFACT_TYPE_TEMPLATE = "template";
public static final String ARTIFACT_TYPE_LIB = "lib";
private String url;
private CustomSaasMethod m;
private Map<String, Map<String, String>> templates;
private Map<String, String> libs;
private boolean canGenerateJaxb;
private String serviceMethodName;
public CustomClientSaasBean(CustomSaasMethod m) throws IOException {
this(m, false);
}
public CustomClientSaasBean(CustomSaasMethod m, boolean isDropTargetWeb) throws IOException {
super(m.getSaas(), deriveResourceName(m), null,
deriveUriTemplate(m), new MimeType[]{MimeType.XML},
new String[]{"java.lang.String"}, //NOI18N
new HttpMethodType[]{HttpMethodType.GET});
this.m = m;
setIsDropTargetWeb(isDropTargetWeb);
init();
}
private void init() throws IOException {
setHttpMethod(HttpMethodType.GET);
if(m.getHref() != null)
setResourceClassTemplate(m.getHref());
findAuthentication(m);
List<MimeType> mimeTypes = new ArrayList<MimeType>();
try {
Output out = m.getOutput();
findSaasMediaType(mimeTypes, out.getMedia());
if(mimeTypes.size() > 0)
setMimeTypes(mimeTypes.toArray(new MimeType[mimeTypes.size()]));
} catch (Exception ex) {
throw new IOException(ex.getMessage());
}
templates = new HashMap<String, Map<String, String>>();
libs = new HashMap<String, String>();
CodeGen codegen = m.getSaas().getSaasMetadata().getCodeGen();
if(codegen != null) {
List<Artifacts> artifactsList = codegen.getArtifacts();
if(artifactsList != null) {
for(Artifacts artifacts: artifactsList) {
Map<String, String> artifactMap = new HashMap<String, String>();
String targets = artifacts.getTargets();
for(String target:targets.split(",")) {
addArtifactTemplates(target, artifactMap);
}
List<Artifact> artifactList = artifacts.getArtifact();
if(artifactList != null) {
for(Artifact artifact: artifactList) {
if(artifact.getRequires() != null) {
//TODO
}
String type = artifact.getType();
if(type == null)
throw new IOException("saas-metadata/code-gen/artifacts/artifact/@type value is null.");
String id = artifact.getId();
String artifactUrl = artifact.getUrl();
if(id == null || artifactUrl == null)
throw new IOException("saas-metadata/code-gen/artifacts/artifact/@id|@url value is null.");
if(type.equals(ARTIFACT_TYPE_TEMPLATE)) {
if(artifactMap.get(id) != null)
throw new IOException("saas-metadata/code-gen/artifacts/artifact/@"+id+" already exists.");
artifactMap.put(id, artifactUrl);
} else if(type.equals(ARTIFACT_TYPE_LIB)) {
if(libs.get(id) != null)
throw new IOException("saas-metadata/code-gen/artifacts/artifact/@"+id+" already exists.");
libs.put(id, artifactUrl);
}
}
}
}
}
}
}
public String getSaasServiceMethodName() {
if(serviceMethodName == null) {
serviceMethodName = Util.deriveMethodName(getMethod().getName());
serviceMethodName = serviceMethodName.substring(0, 1).toLowerCase() + serviceMethodName.substring(1);
}
return serviceMethodName;
}
public CustomSaasMethod getMethod() {
return m;
}
protected List<ParameterInfo> initInputParameters() {
List<ParameterInfo> inputParams = new ArrayList<ParameterInfo>();
Input in = m.getInput();
if(in != null && in.getParams() != null && in.getParams().getParam() != null) {
List<Param> params = in.getParams().getParam();
findSaasParams(inputParams, params);
for(ParameterInfo p:inputParams) {
p.setStyle(ParamStyle.QUERY);
}
}
return inputParams;
}
public String getUrl() {
return this.url;
}
protected static String deriveResourceName(CustomSaasMethod m) {
String name = m.getName();
if(m.getHref() != null && !m.getHref().trim().equals(""))
name = m.getHref();
return Inflector.getInstance().camelize(name + GenericResourceBean.RESOURCE_SUFFIX);
}
protected static String deriveUriTemplate(CustomSaasMethod m) {
String name = m.getName();
if(m.getHref() != null && !m.getHref().trim().equals(""))
name = m.getHref();
return Inflector.getInstance().camelize(name, true) + "/"; //NOI18N
}
public Map<String, String> getArtifactLibs() {
return libs;
}
public void setArtifactLibs(Map<String, String> libs) {
this.libs = libs;
}
public Map<String, String> getArtifactTemplates(String target) {
return this.templates.get(target);
}
public void addArtifactTemplates(String target, Map<String, String> templates) {
this.templates.put(target, templates);
}
public boolean canGenerateJAXBUnmarshaller() {
return canGenerateJaxb;
}
public void setCanGenerateJAXBUnmarshaller(boolean canGenerateJaxb) {
this.canGenerateJaxb = canGenerateJaxb;
}
}
| 3,647 |
598 | from enum import Enum
class MessageTag(Enum):
ROLLOUT = "rollout"
CHOOSE_ACTION = "choose_action"
ACTION = "action"
ABORT_ROLLOUT = "abort_rollout"
TRAIN = "train"
FINISHED = "finished"
EXIT = "exit"
class PayloadKey(Enum):
ACTION = "action"
AGENT_ID = "agent_id"
ROLLOUT_INDEX = "rollout_index"
TIME_STEP = "time_step"
METRICS = "metrics"
DETAILS = "details"
STATE = "state"
TRAINING = "training"
MODEL = "model"
EXPLORATION_PARAMS = "exploration_params"
| 234 |
460 | #include "../../../src/declarative/graphicsitems/qdeclarativelistview_p.h"
| 29 |
831 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.profilers.cpu;
import com.android.tools.profiler.proto.Cpu;
import org.jetbrains.annotations.NotNull;
public enum ProfilingTechnology {
ART_SAMPLED("Java Method Sample Recording",
"Samples Java code using Android Runtime."),
ART_INSTRUMENTED("Java Method Trace Recording",
"Instruments Java code using Android Runtime."),
// This technology used by imported ART Trace configurations.
// "Unspecified" because there is no way of telling if the trace was generated using sampling or instrumentations.
ART_UNSPECIFIED("Java Method Recording",
"Profiles Java code using Android Runtime."),
SIMPLEPERF("C/C++ Function Recording",
"Samples native code using simpleperf.",
"Available for Android 8.0 (API level 26) and higher."),
SYSTEM_TRACE("System Trace Recording",
"Traces Java and native code at the Android platform level.",
"Available for Android 7.0 (API level 24) and higher.");
@NotNull private final String myName;
/**
* Description of the technology, e.g it is used in {@code RecordingInitiatorPane}.
*/
@NotNull private final String myDescription;
/**
* An extra context for the description of the technology, e.g it is used in {@code CpuProfilingConfigPane}.
*/
@NotNull private final String myExtraDescription;
ProfilingTechnology(@NotNull String name, @NotNull String description, @NotNull String extraDescription) {
myName = name;
myDescription = description;
myExtraDescription = extraDescription;
}
ProfilingTechnology(@NotNull String name, @NotNull String description) {
this(name, description, "");
}
@NotNull
public String getName() {
return myName;
}
@NotNull
public String getDescription() {
return myDescription;
}
@NotNull
public String getLongDescription() {
return String.format("<html>%s %s</html>", myDescription, myExtraDescription);
}
@NotNull
public Cpu.CpuTraceType getType() {
switch (this) {
case ART_SAMPLED:
return Cpu.CpuTraceType.ART;
case ART_INSTRUMENTED:
return Cpu.CpuTraceType.ART;
case ART_UNSPECIFIED:
return Cpu.CpuTraceType.ART;
case SIMPLEPERF:
return Cpu.CpuTraceType.SIMPLEPERF;
case SYSTEM_TRACE:
return Cpu.CpuTraceType.ATRACE;
}
throw new IllegalArgumentException("Unreachable code");
}
@NotNull
public Cpu.CpuTraceMode getMode() {
switch (this) {
case ART_SAMPLED:
return Cpu.CpuTraceMode.SAMPLED;
case ART_INSTRUMENTED:
return Cpu.CpuTraceMode.INSTRUMENTED;
case ART_UNSPECIFIED:
return Cpu.CpuTraceMode.UNSPECIFIED_MODE;
case SIMPLEPERF:
return Cpu.CpuTraceMode.SAMPLED;
case SYSTEM_TRACE:
return Cpu.CpuTraceMode.INSTRUMENTED;
}
throw new IllegalArgumentException("Unreachable code");
}
@NotNull
public static ProfilingTechnology fromTypeAndMode(@NotNull Cpu.CpuTraceType type,
@NotNull Cpu.CpuTraceMode mode) {
switch (type) {
case ART:
if (mode == Cpu.CpuTraceMode.SAMPLED) {
return ART_SAMPLED;
}
else if (mode == Cpu.CpuTraceMode.INSTRUMENTED) {
return ART_INSTRUMENTED;
}
else {
return ART_UNSPECIFIED;
}
case SIMPLEPERF:
return SIMPLEPERF;
case ATRACE: // fall-through
case PERFETTO:
return SYSTEM_TRACE;
default:
throw new IllegalStateException("Error while trying to get the name of an unknown profiling configuration");
}
}
@NotNull
public static ProfilingTechnology fromConfig(@NotNull ProfilingConfiguration config) {
return fromTypeAndMode(config.getTraceType(), config.getMode());
}
}
| 1,674 |
1,006 | /****************************************************************************
* drivers/usbdev/cdcacm.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.
*
****************************************************************************/
#ifndef __DRIVERS_USBDEV_CDCACM_H
#define __DRIVERS_USBDEV_CDCACM_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdint.h>
#include <nuttx/usb/usbdev.h>
#include <nuttx/usb/cdc.h>
#include <nuttx/usb/usbdev_trace.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Configuration ************************************************************/
/* If the serial device is configured as part of a composite device than both
* CONFIG_USBDEV_COMPOSITE and CONFIG_CDCACM_COMPOSITE must be defined.
*/
#ifndef CONFIG_USBDEV_COMPOSITE
# undef CONFIG_CDCACM_COMPOSITE
#endif
#if defined(CONFIG_CDCACM_COMPOSITE) && !defined(CONFIG_CDCACM_STRBASE)
# define CONFIG_CDCACM_STRBASE (0)
#endif
#if defined(CONFIG_CDCACM_COMPOSITE) && !defined(CONFIG_COMPOSITE_IAD)
# warning "CONFIG_COMPOSITE_IAD may be needed"
#endif
/* Packet and request buffer sizes */
#ifndef CONFIG_CDCACM_COMPOSITE
# ifndef CONFIG_CDCACM_EP0MAXPACKET
# define CONFIG_CDCACM_EP0MAXPACKET 64
# endif
#endif
/* Interface IDs. If the serial driver is built as a component of a
* composite device, then the interface IDs may need to be offset.
*/
#ifndef CONFIG_CDCACM_COMPOSITE
# undef CONFIG_CDCACM_IFNOBASE
# define CONFIG_CDCACM_IFNOBASE (0)
#endif
#ifndef CONFIG_CDCACM_IFNOBASE
# define CONFIG_CDCACM_IFNOBASE (0)
#endif
/* Descriptors **************************************************************/
/* These settings are not modifiable via the NuttX configuration */
#define CDC_VERSIONNO 0x0110 /* CDC version number 1.10 (BCD) */
#define CDCACM_CONFIGIDNONE (0) /* Config ID means to return to address mode */
/* Interface IDs:
*
* CDCACM_NINTERFACES Two interfaces
* CDCACM_NOTIFID ID of the notifier interface
* CDCACM_NOTALTIFID No alternate for the notifier interface
* CDCACM_DATAIFID ID of the data interface
* CDCACM_DATAALTIFID No alternate for the data interface
*/
#define CDCACM_NOTALTIFID (0)
#define CDCACM_DATAALTIFID (0)
/* Buffer big enough for any of our descriptors (the config descriptor is the
* biggest).
*/
#define CDCACM_MXDESCLEN (64)
#define CDCACM_MAXSTRLEN (CDCACM_MXDESCLEN-2)
/* Device descriptor values */
#define CDCACM_VERSIONNO (0x0101) /* Device version number 1.1 (BCD) */
/* String language */
#define CDCACM_STR_LANGUAGE (0x0409) /* en-us */
/* Descriptor strings. If there serial device is part of a composite device
* then the manufacturer, product, and serial number strings will be provided
* by the composite logic.
*/
#ifndef CONFIG_CDCACM_COMPOSITE
# define CDCACM_MANUFACTURERSTRID (1)
# define CDCACM_PRODUCTSTRID (2)
# define CDCACM_SERIALSTRID (3)
# define CDCACM_CONFIGSTRID (4)
# define CDCACM_LASTBASESTRID (4)
# define CDCACM_STRBASE (0)
#else
# define CDCACM_STRBASE CONFIG_CDCACM_STRBASE
# define CDCACM_LASTBASESTRID CONFIG_CDCACM_STRBASE
#endif
/* These string IDs only exist if a user-defined string is provided */
#ifdef CONFIG_CDCACM_NOTIFSTR
# define CDCACM_NOTIFSTRID (CDCACM_LASTBASESTRID + 1)
#else
# define CDCACM_NOTIFSTRID CDCACM_LASTBASESTRID
#endif
#ifdef CONFIG_CDCACM_DATAIFSTR
# define CDCACM_DATAIFSTRID (CDCACM_NOTIFSTRID + 1)
#else
# define CDCACM_DATAIFSTRID CDCACM_NOTIFSTRID
#endif
#define CDCACM_LASTSTRID CDCACM_DATAIFSTRID
#define CDCACM_NSTRIDS (CDCACM_LASTSTRID - CDCACM_STRBASE)
/* Endpoint configuration ***************************************************/
#define CDCACM_MKEPINTIN(desc) (USB_DIR_IN | (desc)->epno[CDCACM_EP_INTIN_IDX])
#define CDCACM_EPINTIN_ATTR (USB_EP_ATTR_XFER_INT)
#define CDCACM_MKEPBULKIN(desc) (USB_DIR_IN | (desc)->epno[CDCACM_EP_BULKIN_IDX])
#define CDCACM_EPOUTBULK_ATTR (USB_EP_ATTR_XFER_BULK)
#define CDCACM_MKEPBULKOUT(desc) ((desc)->epno[CDCACM_EP_BULKOUT_IDX])
#define CDCACM_EPINBULK_ATTR (USB_EP_ATTR_XFER_BULK)
/* Device driver definitions ************************************************/
/* A CDC/ACM device is specific by a minor number in the range of 0-255.
* This maps to a character device at /dev/ttyACMx, x=0..255.
*/
#define CDCACM_DEVNAME_FORMAT "/dev/ttyACM%d"
#define CDCACM_DEVNAME_SIZE 16
/* Misc Macros **************************************************************/
/* MIN/MAX macros */
#ifndef MIN
# define MIN(a,b) ((a)<(b)?(a):(b))
#endif
#ifndef MAX
# define MAX(a,b) ((a)>(b)?(a):(b))
#endif
/* Trace values *************************************************************/
#define CDCACM_CLASSAPI_SETUP TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_SETUP)
#define CDCACM_CLASSAPI_SHUTDOWN TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_SHUTDOWN)
#define CDCACM_CLASSAPI_ATTACH TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_ATTACH)
#define CDCACM_CLASSAPI_DETACH TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_DETACH)
#define CDCACM_CLASSAPI_IOCTL TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_IOCTL)
#define CDCACM_CLASSAPI_RECEIVE TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_RECEIVE)
#define CDCACM_CLASSAPI_RXINT TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_RXINT)
#define CDCACM_CLASSAPI_RXAVAILABLE TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_RXAVAILABLE)
#define CDCACM_CLASSAPI_SEND TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_SEND)
#define CDCACM_CLASSAPI_TXINT TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_TXINT)
#define CDCACM_CLASSAPI_TXREADY TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_TXREADY)
#define CDCACM_CLASSAPI_TXEMPTY TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_TXEMPTY)
#define CDCACM_CLASSAPI_FLOWCONTROL TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_FLOWCONTROL)
/****************************************************************************
* Public Types
****************************************************************************/
enum cdcacm_epdesc_e
{
CDCACM_EPINTIN = 0, /* Interrupt IN endpoint descriptor */
CDCACM_EPBULKOUT, /* Bulk OUT endpoint descriptor */
CDCACM_EPBULKIN /* Bulk IN endpoint descriptor */
};
/****************************************************************************
* Public Data
****************************************************************************/
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
/****************************************************************************
* Name: cdcacm_mkstrdesc
*
* Description:
* Construct a string descriptor
*
****************************************************************************/
int cdcacm_mkstrdesc(uint8_t id, struct usb_strdesc_s *strdesc);
/****************************************************************************
* Name: cdcacm_getdevdesc
*
* Description:
* Return a pointer to the raw device descriptor
*
****************************************************************************/
#ifndef CONFIG_CDCACM_COMPOSITE
FAR const struct usb_devdesc_s *cdcacm_getdevdesc(void);
#endif
/****************************************************************************
* Name: cdcacm_copy_epdesc
*
* Description:
* Copies the requested Endpoint Description into the buffer given.
* Returns the number of Bytes filled in (sizeof(struct usb_epdesc_s)).
*
****************************************************************************/
int cdcacm_copy_epdesc(enum cdcacm_epdesc_e epid,
FAR struct usb_epdesc_s *epdesc,
FAR struct usbdev_devinfo_s *devinfo,
bool hispeed);
/****************************************************************************
* Name: cdcacm_mkcfgdesc
*
* Description:
* Construct the configuration descriptor
*
****************************************************************************/
#ifdef CONFIG_USBDEV_DUALSPEED
int16_t cdcacm_mkcfgdesc(FAR uint8_t *buf,
FAR struct usbdev_devinfo_s *devinfo,
uint8_t speed, uint8_t type);
#else
int16_t cdcacm_mkcfgdesc(FAR uint8_t *buf,
FAR struct usbdev_devinfo_s *devinfo);
#endif
/****************************************************************************
* Name: cdcacm_getqualdesc
*
* Description:
* Return a pointer to the raw qual descriptor
*
****************************************************************************/
#if !defined(CONFIG_CDCACM_COMPOSITE) && defined(CONFIG_USBDEV_DUALSPEED)
FAR const struct usb_qualdesc_s *cdcacm_getqualdesc(void);
#endif
#endif /* __DRIVERS_USBDEV_CDCACM_H */
| 3,565 |
312 | # Copyright (C) 2004-2011, Parrot Foundation.
class Foo:
def __init__(self):
self.i = 10
self.j = 20
def I(self):
return self.i
def J(self):
return self.j
class main:
o = Foo()
for i in range(1,500001):
x = o.I()
y = o.J()
print o.I()
| 127 |
5,079 | <reponame>rohankumardubey/hue<gh_stars>1000+
# Generated by Django 3.2.4 on 2021-07-13 01:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('desktop', '0012_connector_interface'),
]
operations = [
migrations.AlterField(
model_name='document2',
name='is_trashed',
field=models.BooleanField(db_index=True, default=False, verbose_name='True if trashed'),
),
]
| 213 |
560 | <gh_stars>100-1000
/*
* Copyright (c) 2017 <NAME> <<EMAIL>>
* All Rights Reserved.
*/
package me.zhanghai.android.douya.app;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import android.text.TextUtils;
import java.io.FileInputStream;
import java.io.InputStream;
import me.zhanghai.android.douya.util.FileTypeUtils;
public class ImageTypeFileProvider extends FileProvider {
@Override
public String getType(@NonNull Uri uri) {
String type = super.getType(uri);
if (!TextUtils.equals(type, "application/octet-stream")) {
return type;
}
try (ParcelFileDescriptor parcelFileDescriptor = openFile(uri, "r")) {
if (parcelFileDescriptor == null) {
return type;
}
try (InputStream inputStream = new FileInputStream(
parcelFileDescriptor.getFileDescriptor())) {
type = FileTypeUtils.getImageMimeType(inputStream, type);
}
} catch (Exception e) {
e.printStackTrace();
}
return type;
}
}
| 506 |
424 | /*
* Copyright (C) 2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.vertx.sqlclient;
import io.vertx.codegen.annotations.GenIgnore;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collector;
/**
* A query for a prepared statement allowing parameterized execution of the query, this query will use
* a prepared statement.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
@VertxGen
public interface PreparedQuery<T> extends Query<T> {
/**
* Execute the query.
*
* @param handler the handler receiving the response
*/
void execute(Tuple tuple, Handler<AsyncResult<T>> handler);
/**
* Like {@link #execute(Handler)} but returns a {@code Future} of the asynchronous result
*/
Future<T> execute(Tuple tuple);
/**
* Execute the query with a batch of tuples.
*
* @param batch the batch of tuples
* @param handler the handler receiving the response
*/
void executeBatch(List<Tuple> batch, Handler<AsyncResult<T>> handler);
/**
* Like {@link #executeBatch(List, Handler)} but returns a {@code Future} of the asynchronous result
*/
Future<T> executeBatch(List<Tuple> batch);
/**
* Use the specified {@code collector} for collecting the query result to {@code <R>}.
*/
@GenIgnore
<R> PreparedQuery<SqlResult<R>> collecting(Collector<Row, ?, R> collector);
/**
* Use the specified {@code mapper} for mapping {@link Row} to {@code <U>}.
*/
<U> PreparedQuery<RowSet<U>> mapping(Function<Row, U> mapper);
}
| 686 |
1,144 | package de.metas.printing.client.encoder;
/*
* #%L
* de.metas.printing.esb.client
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import de.metas.printing.esb.api.PrintPackage;
import de.metas.printing.esb.api.PrintPackageInfo;
public class BeanEncoderTest
{
private final IBeanEnconder[] parsers = new IBeanEnconder[] {
new JsonBeanEncoder()
};
@Test
public void parsePrintPackage_test01()
{
final PrintPackage printPackage = new PrintPackage();
printPackage.setTransactionId("testTrx");
printPackage.setPrintPackageId("456");
printPackage.setPageCount(10);
printPackage.setFormat("PDF");
final List<PrintPackageInfo> printPackageInfos = new ArrayList<PrintPackageInfo>();
printPackage.setPrintPackageInfos(printPackageInfos);
{
final PrintPackageInfo info = new PrintPackageInfo();
info.setPrintService("service01");
info.setTray("tray01");
info.setPageFrom(1);
info.setPageTo(3);
printPackageInfos.add(info);
}
{
final PrintPackageInfo info = new PrintPackageInfo();
info.setPrintService("service02");
info.setTray("tray02");
info.setPageFrom(1);
info.setPageTo(3);
printPackageInfos.add(info);
}
final String printPackageExpectedStr = printPackage.toString();
for (final IBeanEnconder parser : parsers)
{
final byte[] data = parser.encode(printPackage); // transport data
final PrintPackage printPackageActual = parser.decodeBytes(data, PrintPackage.class);
final String printPackageActualStr = printPackageActual.toString();
Assert.assertEquals("Invalid data produced by parser " + parser, printPackageExpectedStr, printPackageActualStr);
}
}
}
| 794 |
739 | package org.fxmisc.richtext.keyboard;
import com.nitorcreations.junit.runners.NestedRunner;
import javafx.scene.Scene;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.stage.Stage;
import org.fxmisc.flowless.VirtualizedScrollPane;
import org.fxmisc.richtext.CodeArea;
import org.fxmisc.richtext.InlineCssTextAreaAppTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.testfx.framework.junit.ApplicationTest;
import static javafx.scene.input.KeyCode.*;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assume.assumeFalse;
@RunWith(NestedRunner.class)
public class CutCopyPasteTests extends InlineCssTextAreaAppTest {
String text = "text";
String beginning = "Once upon a time, ";
String middle = "a princess was saved";
String end = " by a knight.";
String fullText = beginning + middle + end;
@Override
public void start(Stage stage) throws Exception {
super.start(stage);
area.replaceText(fullText);
}
public class When_Nothing_Is_Selected {
@Before
public void insureSelectionIsEmpty() {
area.moveTo(beginning.length());
assertTrue(area.getSelectedText().isEmpty());
}
public class Nothing_Is_Stored_In_Clipboard_When_Copy_Via {
private void runAssert() {
interact(() -> assertFalse(Clipboard.getSystemClipboard().hasString()));
}
@Before
public void insureClipboardHasNoContent() {
interact(() -> Clipboard.getSystemClipboard().clear());
}
@Test
public void copy() {
assumeFalse(USING_AWT_ADAPTER && IS_WINDOWS);
press(COPY);
runAssert();
}
@Test
public void shortcut_c() {
press(SHORTCUT, C);
runAssert();
}
@Test
public void shortcut_insert() {
press(SHORTCUT, INSERT);
runAssert();
}
}
public class Nothing_Is_Removed_In_Area_When_Cut_Via {
private void runAssert() {
assertEquals(fullText, area.getText());
}
@Test
public void cut() {
assumeFalse(USING_AWT_ADAPTER && IS_WINDOWS);
press(CUT);
runAssert();
}
@Test
public void shortcut_x() {
press(SHORTCUT, X);
runAssert();
}
@Test
public void shift_delete() {
press(SHIFT, DELETE);
runAssert();
}
}
public class Text_Is_Inserted_In_Area_When_Paste_Via {
private void runAssert() {
assertEquals(beginning + text + middle + end, area.getText());
}
@Before
public void storeTextInClipboard() {
interact(() -> {
ClipboardContent content = new ClipboardContent();
content.putString(text);
Clipboard.getSystemClipboard().setContent(content);
});
}
@Test
public void paste() {
// this test fails on Linux; Windows is untested
// so for now, only run on Mac
// TODO: update if test succeeds on Windows, too
run_only_on_mac();
press(PASTE);
runAssert();
}
@Test
public void shortcut_v() {
press(SHORTCUT, V);
runAssert();
}
@Test
public void shift_insert() {
press(SHIFT, INSERT);
runAssert();
}
}
}
public class When_Text_Is_Selected {
int startMiddle = beginning.length();
int endMiddle = startMiddle + middle.length();
@Before
public void selectMiddleAndClearClipboard() {
area.selectRange(startMiddle, endMiddle);
assertEquals(middle, area.getSelectedText());
interact(() -> Clipboard.getSystemClipboard().clear());
}
public class Selection_Is_Stored_In_Clipboard_When_Copy_Via {
private void runAssert() {
interact(() -> {
assertTrue(Clipboard.getSystemClipboard().hasString());
assertEquals(middle, Clipboard.getSystemClipboard().getString());
});
}
@Test
public void copy() {
// this test fails on Linux; Windows is untested
// so for now, only run on Mac
// TODO: update if test succeeds on Windows, too
run_only_on_mac();
press(COPY);
runAssert();
}
@Test
public void shortcut_c() {
press(SHORTCUT, C);
runAssert();
}
@Test
public void shortcut_insert() {
press(SHORTCUT, INSERT);
runAssert();
}
}
public class Selection_Is_Removed_And_Stored_In_Clipboard_When_Cut_Via {
private void runAssert() {
assertEquals(beginning + end, area.getText());
interact(() -> {
assertTrue(Clipboard.getSystemClipboard().hasString());
assertEquals(middle, Clipboard.getSystemClipboard().getString());
});
}
@Test
public void cut() {
// this test fails on Linux; Windows is untested
// so for now, only run on Mac
// TODO: update if test succeeds on Windows, too
run_only_on_mac();
press(CUT);
runAssert();
}
@Test
public void shortcut_x() {
press(SHORTCUT, X);
runAssert();
}
@Test
public void shift_delete() {
press(SHIFT, DELETE);
runAssert();
}
}
public class Selection_Is_Replaced_In_Area_When_Paste_Via {
@Before
public void storeTextInClipboard() {
interact(() -> {
ClipboardContent content = new ClipboardContent();
content.putString(text);
Clipboard.getSystemClipboard().setContent(content);
});
}
private void runAssert() {
assertEquals(beginning + text + end, area.getText());
}
@Test
public void paste() {
// this test fails on Linux; Windows is untested
// so for now, only run on Mac
// TODO: update if test succeeds on Windows, too
run_only_on_mac();
press(PASTE);
runAssert();
}
@Test
public void shortcut_v() {
press(SHORTCUT, V);
runAssert();
}
@Test
public void shift_insert() {
press(SHIFT, INSERT);
runAssert();
}
}
}
public class MiscellaneousCases extends ApplicationTest {
CodeArea area;
@Override
public void start(Stage primaryStage) throws Exception {
area = new CodeArea("abc\ndef\nghi");
VirtualizedScrollPane<CodeArea> vsPane = new VirtualizedScrollPane<>(area);
Scene scene = new Scene(vsPane, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public class When_User_Makes_Selection_Ending_In_Newline_Character {
@Before
public void setup() {
interact(() -> area.selectRange(2, 4));
}
@Test
public void copying_and_pasting_should_not_throw_exception() {
interact(area::copy);
interact(area::paste);
}
}
}
} | 4,411 |
6,215 | <reponame>OTRI-Unipd/OTRI-airbyte
{
"_airbyte_another.postgres_has_a_64_characters_limit_to_table_names_but_other_destinations_are_fine.postgres_has_a_64_characters_limit_to_table_names_but_other_destinations_are_fine": {
"file": "_airbyte_another_postgres_has_a_64_characters_limit_to_table_names_but_other_destinations_are_fine",
"schema": "_airbyte_another",
"table": "postgres_has_a_64_characters_limit_to_table_names_but_other_destinations_are_fine"
},
"_airbyte_schema_test.postgres_has_a_64_characters_and_not_more_limit_to_table_names_but_other_destinations_are_fine.postgres_has_a_64_characters_and_not_more_limit_to_table_names_but_other_destinations_are_fine": {
"file": "postgres_has_a_64_characters_and_not_more_limit_to_table_names_but_other_destinations_are_fine",
"schema": "_airbyte_schema_test",
"table": "postgres_has_a_64_characters_and_not_more_limit_to_table_names_but_other_destinations_are_fine"
},
"_airbyte_schema_test.postgres_has_a_64_characters_limit_to_table_names_but_other_destinations_are_fine.postgres_has_a_64_characters_limit_to_table_names_but_other_destinations_are_fine": {
"file": "_airbyte_schema_test_postgres_has_a_64_characters_limit_to_table_names_but_other_destinations_are_fine",
"schema": "_airbyte_schema_test",
"table": "postgres_has_a_64_characters_limit_to_table_names_but_other_destinations_are_fine"
},
"another.postgres_has_a_64_characters_limit_to_table_names_but_other_destinations_are_fine.postgres_has_a_64_characters_limit_to_table_names_but_other_destinations_are_fine": {
"file": "another_postgres_has_a_64_characters_limit_to_table_names_but_other_destinations_are_fine",
"schema": "another",
"table": "postgres_has_a_64_characters_limit_to_table_names_but_other_destinations_are_fine"
},
"schema_test.postgres_has_a_64_characters_and_not_more_limit_to_table_names_but_other_destinations_are_fine.postgres_has_a_64_characters_and_not_more_limit_to_table_names_but_other_destinations_are_fine": {
"file": "postgres_has_a_64_characters_and_not_more_limit_to_table_names_but_other_destinations_are_fine",
"schema": "schema_test",
"table": "postgres_has_a_64_characters_and_not_more_limit_to_table_names_but_other_destinations_are_fine"
},
"schema_test.postgres_has_a_64_characters_limit_to_table_names_but_other_destinations_are_fine.postgres_has_a_64_characters_limit_to_table_names_but_other_destinations_are_fine": {
"file": "schema_test_postgres_has_a_64_characters_limit_to_table_names_but_other_destinations_are_fine",
"schema": "schema_test",
"table": "postgres_has_a_64_characters_limit_to_table_names_but_other_destinations_are_fine"
}
}
| 1,092 |
410 | #include "Precompiled.h"
#include "Math/Math.h"
#include "SIMD/SIMD.h"
#include "Core/CVars.h"
#include "Sound/SoundSystem.h"
BE_NAMESPACE_BEGIN
static const int MaxSources = 32;
static CVar s_khz("s_khz", "44", CVar::Flag::Integer | CVar::Flag::Archive, "");
static CVar s_doppler("s_doppler", "1.0", CVar::Flag::Float | CVar::Flag::Archive, "");
static CVar s_rolloff("s_rolloff", "2.0", CVar::Flag::Float | CVar::Flag::Archive, "");
bool SoundSystem::InitDevice(void *windowHandle) {
BE_LOG("Initializing OpenAL...\n");
// Verify that a given extension is available for the current context
ALboolean enumeration = alcIsExtensionPresent(nullptr, "ALC_ENUMERATION_EXT");
if (enumeration == AL_FALSE) {
BE_WARNLOG("OpenAL enumeration extension not available\n");
}
// Retrieve a list of available devices
// Each device name is separated by a single nullptr character
// and the list is terminated with 2 nullptr characters
const ALCchar *deviceNameList = alcGetString(nullptr, ALC_DEVICE_SPECIFIER);
const ALCchar *deviceNamePtr = deviceNameList;
BE_LOG("OpenAL devices: \n");
while (1) {
BE_LOG("...%s\n", deviceNamePtr);
size_t nextOffset = strlen(deviceNamePtr);
if (!deviceNamePtr[nextOffset]) {
break;
}
deviceNamePtr += nextOffset;
}
// Retrieve the default device name
const ALCchar *defaultDeviceName = alcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER);
// Reset the error stack
alGetError();
// Open the default device
BE_LOG("...opening OpenAL device: ");
alDevice = alcOpenDevice(defaultDeviceName);
if (!alDevice) {
BE_LOG("failed\n");
return false;
}
BE_LOG("ok\n");
// Get the OpenAL version
ALCint majorVersion, minorVersion;
alcGetIntegerv(alDevice, ALC_MAJOR_VERSION, 1, &majorVersion);
alcGetIntegerv(alDevice, ALC_MINOR_VERSION, 1, &minorVersion);
// Create context
BE_LOG("...creating OpenAL context: ");
#if defined(__WIN32__)
int attrs[] = {
ALC_FREQUENCY, 44100,
ALC_STEREO_SOURCES, 4,
0, 0
};
alContext = alcCreateContext(alDevice, attrs);
#else
alContext = alcCreateContext(alDevice, 0);
#endif
if (!alContext) {
alcCloseDevice(alDevice);
BE_LOG("failed\n");
return false;
}
BE_LOG("ok\n");
// Set active context
BE_LOG("...make current context: ");
if (!alcMakeContextCurrent(alContext)) {
alcDestroyContext(alContext);
alcCloseDevice(alDevice);
BE_LOG("failed\n");
return false;
}
BE_LOG("ok\n");
BE_LOG("OpenAL vendor: %s\n", alGetString(AL_VENDOR));
BE_LOG("OpenAL renderer: %s\n", alGetString(AL_RENDERER));
BE_LOG("OpenAL version: %s\n", alGetString(AL_VERSION));
BE_LOG("OpenAL extensions: %s\n", alGetString(AL_EXTENSIONS));
ALCint freq, monoSources, stereoSources, refresh, sync;
alcGetIntegerv(alDevice, ALC_FREQUENCY, 1, &freq);
alcGetIntegerv(alDevice, ALC_MONO_SOURCES, 1, &monoSources);
alcGetIntegerv(alDevice, ALC_STEREO_SOURCES, 1, &stereoSources);
alcGetIntegerv(alDevice, ALC_REFRESH, 1, &refresh);
alcGetIntegerv(alDevice, ALC_SYNC, 1, &sync);
alListenerf(AL_GAIN, 0.99f);
alDistanceModel(AL_LINEAR_DISTANCE_CLAMPED);
//alDopplerFactor(1.0); // 1.2 = exaggerate the pitch shift by 20%
//alDopplerVelocity(343.0f); // m/s this may need to be scaled at some point
for (int sourceIndex = 0; sourceIndex < MaxSources; sourceIndex++) {
ALuint alSourceId;
alGenSources((ALuint)1, &alSourceId);
ALenum error = alGetError();
if (error == AL_NO_ERROR) {
SoundSource *source = new SoundSource;
source->alSourceId = alSourceId;
sources.Append(source);
freeSources.Append(source);
} else {
break;
}
}
return true;
}
void SoundSystem::ShutdownDevice() {
BE_LOG("Shutting down OpenAL...\n");
for (int sourceIndex = 0; sourceIndex < sources.Count(); sourceIndex++) {
SoundSource *source = sources[sourceIndex];
alSourceStop(source->alSourceId);
alDeleteSources(1, &source->alSourceId);
delete source;
}
sources.Clear();
freeSources.Clear();
alcMakeContextCurrent(nullptr);
alcDestroyContext(alContext);
alcCloseDevice(alDevice);
}
void SoundSystem::PlaceListenerInternal(const Vec3 &position, const Vec3 &forward, const Vec3 &up) {
ALfloat listenerOri[] = { forward.x, forward.y, forward.z, up.x, up.y, up.z };
//ALfloat listenerVel[] = { 0, 0, 0 };
alListener3f(AL_POSITION, position.x, position.y, position.z);
alListenerfv(AL_ORIENTATION, listenerOri);
//alListenerfv(AL_VELOCITY, listenerVel);
}
BE_NAMESPACE_END
| 2,066 |
521 | /* $Id: UIThreadPool.h $ */
/** @file
* VBox Qt GUI - UIThreadPool and UITask classes declaration.
*/
/*
* Copyright (C) 2013-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#ifndef ___UIThreadPool_h___
#define ___UIThreadPool_h___
/* Qt includes: */
#include <QObject>
#include <QMutex>
#include <QQueue>
#include <QSet>
#include <QVariant>
#include <QVector>
#include <QWaitCondition>
/* Forward declarations: */
class UIThreadWorker;
class UITask;
/** QObject extension used as worker-thread pool.
* Schedules COM-related GUI tasks to multiple worker-threads. */
class UIThreadPool : public QObject
{
Q_OBJECT;
signals:
/** Notifies listeners about @a pTask complete. */
void sigTaskComplete(UITask *pTask);
public:
/** Constructs worker-thread pool.
* @param cMaxWorkers defines the maximum amount of worker-threads.
* @param cMsWorkerIdleTimeout defines the maximum amount of time (in ms) which
* pool will wait for the worker-thread on cleanup. */
UIThreadPool(ulong cMaxWorkers = 3, ulong cMsWorkerIdleTimeout = 5000);
/** Destructs worker-thread pool. */
~UIThreadPool();
/** Returns whether the 'termination sequence' is started. */
bool isTerminating() const;
/** Defines that the 'termination sequence' is started. */
void setTerminating();
/** Enqueues @a pTask into the task-queue. */
void enqueueTask(UITask *pTask);
/** Returns dequeued top-most task from the task-queue.
* @remarks Called by the @a pWorker passed as a hint. */
UITask* dequeueTask(UIThreadWorker *pWorker);
private slots:
/** Handles @a pTask complete signal. */
void sltHandleTaskComplete(UITask *pTask);
/** Handles @a pWorker finished signal. */
void sltHandleWorkerFinished(UIThreadWorker *pWorker);
private:
/** @name Worker-thread stuff.
* @{ */
/** Holds the maximum amount of time (in ms) which
* pool will wait for the worker-thread on cleanup. */
const ulong m_cMsIdleTimeout;
/** Holds the vector of worker-threads. */
QVector<UIThreadWorker*> m_workers;
/** Holds the number of worker-threads.
* @remarks We cannot use the vector size since it may contain 0 pointers. */
int m_cWorkers;
/** Holds the number of idle worker-threads. */
int m_cIdleWorkers;
/** Holds whether the 'termination sequence' is started
* and all worker-threads should terminate ASAP. */
bool m_fTerminating;
/** @} */
/** @name Task stuff
* @{ */
/** Holds the queue of pending tasks. */
QQueue<UITask*> m_pendingTasks;
/** Holds the set of executing tasks. */
QSet<UITask*> m_executingTasks;
/** Holds the condition variable that gets signalled when
* queuing a new task and there are idle worker threads around.
* @remarks Idle threads sits in dequeueTask waiting for this.
* Thus on thermination, setTerminating() will send a
* broadcast signal to wake up all workers (after
* setting m_fTerminating of course). */
QWaitCondition m_taskCondition;
/** @} */
/** Holds the guard mutex object protecting
* all the inter-thread variables. */
mutable QMutex m_everythingLocker;
};
/** QObject extension used as worker-thread task interface.
* Describes task to be executed by the UIThreadWorker object. */
class UITask : public QObject
{
Q_OBJECT;
signals:
/** Notifies listeners about @a pTask complete. */
void sigComplete(UITask *pTask);
public:
/** Task types. */
enum Type
{
Type_MediumEnumeration = 1,
Type_DetailsPopulation = 2,
};
/** Constructs the task of passed @a type. */
UITask(UITask::Type type) : m_type(type) {}
/** Returns the type of the task. */
UITask::Type type() const { return m_type; }
/** Starts the task. */
void start();
protected:
/** Contains the abstract task body.
* @remarks To be reimplemented in sub-class. */
virtual void run() = 0;
private:
/** Holds the type of the task. */
const UITask::Type m_type;
};
#endif /* !___UIThreadPool_h___ */
| 1,720 |
947 | <filename>src/modules/extrakeys/hsort_impl.h
/***********************************************************************
* Copyright (c) 2021 <NAME>, <NAME> *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_HSORT_IMPL_H_
#define SECP256K1_HSORT_IMPL_H_
#include "hsort.h"
/* An array is a heap when, for all non-zero indexes i, the element at index i
* compares as less than or equal to the element at index parent(i) = (i-1)/2.
*/
static SECP256K1_INLINE size_t child1(size_t i) {
VERIFY_CHECK(i <= (SIZE_MAX - 1)/2);
return 2*i + 1;
}
static SECP256K1_INLINE size_t child2(size_t i) {
VERIFY_CHECK(i <= SIZE_MAX/2 - 1);
return child1(i)+1;
}
static SECP256K1_INLINE void swap64(unsigned char *a, size_t i, size_t j, size_t stride) {
unsigned char tmp[64];
VERIFY_CHECK(stride <= 64);
memcpy(tmp, a + i*stride, stride);
memmove(a + i*stride, a + j*stride, stride);
memcpy(a + j*stride, tmp, stride);
}
static SECP256K1_INLINE void swap(unsigned char *a, size_t i, size_t j, size_t stride) {
while (64 < stride) {
swap64(a + (stride - 64), i, j, 64);
stride -= 64;
}
swap64(a, i, j, stride);
}
static SECP256K1_INLINE void heap_down(unsigned char *a, size_t i, size_t heap_size, size_t stride,
int (*cmp)(const void *, const void *, void *), void *cmp_data) {
while (i < heap_size/2) {
VERIFY_CHECK(i <= SIZE_MAX/2 - 1);
/* Proof:
* i < heap_size/2
* i + 1 <= heap_size/2
* 2*i + 2 <= heap_size <= SIZE_MAX
* 2*i <= SIZE_MAX - 2
*/
VERIFY_CHECK(child1(i) < heap_size);
/* Proof:
* i < heap_size/2
* i + 1 <= heap_size/2
* 2*i + 2 <= heap_size
* 2*i + 1 < heap_size
* child1(i) < heap_size
*/
/* Let [x] be notation for the contents at a[x*stride].
*
* If [child1(i)] > [i] and [child2(i)] > [i],
* swap [i] with the larger child to ensure the new parent is larger
* than both children. When [child1(i)] == [child2(i)], swap [i] with
* [child2(i)].
* Else if [child1(i)] > [i], swap [i] with [child1(i)].
* Else if [child2(i)] > [i], swap [i] with [child2(i)].
*/
if (child2(i) < heap_size
&& 0 <= cmp(a + child2(i)*stride, a + child1(i)*stride, cmp_data)) {
if (0 < cmp(a + child2(i)*stride, a + i*stride, cmp_data)) {
swap(a, i, child2(i), stride);
i = child2(i);
} else {
/* At this point we have [child2(i)] >= [child1(i)] and we have
* [child2(i)] <= [i], and thus [child1(i)] <= [i] which means
* that the next comparison can be skipped. */
return;
}
} else if (0 < cmp(a + child1(i)*stride, a + i*stride, cmp_data)) {
swap(a, i, child1(i), stride);
i = child1(i);
} else {
return;
}
}
/* heap_size/2 <= i
* heap_size/2 < i + 1
* heap_size < 2*i + 2
* heap_size <= 2*i + 1
* heap_size <= child1(i)
* Thus child1(i) and child2(i) are now out of bounds and we are at a leaf.
*/
}
/* In-place heap sort. */
static void secp256k1_hsort(void *ptr, size_t count, size_t size,
int (*cmp)(const void *, const void *, void *),
void *cmp_data ) {
size_t i;
for(i = count/2; 0 < i; --i) {
heap_down(ptr, i-1, count, size, cmp, cmp_data);
}
for(i = count; 1 < i; --i) {
/* Extract the largest value from the heap */
swap(ptr, 0, i-1, size);
/* Repair the heap condition */
heap_down(ptr, 0, i-1, size, cmp, cmp_data);
}
}
#endif
| 1,988 |
450 | /* ______ ___ ___
* /\ _ \ /\_ \ /\_ \
* \ \ \L\ \\//\ \ \//\ \ __ __ _ __ ___
* \ \ __ \ \ \ \ \ \ \ /'__`\ /'_ `\/\`'__\/ __`\
* \ \ \/\ \ \_\ \_ \_\ \_/\ __//\ \L\ \ \ \//\ \L\ \
* \ \_\ \_\/\____\/\____\ \____\ \____ \ \_\\ \____/
* \/_/\/_/\/____/\/____/\/____/\/___L\ \/_/ \/___/
* /\____/
* \_/__/
*
* Graphics routines: palette fading, circles, etc.
*
* By <NAME>.
*
* Optimised line drawer by <NAME>.
*
* Bresenham arc routine by <NAME>.
*
* Cohen-Sutherland line clipping by <NAME>.
*
* See readme.txt for copyright information.
*/
#include <math.h>
#include "allegro.h"
#include "allegro/internal/aintern.h"
/* drawing_mode:
* Sets the drawing mode. This only affects routines like putpixel,
* lines, rectangles, triangles, etc, not the blitting or sprite
* drawing functions.
*/
void drawing_mode(int mode, BITMAP *pattern, int x_anchor, int y_anchor)
{
_drawing_mode = mode;
_drawing_pattern = pattern;
_drawing_x_anchor = x_anchor;
_drawing_y_anchor = y_anchor;
if (pattern) {
_drawing_x_mask = 1;
while (_drawing_x_mask < (unsigned)pattern->w)
_drawing_x_mask <<= 1; /* find power of two greater than w */
if (_drawing_x_mask > (unsigned)pattern->w) {
ASSERT(FALSE);
_drawing_x_mask >>= 1; /* round down if required */
}
_drawing_x_mask--; /* convert to AND mask */
_drawing_y_mask = 1;
while (_drawing_y_mask < (unsigned)pattern->h)
_drawing_y_mask <<= 1; /* find power of two greater than h */
if (_drawing_y_mask > (unsigned)pattern->h) {
ASSERT(FALSE);
_drawing_y_mask >>= 1; /* round down if required */
}
_drawing_y_mask--; /* convert to AND mask */
}
else
_drawing_x_mask = _drawing_y_mask = 0;
}
/* set_blender_mode:
* Specifies a custom set of blender functions for interpolating between
* truecolor pixels. The 24 bit blender is shared between the 24 and 32 bit
* modes. Pass a NULL table for unused color depths (you must not draw
* translucent graphics in modes without a handler, though!). Your blender
* will be passed two 32 bit colors in the appropriate format (5.5.5, 5.6.5,
* or 8.8.8), and an alpha value, should return the result of combining them.
* In translucent drawing modes, the two colors are taken from the source
* and destination images and the alpha is specified by this function. In
* lit modes, the alpha is specified when you call the drawing routine, and
* the interpolation is between the source color and the RGB values you pass
* to this function.
*/
void set_blender_mode(BLENDER_FUNC b15, BLENDER_FUNC b16, BLENDER_FUNC b24, int r, int g, int b, int a)
{
_blender_func15 = b15;
_blender_func16 = b16;
_blender_func24 = b24;
_blender_func32 = b24;
_blender_func15x = _blender_black;
_blender_func16x = _blender_black;
_blender_func24x = _blender_black;
_blender_col_15 = makecol15(r, g, b);
_blender_col_16 = makecol16(r, g, b);
_blender_col_24 = makecol24(r, g, b);
_blender_col_32 = makecol32(r, g, b);
_blender_alpha = a;
}
/* set_blender_mode_ex
* Specifies a custom set of blender functions for interpolating between
* truecolor pixels, providing a more complete set of routines, which
* differentiate between 24 and 32 bit modes, and have special routines
* for blending 32 bit RGBA pixels onto a destination of any format.
*/
void set_blender_mode_ex(BLENDER_FUNC b15, BLENDER_FUNC b16, BLENDER_FUNC b24, BLENDER_FUNC b32, BLENDER_FUNC b15x, BLENDER_FUNC b16x, BLENDER_FUNC b24x, int r, int g, int b, int a)
{
_blender_func15 = b15;
_blender_func16 = b16;
_blender_func24 = b24;
_blender_func32 = b32;
_blender_func15x = b15x;
_blender_func16x = b16x;
_blender_func24x = b24x;
_blender_col_15 = makecol15(r, g, b);
_blender_col_16 = makecol16(r, g, b);
_blender_col_24 = makecol24(r, g, b);
_blender_col_32 = makecol32(r, g, b);
_blender_alpha = a;
}
/* xor_mode:
* Shortcut function for toggling XOR mode on and off.
*/
void xor_mode(int on)
{
drawing_mode(on ? DRAW_MODE_XOR : DRAW_MODE_SOLID, NULL, 0, 0);
}
/* solid_mode:
* Shortcut function for selecting solid drawing mode.
*/
void solid_mode(void)
{
drawing_mode(DRAW_MODE_SOLID, NULL, 0, 0);
}
/* clear_bitmap:
* Clears the bitmap to color 0.
*/
void clear_bitmap(BITMAP *bitmap)
{
clear_to_color(bitmap, 0);
}
/* _bitmap_has_alpha:
* Checks whether this bitmap has an alpha channel.
*/
int _bitmap_has_alpha(BITMAP *bmp)
{
int x, y, c;
if (bitmap_color_depth(bmp) != 32)
return FALSE;
for (y = 0; y < bmp->h; y++) {
for (x = 0; x < bmp->w; x++) {
c = getpixel(bmp, x, y);
if (geta32(c))
return TRUE;
}
}
return FALSE;
}
/* set_color:
* Sets a single palette entry.
*/
void set_color(int index, AL_CONST RGB *p)
{
ASSERT(index >= 0 && index < PAL_SIZE);
set_palette_range((struct RGB *)p-index, index, index, FALSE);
}
/* set_palette:
* Sets the entire color palette.
*/
void set_palette(AL_CONST PALETTE p)
{
set_palette_range(p, 0, PAL_SIZE-1, TRUE);
}
/* set_palette_range:
* Sets a part of the color palette.
*/
void set_palette_range(AL_CONST PALETTE p, int from, int to, int vsync)
{
int c;
ASSERT(from >= 0 && from < PAL_SIZE);
ASSERT(to >= 0 && to < PAL_SIZE)
for (c=from; c<=to; c++) {
_current_palette[c] = p[c];
if (_color_depth != 8)
palette_color[c] = makecol(_rgb_scale_6[p[c].r], _rgb_scale_6[p[c].g], _rgb_scale_6[p[c].b]);
}
_current_palette_changed = 0xFFFFFFFF & ~(1<<(_color_depth-1));
}
/* previous palette, so the image loaders can restore it when they are done */
int _got_prev_current_palette = FALSE;
PALETTE _prev_current_palette;
static int prev_palette_color[PAL_SIZE];
/* select_palette:
* Sets the aspects of the palette tables that are used for converting
* between different image formats, without altering the display settings.
* The previous settings are copied onto a one-deep stack, from where they
* can be restored by calling unselect_palette().
*/
void select_palette(AL_CONST PALETTE p)
{
int c;
for (c=0; c<PAL_SIZE; c++) {
_prev_current_palette[c] = _current_palette[c];
_current_palette[c] = p[c];
}
if (_color_depth != 8) {
for (c=0; c<PAL_SIZE; c++) {
prev_palette_color[c] = palette_color[c];
palette_color[c] = makecol(_rgb_scale_6[p[c].r], _rgb_scale_6[p[c].g], _rgb_scale_6[p[c].b]);
}
}
_got_prev_current_palette = TRUE;
_current_palette_changed = 0xFFFFFFFF & ~(1<<(_color_depth-1));
}
/* unselect_palette:
* Restores palette settings from before the last call to select_palette().
*/
void unselect_palette(void)
{
int c;
for (c=0; c<PAL_SIZE; c++)
_current_palette[c] = _prev_current_palette[c];
if (_color_depth != 8) {
for (c=0; c<PAL_SIZE; c++)
palette_color[c] = prev_palette_color[c];
}
ASSERT(_got_prev_current_palette == TRUE);
_got_prev_current_palette = FALSE;
_current_palette_changed = 0xFFFFFFFF & ~(1<<(_color_depth-1));
}
/* _palette_expansion_table:
* Creates a lookup table for expanding 256->truecolor.
*/
static int *palette_expansion_table(int bpp)
{
int *table;
int c;
switch (bpp) {
case 15: table = _palette_color15; break;
case 16: table = _palette_color16; break;
case 24: table = _palette_color24; break;
case 32: table = _palette_color32; break;
default: ASSERT(FALSE); return NULL;
}
if (_current_palette_changed & (1<<(bpp-1))) {
for (c=0; c<PAL_SIZE; c++) {
table[c] = makecol_depth(bpp,
_rgb_scale_6[_current_palette[c].r],
_rgb_scale_6[_current_palette[c].g],
_rgb_scale_6[_current_palette[c].b]);
}
_current_palette_changed &= ~(1<<(bpp-1));
}
return table;
}
/* this has to be called through a function pointer, so MSVC asm can use it */
int *(*_palette_expansion_table)(int) = palette_expansion_table;
/* generate_332_palette:
* Used when loading a truecolor image into an 8 bit bitmap, to generate
* a 3.3.2 RGB palette.
*/
void generate_332_palette(PALETTE pal)
{
int c;
for (c=0; c<PAL_SIZE; c++) {
pal[c].r = ((c>>5)&7) * 63/7;
pal[c].g = ((c>>2)&7) * 63/7;
pal[c].b = (c&3) * 63/3;
}
pal[0].r = 63;
pal[0].g = 0;
pal[0].b = 63;
pal[254].r = pal[254].g = pal[254].b = 0;
}
/* get_color:
* Retrieves a single color from the palette.
*/
void get_color(int index, RGB *p)
{
ASSERT(index >= 0 && index < PAL_SIZE);
ASSERT(p);
get_palette_range(p-index, index, index);
}
/* get_palette:
* Retrieves the entire color palette.
*/
void get_palette(PALETTE p)
{
get_palette_range(p, 0, PAL_SIZE-1);
}
/* get_palette_range:
* Retrieves a part of the color palette.
*/
void get_palette_range(PALETTE p, int from, int to)
{
int c;
ASSERT(from >= 0 && from < PAL_SIZE);
ASSERT(to >= 0 && to < PAL_SIZE);
for (c=from; c<=to; c++)
p[c] = _current_palette[c];
}
/* fade_interpolate:
* Calculates a palette part way between source and dest, returning it
* in output. The pos indicates how far between the two extremes it should
* be: 0 = return source, 64 = return dest, 32 = return exactly half way.
* Only affects colors between from and to (inclusive).
*/
void fade_interpolate(AL_CONST PALETTE source, AL_CONST PALETTE dest, PALETTE output, int pos, int from, int to)
{
int c;
ASSERT(pos >= 0 && pos <= 64);
ASSERT(from >= 0 && from < PAL_SIZE);
ASSERT(to >= 0 && to < PAL_SIZE);
for (c=from; c<=to; c++) {
output[c].r = ((int)source[c].r * (63-pos) + (int)dest[c].r * pos) / 64;
output[c].g = ((int)source[c].g * (63-pos) + (int)dest[c].g * pos) / 64;
output[c].b = ((int)source[c].b * (63-pos) + (int)dest[c].b * pos) / 64;
}
}
/* rect:
* Draws an outline rectangle.
*/
void _soft_rect(BITMAP *bmp, int x1, int y1, int x2, int y2, int color)
{
int t;
if (x2 < x1) {
t = x1;
x1 = x2;
x2 = t;
}
if (y2 < y1) {
t = y1;
y1 = y2;
y2 = t;
}
acquire_bitmap(bmp);
hline(bmp, x1, y1, x2, color);
if (y2 > y1)
hline(bmp, x1, y2, x2, color);
if (y2-1 >= y1+1) {
vline(bmp, x1, y1+1, y2-1, color);
if (x2 > x1)
vline(bmp, x2, y1+1, y2-1, color);
}
release_bitmap(bmp);
}
/* _normal_rectfill:
* Draws a solid filled rectangle, using hfill() to do the work.
*/
void _normal_rectfill(BITMAP *bmp, int x1, int y1, int x2, int y2, int color)
{
int t;
if (y1 > y2) {
t = y1;
y1 = y2;
y2 = t;
}
if (bmp->clip) {
if (x1 > x2) {
t = x1;
x1 = x2;
x2 = t;
}
if (x1 < bmp->cl)
x1 = bmp->cl;
if (x2 >= bmp->cr)
x2 = bmp->cr-1;
if (x2 < x1)
return;
if (y1 < bmp->ct)
y1 = bmp->ct;
if (y2 >= bmp->cb)
y2 = bmp->cb-1;
if (y2 < y1)
return;
bmp->clip = FALSE;
t = TRUE;
}
else
t = FALSE;
acquire_bitmap(bmp);
while (y1 <= y2) {
bmp->vtable->hfill(bmp, x1, y1, x2, color);
y1++;
};
release_bitmap(bmp);
bmp->clip = t;
}
/* do_line:
* Calculates all the points along a line between x1, y1 and x2, y2,
* calling the supplied function for each one. This will be passed a
* copy of the bmp parameter, the x and y position, and a copy of the
* d parameter (so do_line() can be used with putpixel()).
*/
void do_line(BITMAP *bmp, int x1, int y1, int x2, int y2, int d, void (*proc)(BITMAP *, int, int, int))
{
int dx = x2-x1;
int dy = y2-y1;
int i1, i2;
int x, y;
int dd;
/* worker macro */
#define DO_LINE(pri_sign, pri_c, pri_cond, sec_sign, sec_c, sec_cond) \
{ \
if (d##pri_c == 0) { \
proc(bmp, x1, y1, d); \
return; \
} \
\
i1 = 2 * d##sec_c; \
dd = i1 - (sec_sign (pri_sign d##pri_c)); \
i2 = dd - (sec_sign (pri_sign d##pri_c)); \
\
x = x1; \
y = y1; \
\
while (pri_c pri_cond pri_c##2) { \
proc(bmp, x, y, d); \
\
if (dd sec_cond 0) { \
sec_c = sec_c sec_sign 1; \
dd += i2; \
} \
else \
dd += i1; \
\
pri_c = pri_c pri_sign 1; \
} \
}
if (dx >= 0) {
if (dy >= 0) {
if (dx >= dy) {
/* (x1 <= x2) && (y1 <= y2) && (dx >= dy) */
DO_LINE(+, x, <=, +, y, >=);
}
else {
/* (x1 <= x2) && (y1 <= y2) && (dx < dy) */
DO_LINE(+, y, <=, +, x, >=);
}
}
else {
if (dx >= -dy) {
/* (x1 <= x2) && (y1 > y2) && (dx >= dy) */
DO_LINE(+, x, <=, -, y, <=);
}
else {
/* (x1 <= x2) && (y1 > y2) && (dx < dy) */
DO_LINE(-, y, >=, +, x, >=);
}
}
}
else {
if (dy >= 0) {
if (-dx >= dy) {
/* (x1 > x2) && (y1 <= y2) && (dx >= dy) */
DO_LINE(-, x, >=, +, y, >=);
}
else {
/* (x1 > x2) && (y1 <= y2) && (dx < dy) */
DO_LINE(+, y, <=, -, x, <=);
}
}
else {
if (-dx >= -dy) {
/* (x1 > x2) && (y1 > y2) && (dx >= dy) */
DO_LINE(-, x, >=, -, y, <=);
}
else {
/* (x1 > x2) && (y1 > y2) && (dx < dy) */
DO_LINE(-, y, >=, -, x, <=);
}
}
}
#undef DO_LINE
}
/* _normal_line:
* Draws a line from x1, y1 to x2, y2, using putpixel() to do the work.
*/
void _normal_line(BITMAP *bmp, int x1, int y1, int x2, int y2, int color)
{
int sx, sy, dx, dy, t;
if (x1 == x2) {
vline(bmp, x1, y1, y2, color);
return;
}
if (y1 == y2) {
hline(bmp, x1, y1, x2, color);
return;
}
/* use a bounding box to check if the line needs clipping */
if (bmp->clip) {
sx = x1;
sy = y1;
dx = x2;
dy = y2;
if (sx > dx) {
t = sx;
sx = dx;
dx = t;
}
if (sy > dy) {
t = sy;
sy = dy;
dy = t;
}
if ((sx >= bmp->cr) || (sy >= bmp->cb) || (dx < bmp->cl) || (dy < bmp->ct))
return;
if ((sx >= bmp->cl) && (sy >= bmp->ct) && (dx < bmp->cr) && (dy < bmp->cb))
bmp->clip = FALSE;
t = TRUE;
}
else
t= FALSE;
acquire_bitmap(bmp);
do_line(bmp, x1, y1, x2, y2, color, bmp->vtable->putpixel);
release_bitmap(bmp);
bmp->clip = t;
}
/* circlefill:
* Draws a filled circle.
*/
void _soft_circlefill(BITMAP *bmp, int x, int y, int radius, int color)
{
int cx = 0;
int cy = radius;
int df = 1 - radius;
int d_e = 3;
int d_se = -2 * radius + 5;
int clip, sx, sy, dx, dy;
ASSERT(bmp);
if (bmp->clip) {
sx = x-radius-1;
sy = y-radius-1;
dx = x+radius+1;
dy = y+radius+1;
if ((sx >= bmp->cr) || (sy >= bmp->cb) || (dx < bmp->cl) || (dy < bmp->ct))
return;
if ((sx >= bmp->cl) && (sy >= bmp->ct) && (dx < bmp->cr) && (dy < bmp->cb))
bmp->clip = FALSE;
clip = TRUE;
}
else
clip = FALSE;
acquire_bitmap(bmp);
do {
bmp->vtable->hfill(bmp, x-cy, y-cx, x+cy, color);
if (cx)
bmp->vtable->hfill(bmp, x-cy, y+cx, x+cy, color);
if (df < 0) {
df += d_e;
d_e += 2;
d_se += 2;
}
else {
if (cx != cy) {
bmp->vtable->hfill(bmp, x-cx, y-cy, x+cx, color);
if (cy)
bmp->vtable->hfill(bmp, x-cx, y+cy, x+cx, color);
}
df += d_se;
d_e += 2;
d_se += 4;
cy--;
}
cx++;
} while (cx <= cy);
release_bitmap(bmp);
bmp->clip = clip;
}
| 8,455 |
2,151 | <filename>chrome/browser/safe_browsing/download_protection/disk_image_type_sniffer_mac.cc
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/safe_browsing/download_protection/disk_image_type_sniffer_mac.h"
#include "base/threading/thread_restrictions.h"
#include "content/public/browser/browser_thread.h"
namespace safe_browsing {
namespace {
const uint8_t kKolySignature[4] = {'k', 'o', 'l', 'y'};
constexpr size_t kSizeKolySignatureInBytes = sizeof(kKolySignature);
const size_t kSizeKolyTrailerInBytes = 512;
} // namespace
DiskImageTypeSnifferMac::DiskImageTypeSnifferMac() {}
// static
bool DiskImageTypeSnifferMac::IsAppleDiskImage(const base::FilePath& dmg_file) {
base::AssertBlockingAllowed();
base::File file(dmg_file, base::File::FLAG_OPEN | base::File::FLAG_READ);
if (!file.IsValid())
return false;
char data[kSizeKolySignatureInBytes];
if (file.Seek(base::File::FROM_END, -1 * kSizeKolyTrailerInBytes) == -1)
return false;
if (file.ReadAtCurrentPos(data, kSizeKolySignatureInBytes) !=
kSizeKolySignatureInBytes)
return false;
return (memcmp(data, kKolySignature, kSizeKolySignatureInBytes) == 0);
}
DiskImageTypeSnifferMac::~DiskImageTypeSnifferMac() = default;
} // namespace safe_browsing
| 495 |
1,144 | <filename>backend/de.metas.materialtracking/src/main/java/de/metas/materialtracking/qualityBasedInvoicing/IQualityInspectionLineBuilder.java
package de.metas.materialtracking.qualityBasedInvoicing;
/*
* #%L
* de.metas.materialtracking
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import java.math.BigDecimal;
import org.compiere.model.I_C_UOM;
import de.metas.materialtracking.IHandlingUnitsInfo;
/**
* Builder class used to create {@link IQualityInspectionLine}s.
*
* @author tsa
*
*/
public interface IQualityInspectionLineBuilder
{
IQualityInspectionLine create();
IQualityInspectionLineBuilder setQualityInspectionLineType(QualityInspectionLineType qualityInspectionLineType);
IQualityInspectionLineBuilder setProductionMaterial(final IProductionMaterial productionMaterial);
IQualityInspectionLineBuilder setQty(final BigDecimal qty);
/**
*
* @param negateQty true if we shall negate the Qty from produced report line. Only the "Qty" will be negated and not the other quantities.
* @return
*/
IQualityInspectionLineBuilder setNegateQty(boolean negateQty);
IQualityInspectionLineBuilder setQtyProjected(final BigDecimal qtyProjected);
IQualityInspectionLineBuilder setC_UOM(final I_C_UOM uom);
IQualityInspectionLineBuilder setPercentage(final BigDecimal percentage);
IQualityInspectionLineBuilder setName(String name);
IQualityInspectionLineBuilder setHandlingUnitsInfo(IHandlingUnitsInfo handlingUnitsInfo);
IQualityInspectionLineBuilder setHandlingUnitsInfoProjected(IHandlingUnitsInfo handlingUnitsInfo);
}
| 644 |
511 | /******************************************************************
*
* Copyright 2016 Samsung Electronics 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.
*
******************************************************************/
#ifndef SIMULATOR_RESOURCE_MODEL_SCHEMA_H_
#define SIMULATOR_RESOURCE_MODEL_SCHEMA_H_
#include <unordered_map>
#include <memory>
#include "simulator_resource_model.h"
class IntegerProperty;
class DoubleProperty;
class BooleanProperty;
class StringProperty;
class ArrayProperty;
class ModelProperty;
class AttributeProperty
{
public:
enum class Type
{
INTEGER,
DOUBLE,
BOOLEAN,
STRING,
MODEL,
ARRAY
};
explicit AttributeProperty(Type type);
virtual ~AttributeProperty() {};
Type getType() const;
virtual bool isInteger() const { return false; }
virtual bool isDouble() const { return false; }
virtual bool isBoolean() const { return false; }
virtual bool isString() const { return false; }
virtual bool isArray() const { return false; }
virtual bool isModel() const { return false; }
virtual std::shared_ptr<IntegerProperty> asInteger() { return nullptr; }
virtual std::shared_ptr<DoubleProperty> asDouble() { return nullptr; }
virtual std::shared_ptr<BooleanProperty> asBoolean() { return nullptr; }
virtual std::shared_ptr<StringProperty> asString() { return nullptr; }
virtual std::shared_ptr<ArrayProperty> asArray() { return nullptr; }
virtual std::shared_ptr<ModelProperty> asModel() { return nullptr; }
virtual bool validate(const AttributeValueVariant &value) = 0;
virtual AttributeValueVariant buildValue() = 0;
private:
Type m_type;
};
class IntegerProperty : public AttributeProperty,
public std::enable_shared_from_this<IntegerProperty>
{
public:
static std::shared_ptr<IntegerProperty> build(int defaultValue = 0);
bool isInteger() const;
std::shared_ptr<IntegerProperty> asInteger();
void setDefaultValue(int value);
void setRange(int min, int max);
void setValues(const std::vector<int> &values);
bool hasRange() const;
bool hasValues() const;
int getDefaultValue() const;
bool getRange(int &min, int &max) const;
bool getValues(std::vector<int> &values) const;
bool validate(const AttributeValueVariant &value);
bool validate(const int &value);
AttributeValueVariant buildValue();
private:
explicit IntegerProperty(int defaultValue);
int m_defaultValue;
int m_min;
int m_max;
std::vector<int> m_values;
bool m_hasRange;
};
class DoubleProperty : public AttributeProperty,
public std::enable_shared_from_this<DoubleProperty>
{
public:
static std::shared_ptr<DoubleProperty> build(double defaultValue = 0.0);
bool isDouble() const;
std::shared_ptr<DoubleProperty> asDouble();
void setDefaultValue(double value);
void setRange(double min, double max);
void setValues(const std::vector<double> &values);
bool hasRange() const;
bool hasValues() const;
double getDefaultValue() const;
bool getRange(double &min, double &max) const;
bool getValues(std::vector<double> &values) const;
bool validate(const AttributeValueVariant &value);
bool validate(const double &value);
AttributeValueVariant buildValue();
private:
explicit DoubleProperty(double defaultValue);
double m_defaultValue;
double m_min;
double m_max;
std::vector<double> m_values;
bool m_hasRange;
};
class BooleanProperty : public AttributeProperty,
public std::enable_shared_from_this<BooleanProperty>
{
public:
static std::shared_ptr<BooleanProperty> build(bool defaultValue = true);
bool isBoolean() const;
std::shared_ptr<BooleanProperty> asBoolean();
void setDefaultValue(bool value);
bool getDefaultValue() const;
bool validate(const AttributeValueVariant &value);
AttributeValueVariant buildValue();
private:
explicit BooleanProperty(bool defaultValue);
bool m_defaultValue;
};
class StringProperty : public AttributeProperty,
public std::enable_shared_from_this<StringProperty>
{
public:
static std::shared_ptr<StringProperty> build(const std::string &defaultValue = "");
bool isString() const;
std::shared_ptr<StringProperty> asString();
void setDefaultValue(const std::string &value);
void setRange(size_t min, size_t max);
void setValues(const std::vector<std::string> &values);
bool hasRange() const;
bool hasValues() const;
std::string getDefaultValue() const;
bool getRange(size_t &min, size_t &max) const;
bool getValues(std::vector<std::string> &values) const;
bool validate(const AttributeValueVariant &value);
bool validate(const std::string &value);
AttributeValueVariant buildValue();
private:
StringProperty(const std::string &defaultValue);
std::string m_defaultValue;
size_t m_min;
size_t m_max;
std::vector<std::string> m_values;
bool m_hasRange;
};
class ArrayProperty : public AttributeProperty,
public std::enable_shared_from_this<ArrayProperty>
{
public:
static std::shared_ptr<ArrayProperty> build();
bool isArray() const;
std::shared_ptr<ArrayProperty> asArray();
void setRange(size_t minItems, size_t maxItems);
void setVariable(bool state);
void setUnique(bool state);
bool setElementProperty(const std::shared_ptr<AttributeProperty> &property);
bool hasRange() const;
bool isVariable() const;
bool isUnique() const;
size_t getMinItems() const;
size_t getMaxItems() const;
std::shared_ptr<AttributeProperty> getElementProperty();
bool validate(const AttributeValueVariant &value);
AttributeValueVariant buildValue();
private:
ArrayProperty();
int findDepth(std::shared_ptr<AttributeProperty> &elementProperty);
size_t m_min;
size_t m_max;
bool m_isVariableSize;
bool m_isUnique;
std::shared_ptr<AttributeProperty> m_elementProperty;
bool m_hasRange;
};
class ModelProperty : public AttributeProperty,
public std::enable_shared_from_this<ModelProperty>
{
public:
static std::shared_ptr<ModelProperty> build();
bool isModel() const;
std::shared_ptr<ModelProperty> asModel();
bool add(const std::string &name, const std::shared_ptr<AttributeProperty> &property,
bool required = false);
std::shared_ptr<AttributeProperty> get(const std::string &name);
std::unordered_map<std::string, std::shared_ptr<AttributeProperty>> getChildProperties();
bool isRequired(const std::string &name);
void remove(const std::string &name);
void setRequired(const std::string &name);
void unsetRequired(const std::string &name);
SimulatorResourceModel buildResourceModel();
bool validate(const AttributeValueVariant &value);
bool validate(const SimulatorResourceModel &model);
AttributeValueVariant buildValue();
private:
ModelProperty();
std::unordered_map<std::string, bool> m_requiredAttributes;
std::unordered_map<std::string, std::shared_ptr<AttributeProperty>> m_childProperties;
};
typedef ModelProperty SimulatorResourceModelSchema;
#endif
| 3,095 |
619 | <gh_stars>100-1000
/*
* Author: <NAME> <<EMAIL>>
* Copyright (c) 2016 Intel Corporation.
*
* This program and the accompanying materials are made available under the
* terms of the The MIT License which is available at
* https://opensource.org/licenses/MIT.
*
* SPDX-License-Identifier: MIT
*/
#include <ecezo.hpp>
#include <iostream>
#include <signal.h>
#include <upm_utilities.h>
using namespace std;
using namespace upm;
bool shouldRun = true;
void
sig_handler(int signo)
{
if (signo == SIGINT)
shouldRun = false;
}
int
main()
{
signal(SIGINT, sig_handler);
//! [Interesting]
// Instantiate a ECEZO sensor on uart 0 at 9600 baud.
upm::ECEZO sensor(0, 9600, false);
// For I2C, assuming the device is configured for address 0x64 on
// I2C bus 0, you could use something like:
//
// upm::ECEZO sensor(0, 0x64, true);
while (shouldRun) {
// this will take about 1 second to complete
sensor.update();
cout << "EC " << sensor.getEC() << " uS/cm, TDS " << sensor.getTDS() << " mg/L, Salinity "
<< sensor.getSalinity() << " PSS-78, SG " << sensor.getSG() << endl;
upm_delay(5);
}
//! [Interesting]
cout << "Exiting..." << endl;
return 0;
}
| 507 |
2,606 | package weixin.popular.bean.shakearound.device;
import com.alibaba.fastjson.annotation.JSONField;
/**
* 设备信息ID
* @author Moyq5
* @date 2016年7月30日
*/
public class DeviceIdentifier {
/**
* 设备编号,<br>
* 添加或修改时,若填了UUID、major、minor,则可不填设备编号,若二者都填,则以设备编号为优先<br>
* 必填
*/
@JSONField(name = "device_id")
private Integer deviceId;
/**
* 添加或修改时,UUID、major、minor,三个信息需填写完整,若填了设备编号,则可不填此信息。<br>
* 必填
*/
private String uuid;
/**
* 添加或修改时,UUID、major、minor,三个信息需填写完整,若填了设备编号,则可不填此信息。<br>
* 必填
*/
private Integer major;
/**
* 添加或修改时,UUID、major、minor,三个信息需填写完整,若填了设备编号,则可不填此信息。<br>
* 必填
*/
private Integer minor;
/**
* @return 设备编号
*/
public Integer getDeviceId() {
return deviceId;
}
/**
* 设备编号,<br>
* 添加或修改时,若填了UUID、major、minor,则可不填设备编号,若二者都填,则以设备编号为优先<br>
* 必填
* @param deviceId 设备编号
*/
public void setDeviceId(Integer deviceId) {
this.deviceId = deviceId;
}
/**
* @return UUID
*/
public String getUuid() {
return uuid;
}
/**
* 添加或修改时,UUID、major、minor,三个信息需填写完整,若填了设备编号,则可不填此信息。<br>
* 必填
* @param uuid UUID
*/
public void setUuid(String uuid) {
this.uuid = uuid;
}
/**
* @return major
*/
public Integer getMajor() {
return major;
}
/**
* 添加或修改时,UUID、major、minor,三个信息需填写完整,若填了设备编号,则可不填此信息。<br>
* 必填
* @param major major
*/
public void setMajor(Integer major) {
this.major = major;
}
/**
* @return minor
*/
public Integer getMinor() {
return minor;
}
/**
* 添加或修改时,UUID、major、minor,三个信息需填写完整,若填了设备编号,则可不填此信息。<br>
* 必填
* @param minor minor
*/
public void setMinor(Integer minor) {
this.minor = minor;
}
}
| 1,414 |
515 | <reponame>kraehlit/CTK<filename>Plugins/org.commontk.eventadmin/dispatch/ctkEALinkedQueue_p.h
/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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.
=============================================================================*/
#ifndef CTKEALINKEDQUEUE_P_H
#define CTKEALINKEDQUEUE_P_H
#include "ctkEAChannel_p.h"
#include <dispatch/ctkEAInterruptibleThread_p.h>
#include <QMutex>
#include <QWaitCondition>
/** A standard linked list node used in various queue classes **/
struct ctkEALinkedNode
{
ctkEARunnable* value;
ctkEALinkedNode* next;
ctkEALinkedNode(ctkEARunnable* x = 0)
: value(x), next(0)
{ if (x && x->autoDelete()) ++x->ref; }
ctkEALinkedNode(ctkEARunnable* x, ctkEALinkedNode* n)
: value(x), next(n)
{ if (x && x->autoDelete()) ++x->ref; }
~ctkEALinkedNode()
{
if (value && value->autoDelete())
{
--value->ref;
}
}
};
/**
* A linked list based channel implementation.
* The algorithm avoids contention between puts
* and takes when the queue is not empty.
* Normally a put and a take can proceed simultaneously.
* (Although it does not allow multiple concurrent puts or takes.)
* This class tends to perform more efficently than
* other ctkEAChannel implementations in producer/consumer
* applications.
*/
class ctkEALinkedQueue : public ctkEAChannel
{
protected:
/**
* Dummy header node of list. The first actual node, if it exists, is always
* at head_->next. After each take, the old first node becomes the head.
**/
ctkEALinkedNode* head_;
mutable QMutex headLock_;
QMutex mutex_;
/**
* Helper monitor for managing access to last node.
**/
QMutex putLock_;
QWaitCondition putLockWait_;
/**
* The last node of list. put() appends to list, so modifies last_
**/
ctkEALinkedNode* last_;
QMutex lastLock_;
/**
* The number of threads waiting for a take.
* Notifications are provided in put only if greater than zero.
* The bookkeeping is worth it here since in reasonably balanced
* usages, the notifications will hardly ever be necessary, so
* the call overhead to notify can be eliminated.
**/
int waitingForTake_;
public:
ctkEALinkedQueue();
~ctkEALinkedQueue();
void put(ctkEARunnable* x);
bool offer(ctkEARunnable* x, long msecs);
ctkEARunnable* take();
ctkEARunnable* peek() const;
bool isEmpty() const;
ctkEARunnable* poll(long msecs);
protected:
/** Main mechanics for put/offer **/
void insert(ctkEARunnable* x);
/** Main mechanics for take/poll **/
ctkEARunnable* extract();
};
#endif // CTKEALINKEDQUEUE_P_H
| 1,054 |
335 | <filename>P/Pin_noun.json
{
"word": "Pin",
"definitions": [
"A thin piece of metal with a sharp point at one end and a round head at the other, used for fastening pieces of cloth, paper, etc.",
"A small brooch or badge.",
"A steel rod used to join the ends of fractured bones while they heal.",
"A metal peg that holds down the activating lever of a hand grenade, preventing its explosion.",
"A hairpin.",
"A peg round which one string of a musical instrument is fastened.",
"A metal projection from a plug or an integrated circuit which makes an electrical connection with a socket or another part of a circuit.",
"A stick with a flag placed in a hole to mark its position.",
"A skittle in bowling.",
"A person's legs.",
"An attack on a piece or pawn which is thereby pinned.",
"A half-firkin cask for beer."
],
"parts-of-speech": "Noun"
} | 325 |
1,194 | {
"resourceType": "Observation",
"id": "vp-oyster",
"text": {
"status": "generated",
"div": "\u003cdiv xmlns\u003d\"http://www.w3.org/1999/xhtml\"\u003e\u003cp\u003e\u003cb\u003eGenerated Narrative with Details\u003c/b\u003e\u003c/p\u003e\u003cp\u003e\u003cb\u003eid\u003c/b\u003e: vp-oyster\u003c/p\u003e\u003cp\u003e\u003cb\u003eidentifier\u003c/b\u003e: 20171014-1234 (OFFICIAL)\u003c/p\u003e\u003cp\u003e\u003cb\u003estatus\u003c/b\u003e: preliminary\u003c/p\u003e\u003cp\u003e\u003cb\u003ecode\u003c/b\u003e: OYSTER TESTING \u003cspan\u003e(Details : {LOINC code \u002741857-4\u0027 \u003d \u0027Vibrio parahaemolyticus DNA [Presence] in Unspecified specimen by Probe and target amplification method\u0027, given as \u0027Vibrio parahaemolyticus DNA [Presence] in Unspecified specimen by Probe and target amplification method\u0027}; {http://sonomacounty.ca.gov/Health/Public-Health/Laboratory/test-codes code \u0027VP MULTI PCR\u0027 \u003d \u0027VP MULTI PCR\u0027, given as \u0027VP MULTI PCR\u0027})\u003c/span\u003e\u003c/p\u003e\u003cp\u003e\u003cb\u003esubject\u003c/b\u003e: Sonoma oyster farm\u003c/p\u003e\u003cp\u003e\u003cb\u003eeffective\u003c/b\u003e: 12/10/2017\u003c/p\u003e\u003cp\u003e\u003cb\u003eissued\u003c/b\u003e: 14/10/2017 11:11:24 PM\u003c/p\u003e\u003cp\u003e\u003cb\u003eperformer\u003c/b\u003e: \u003ca\u003eA. Langeveld\u003c/a\u003e\u003c/p\u003e\u003cp\u003e\u003cb\u003evalue\u003c/b\u003e: POSITIVE \u003cspan\u003e(Details : {SNOMED CT code \u002710828004\u0027 \u003d \u0027Positive\u0027, given as \u0027Positive (qualifier value)\u0027}; {http://sonomacounty.ca.gov/Health/Public-Health/Laboratory/result-codes code \u0027POSITIVE\u0027 \u003d \u0027POSITIVE\u0027, given as \u0027POSITIVE\u0027})\u003c/span\u003e\u003c/p\u003e\u003cp\u003e\u003cb\u003einterpretation\u003c/b\u003e: Abnormal \u003cspan\u003e(Details : {http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation code \u0027A\u0027 \u003d \u0027Abnormal\u0027, given as \u0027Abnormal\u0027})\u003c/span\u003e\u003c/p\u003e\u003cp\u003e\u003cb\u003especimen\u003c/b\u003e: Live Oysters Acc#20171014-1234\u003c/p\u003e\u003ch3\u003eReferenceRanges\u003c/h3\u003e\u003ctable\u003e\u003ctr\u003e\u003ctd\u003e-\u003c/td\u003e\u003ctd\u003e\u003cb\u003eText\u003c/b\u003e\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e*\u003c/td\u003e\u003ctd\u003eNEGATIVE\u003c/td\u003e\u003c/tr\u003e\u003c/table\u003e\u003c/div\u003e"
},
"identifier": [
{
"use": "official",
"system": "http://sonomacounty.ca.gov/Health/Public-Health/Laboratory",
"value": "20171014-1234"
}
],
"status": "preliminary",
"code": {
"coding": [
{
"system": "http://loinc.org",
"code": "41857-4",
"display": "Vibrio parahaemolyticus DNA [Presence] in Unspecified specimen by Probe and target amplification method"
},
{
"system": "http://sonomacounty.ca.gov/Health/Public-Health/Laboratory/test-codes",
"code": "VP MULTI PCR",
"display": "VP MULTI PCR"
}
],
"text": "OYSTER TESTING"
},
"subject": {
"display": "Sonoma oyster farm"
},
"effectiveDateTime": "2017-10-12",
"issued": "2017-10-14T23:11:24Z",
"performer": [
{
"reference": "Practitioner/f005",
"display": "<NAME>"
}
],
"valueCodeableConcept": {
"coding": [
{
"system": "http://snomed.info/sct",
"code": "10828004",
"display": "Positive (qualifier value)"
},
{
"system": "http://sonomacounty.ca.gov/Health/Public-Health/Laboratory/result-codes",
"code": "POSITIVE",
"display": "POSITIVE"
}
],
"text": "POSITIVE"
},
"interpretation": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
"code": "A",
"display": "Abnormal"
}
]
}
],
"specimen": {
"display": "Live Oysters Acc#20171014-1234"
},
"referenceRange": [
{
"text": "NEGATIVE"
}
],
"meta": {
"tag": [
{
"system": "http://terminology.hl7.org/CodeSystem/v3-ActReason",
"code": "HTEST",
"display": "test health data"
}
]
}
} | 2,098 |
364 | <reponame>spring-operator/reactive-streams-commons
package rsc.scheduler;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import rsc.publisher.Px;
import rsc.test.TestSubscriber;
public class SingleThreadedExecutorTest {
@Test
public void range() {
int count = 1_000_000;
Integer[] array = new Integer[count];
for (int i = 0; i < count; i++) {
array[i] = i;
}
Scheduler s1 = new SingleScheduler2();
Scheduler s2 = new SingleScheduler2();
TestSubscriber<Integer> ts = Px.fromArray(array).subscribeOn(s1).observeOn(s2).test();
ts.await(5, TimeUnit.SECONDS);
ts.assertValueCount(count)
.assertNoError()
.assertComplete();
}
}
| 363 |
3,986 | <gh_stars>1000+
/*
* Copyright (C) 2019 xuexiangjys(<EMAIL>)
*
* 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.xuexiang.xui.widget.popupwindow.popup;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ExpandableListView;
import com.xuexiang.xui.adapter.simple.ExpandableItem;
import com.xuexiang.xui.adapter.simple.XUISimpleExpandableListAdapter;
import java.util.List;
/**
* 简单的可伸缩弹窗
*
* @author xuexiang
* @since 2019-11-11 16:31
*/
public class XUISimpleExpandablePopup<T extends XUISimpleExpandablePopup> extends XUIExpandableListPopup {
public XUISimpleExpandablePopup(Context context, List<ExpandableItem> data) {
this(context, new XUISimpleExpandableListAdapter(data));
}
public XUISimpleExpandablePopup(Context context, ExpandableItem... data) {
this(context, new XUISimpleExpandableListAdapter(data));
}
public XUISimpleExpandablePopup(Context context, XUISimpleExpandableListAdapter adapter) {
super(context, adapter);
}
/**
* 创建弹窗
*
* @param onExpandableItemClickListener
* @return
*/
public T create(int width, final OnExpandableItemClickListener onExpandableItemClickListener) {
create(width);
setOnExpandableItemClickListener(onExpandableItemClickListener);
return (T) this;
}
/**
* 创建弹窗
*
* @param width 弹窗的宽度
* @param maxHeight 弹窗最大的高度
* @return
*/
@Override
public T create(int width, int maxHeight) {
super.create(width, maxHeight);
return (T) this;
}
/**
* 创建弹窗
*
* @param width
* @param maxHeight
* @param onExpandableItemClickListener
* @return
*/
public T create(int width, int maxHeight, final OnExpandableItemClickListener onExpandableItemClickListener) {
create(width, maxHeight);
setOnExpandableItemClickListener(onExpandableItemClickListener);
return (T) this;
}
/**
* 设置条目点击监听
*
* @param onExpandableItemClickListener
* @return
*/
public XUIExpandableListPopup setOnExpandableItemClickListener(final OnExpandableItemClickListener onExpandableItemClickListener) {
setOnExpandableItemClickListener(true, onExpandableItemClickListener);
return this;
}
/**
* 设置条目点击监听
*
* @param autoDismiss
* @param onExpandableItemClickListener
* @return
*/
public T setOnExpandableItemClickListener(final boolean autoDismiss, final OnExpandableItemClickListener onExpandableItemClickListener) {
if (mExpandableListView != null) {
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
if (onExpandableItemClickListener != null) {
onExpandableItemClickListener.onExpandableItemClick(getAdapter(), getAdapter().getGroup(groupPosition), groupPosition, childPosition);
}
if (autoDismiss) {
dismiss();
}
return false;
}
});
}
return (T) this;
}
@Override
public XUISimpleExpandableListAdapter getAdapter() {
return (XUISimpleExpandableListAdapter) mAdapter;
}
@Override
public T create(int width) {
super.create(width);
return (T) this;
}
@Override
public T setDividerHeight(int dividerHeight) {
super.setDividerHeight(dividerHeight);
return (T) this;
}
@Override
public T setHasDivider(boolean hasDivider) {
super.setHasDivider(hasDivider);
return (T) this;
}
@Override
public T setGroupDivider(Drawable divider) {
super.setGroupDivider(divider);
return (T) this;
}
@Override
public T setChildDivider(Drawable divider) {
super.setChildDivider(divider);
return (T) this;
}
@Override
public T setEnableOnlyExpandOne(boolean enable) {
super.setEnableOnlyExpandOne(enable);
return (T) this;
}
/**
* 可伸缩列表条目点击监听
*/
public interface OnExpandableItemClickListener {
/**
* 条目点击
*
* @param adapter
* @param group
* @param groupPosition 父节点索引
* @param childPosition 子节点索引
*/
void onExpandableItemClick(XUISimpleExpandableListAdapter adapter, ExpandableItem group, int groupPosition, int childPosition);
}
}
| 2,303 |
354 |
#include <esp_event_loop.h>
#include <esp_log.h>
#include <esp_system.h>
#include <nvs_flash.h>
#include <sys/param.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_camera.h"
static const char *TAG = "example_change_detection";
QueueHandle_t queue;
static camera_config_t detection_config = {
.pin_pwdn = CONFIG_PWDN,
.pin_reset = CONFIG_RESET,
.pin_xclk = CONFIG_XCLK,
.pin_sscb_sda = CONFIG_SDA,
.pin_sscb_scl = CONFIG_SCL,
.pin_d7 = CONFIG_D7,
.pin_d6 = CONFIG_D6,
.pin_d5 = CONFIG_D5,
.pin_d4 = CONFIG_D4,
.pin_d3 = CONFIG_D3,
.pin_d2 = CONFIG_D2,
.pin_d1 = CONFIG_D1,
.pin_d0 = CONFIG_D0,
.pin_vsync = CONFIG_VSYNC,
.pin_href = CONFIG_HREF,
.pin_pclk = CONFIG_PCLK,
//XCLK 20MHz or 10MHz
.xclk_freq_hz = CONFIG_XCLK_FREQ,
.ledc_timer = LEDC_TIMER_0,
.ledc_channel = LEDC_CHANNEL_0,
.pixel_format = PIXFORMAT_GRAYSCALE, //YUV422,GRAYSCALE,RGB565,JPEG
.frame_size = FRAMESIZE_QQVGA, //QQVGA-UXGA Do not use sizes above QVGA when not JPEG
.jpeg_quality = 12, //0-63 lower number means higher quality
.fb_count = 2 //if more than one, i2s runs in continuous mode. Use only with JPEG
};
static camera_config_t photo_config = {
.pin_pwdn = CONFIG_PWDN,
.pin_reset = CONFIG_RESET,
.pin_xclk = CONFIG_XCLK,
.pin_sscb_sda = CONFIG_SDA,
.pin_sscb_scl = CONFIG_SCL,
.pin_d7 = CONFIG_D7,
.pin_d6 = CONFIG_D6,
.pin_d5 = CONFIG_D5,
.pin_d4 = CONFIG_D4,
.pin_d3 = CONFIG_D3,
.pin_d2 = CONFIG_D2,
.pin_d1 = CONFIG_D1,
.pin_d0 = CONFIG_D0,
.pin_vsync = CONFIG_VSYNC,
.pin_href = CONFIG_HREF,
.pin_pclk = CONFIG_PCLK,
//XCLK 20MHz or 10MHz
.xclk_freq_hz = CONFIG_XCLK_FREQ,
.ledc_timer = LEDC_TIMER_0,
.ledc_channel = LEDC_CHANNEL_0,
.pixel_format = PIXFORMAT_JPEG, //YUV422,GRAYSCALE,RGB565,JPEG
.frame_size = FRAMESIZE_UXGA, //QQVGA-UXGA Do not use sizes above QVGA when not JPEG
.jpeg_quality = 12, //0-63 lower number means higher quality
.fb_count = 1 //if more than one, i2s runs in continuous mode. Use only with JPEG
};
typedef struct
{
uint8_t *buf;
size_t len;
} picture_t;
static void consume_image()
{
while (1)
{
picture_t *picture;
if (xQueueReceive(queue, &picture, (TickType_t)5))
{
ESP_LOGW(TAG, "Consume image: [%i] bytes", picture->len);
free(picture->buf);
}
vTaskDelay(5000 / portTICK_RATE_MS);
}
}
static void change_detector()
{
esp_camera_init(&detection_config);
int64_t timestamp;
uint8_t avg;
uint8_t prevAvg = 0;
while (1)
{
if (uxQueueSpacesAvailable(queue) == 0)
{
ESP_LOGE(TAG, "No point in take more pics, queue is full. Waiting 2s");
vTaskDelay(2000 / portTICK_RATE_MS);
continue;
}
timestamp = esp_timer_get_time();
camera_fb_t *pic = esp_camera_fb_get();
avg = pic->buf[0];
for (int i = 1; i < pic->len / 2; i++)
{
avg += (pic->buf[i] - avg) / i;
}
esp_camera_fb_return(pic);
ESP_LOGD(TAG, "Detecting time: %lli, Avg: %i", (esp_timer_get_time() - timestamp), avg);
if ((avg >= prevAvg && avg - prevAvg > CONFIG_MAX_ACCEPTED_AVG_DIFF) || (prevAvg > avg && prevAvg - avg > CONFIG_MAX_ACCEPTED_AVG_DIFF))
{
ESP_LOGI(TAG, "Motion detected: %i", avg);
esp_camera_deinit();
ESP_ERROR_CHECK(esp_camera_init(&photo_config));
pic = esp_camera_fb_get();
picture_t *picture = malloc(sizeof(picture_t));
if (picture == NULL)
{
ESP_LOGE(TAG, "Error while malloc picture.");
}
else
{
uint8_t *buf = malloc(pic->len);
if (buf == NULL)
{
ESP_LOGE(TAG, "Error while malloc picture buff.");
}
else
{
for (int i = 0; i < pic->len; i++)
{
buf[i] = pic->buf[i];
}
picture->buf = buf;
picture->len = pic->len;
ESP_LOGW(TAG, "Add image [%i]", picture->len);
xQueueSend(queue, &picture, portMAX_DELAY);
}
}
esp_camera_deinit();
ESP_ERROR_CHECK(esp_camera_init(&detection_config));
ESP_LOGW(TAG, "Picture time: %lli", (esp_timer_get_time() - timestamp));
}
prevAvg = avg;
}
}
void app_main()
{
queue = xQueueCreate(CONFIG_PICTURE_QUEUE_SIZE, sizeof(picture_t *));
if (queue == NULL)
{
ESP_LOGE(TAG, "Error creating the queue");
ESP_ERROR_CHECK(ESP_FAIL);
}
xTaskCreatePinnedToCore(change_detector, "change_detector", 8192, NULL, 1, NULL, 0);
xTaskCreatePinnedToCore(consume_image, "consume_image", 8192, NULL, 1, NULL, 1);
}
| 2,249 |
928 | <filename>source/cli/metacallcli/include/metacallcli/parser.hpp<gh_stars>100-1000
/*
* MetaCall Command Line Interface by Parra Studios
* Copyright (C) 2016 - 2021 <NAME> <<EMAIL>>
*
* A command line interface example as metacall wrapper.
*
*/
#ifndef METACALL_CLI_PARSER_HPP
#define METACALL_CLI_PARSER_HPP 1
/* -- Headers -- */
#include <metacall/metacall_api.h>
#include "tokenizer.hpp"
#include <iostream>
/* -- Namespace -- */
namespace metacallcli
{
/* -- Forward Declarations -- */
class tokenizer;
class parser;
/* -- Class Definition -- */
/**
* @brief
* Simple parser utility
*/
class parser
{
public:
/* -- Public Methods -- */
/**
* @brief
* Parser class constructor
*
* @param[in] it
* Tokenizer iterator reference
*/
parser(const tokenizer::iterator &it);
/**
* @brief
* Parser class destructor
*/
~parser(void);
/**
* @brief
* Check if current token is a defined type @T
*
* @param[template] T
* Type of value to check against token
*
* @return
* True if type @T is equivalent to current token
*/
template <typename T> bool is(void);
/**
* @brief
* Return current token transformed to type @T
*
* @param[template] T
* Type of value to check against token
*
* @return
* A copy of the value transformed to given type @T
*/
template <typename T> T to(void);
/**
* @brief
* Assignement operator for parser
*
* @return
* Returns a reference to itself
*/
parser &operator=(const parser &) = delete;
protected:
/* -- Private Member Data -- */
const tokenizer::iterator ⁢ /**< Tokenizer iterator reference */
};
/**
* @brief
* Custom parser utility for parameters
*/
class parser_parameter : public parser
{
public:
/* -- Public Methods -- */
/**
* @brief
* Parser class constructor
*
* @param[in] it
* Tokenizer iterator reference
*/
parser_parameter(const tokenizer::iterator &it);
/**
* @brief
* Parser class destructor
*/
~parser_parameter(void);
/**
* @brief
* Check if current token is a defined type @T
*
* @param[template] T
* Type of value to check against token
*
* @return
* True if type @T is equivalent to current token
*/
template <typename T> bool is(void);
/**
* @brief
* Return current token transformed to type @T
*
* @param[template] T
* Type of value to check against token
*
* @return
* A copy of the value transformed to given type @T
*/
template <typename T> T to(void);
/**
* @brief
* Assignement operator for parser
*
* @return
* Returns a reference to itself
*/
parser_parameter &operator=(const parser_parameter &) = delete;
};
/**
* @brief
* Check if current token is a custom quoted char ('')
*
* @return
* True if current token is a custom quoted char
*/
template <> bool parser_parameter::is<char>(void);
/**
* @brief
* Check if current token is a custom long ending with (L)
*
* @return
* True if current token is a custom long
*/
template <> bool parser_parameter::is<long>(void);
/**
* @brief
* Check if current token is a custom float ending with (f)
*
* @return
* True if current token is a custom float
*/
template <> bool parser_parameter::is<float>(void);
/**
* @brief
* Check if current token is a custom quoted string ("")
*
* @return
* True if current token is a custom quoted string
*/
template <> bool parser_parameter::is<std::string>(void);
/**
* @brief
* Return current token transformed from custom quoted char ('')
*
* @return
* A copy of the value transformed to char
*/
template <> char parser_parameter::to<char>(void);
/**
* @brief
* Return current token transformed from custom long ending with (L)
*
* @return
* A copy of the value transformed to long
*/
template <> long parser_parameter::to(void);
/**
* @brief
* Return current token transformed from custom float ending with (f)
*
* @return
* A copy of the value transformed to float
*/
template <> float parser_parameter::to(void);
/**
* @brief
* Return current token transformed from custom quoted string ('')
*
* @return
* A copy of the value transformed to string
*/
template <> std::string parser_parameter::to(void);
} /* namespace metacallcli */
/* -- Template Implementation -- */
#include <metacallcli/parser.inl>
#endif /* METACALL_CLI_PARSER_HPP */
| 1,803 |
11,356 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Imputer.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "Imputer.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
// @@protoc_insertion_point(includes)
namespace CoreML {
namespace Specification {
class ImputerDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Imputer> {
public:
double imputeddoublevalue_;
::google::protobuf::int64 imputedint64value_;
::google::protobuf::internal::ArenaStringPtr imputedstringvalue_;
const ::CoreML::Specification::DoubleVector* imputeddoublearray_;
const ::CoreML::Specification::Int64Vector* imputedint64array_;
const ::CoreML::Specification::StringToDoubleMap* imputedstringdictionary_;
const ::CoreML::Specification::Int64ToDoubleMap* imputedint64dictionary_;
double replacedoublevalue_;
::google::protobuf::int64 replaceint64value_;
::google::protobuf::internal::ArenaStringPtr replacestringvalue_;
} _Imputer_default_instance_;
namespace protobuf_Imputer_2eproto {
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField
const TableStruct::entries[] = {
{0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0},
};
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField
const TableStruct::aux[] = {
::google::protobuf::internal::AuxillaryParseTableField(),
};
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const
TableStruct::schema[] = {
{ NULL, NULL, 0, -1, -1, false },
};
void TableStruct::Shutdown() {
_Imputer_default_instance_.Shutdown();
}
void TableStruct::InitDefaultsImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::internal::InitProtobufDefaults();
::CoreML::Specification::protobuf_DataStructures_2eproto::InitDefaults();
_Imputer_default_instance_.DefaultConstruct();
}
void InitDefaults() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl);
}
void AddDescriptorsImpl() {
InitDefaults();
::CoreML::Specification::protobuf_DataStructures_2eproto::AddDescriptors();
::google::protobuf::internal::OnShutdown(&TableStruct::Shutdown);
}
void AddDescriptors() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
} // namespace protobuf_Imputer_2eproto
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Imputer::kImputedDoubleValueFieldNumber;
const int Imputer::kImputedInt64ValueFieldNumber;
const int Imputer::kImputedStringValueFieldNumber;
const int Imputer::kImputedDoubleArrayFieldNumber;
const int Imputer::kImputedInt64ArrayFieldNumber;
const int Imputer::kImputedStringDictionaryFieldNumber;
const int Imputer::kImputedInt64DictionaryFieldNumber;
const int Imputer::kReplaceDoubleValueFieldNumber;
const int Imputer::kReplaceInt64ValueFieldNumber;
const int Imputer::kReplaceStringValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Imputer::Imputer()
: ::google::protobuf::MessageLite(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_Imputer_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:CoreML.Specification.Imputer)
}
Imputer::Imputer(const Imputer& from)
: ::google::protobuf::MessageLite(),
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
clear_has_ImputedValue();
switch (from.ImputedValue_case()) {
case kImputedDoubleValue: {
set_imputeddoublevalue(from.imputeddoublevalue());
break;
}
case kImputedInt64Value: {
set_imputedint64value(from.imputedint64value());
break;
}
case kImputedStringValue: {
set_imputedstringvalue(from.imputedstringvalue());
break;
}
case kImputedDoubleArray: {
mutable_imputeddoublearray()->::CoreML::Specification::DoubleVector::MergeFrom(from.imputeddoublearray());
break;
}
case kImputedInt64Array: {
mutable_imputedint64array()->::CoreML::Specification::Int64Vector::MergeFrom(from.imputedint64array());
break;
}
case kImputedStringDictionary: {
mutable_imputedstringdictionary()->::CoreML::Specification::StringToDoubleMap::MergeFrom(from.imputedstringdictionary());
break;
}
case kImputedInt64Dictionary: {
mutable_imputedint64dictionary()->::CoreML::Specification::Int64ToDoubleMap::MergeFrom(from.imputedint64dictionary());
break;
}
case IMPUTEDVALUE_NOT_SET: {
break;
}
}
clear_has_ReplaceValue();
switch (from.ReplaceValue_case()) {
case kReplaceDoubleValue: {
set_replacedoublevalue(from.replacedoublevalue());
break;
}
case kReplaceInt64Value: {
set_replaceint64value(from.replaceint64value());
break;
}
case kReplaceStringValue: {
set_replacestringvalue(from.replacestringvalue());
break;
}
case REPLACEVALUE_NOT_SET: {
break;
}
}
// @@protoc_insertion_point(copy_constructor:CoreML.Specification.Imputer)
}
void Imputer::SharedCtor() {
clear_has_ImputedValue();
clear_has_ReplaceValue();
_cached_size_ = 0;
}
Imputer::~Imputer() {
// @@protoc_insertion_point(destructor:CoreML.Specification.Imputer)
SharedDtor();
}
void Imputer::SharedDtor() {
if (has_ImputedValue()) {
clear_ImputedValue();
}
if (has_ReplaceValue()) {
clear_ReplaceValue();
}
}
void Imputer::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const Imputer& Imputer::default_instance() {
protobuf_Imputer_2eproto::InitDefaults();
return *internal_default_instance();
}
Imputer* Imputer::New(::google::protobuf::Arena* arena) const {
Imputer* n = new Imputer;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void Imputer::clear_ImputedValue() {
// @@protoc_insertion_point(one_of_clear_start:CoreML.Specification.Imputer)
switch (ImputedValue_case()) {
case kImputedDoubleValue: {
// No need to clear
break;
}
case kImputedInt64Value: {
// No need to clear
break;
}
case kImputedStringValue: {
ImputedValue_.imputedstringvalue_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
break;
}
case kImputedDoubleArray: {
delete ImputedValue_.imputeddoublearray_;
break;
}
case kImputedInt64Array: {
delete ImputedValue_.imputedint64array_;
break;
}
case kImputedStringDictionary: {
delete ImputedValue_.imputedstringdictionary_;
break;
}
case kImputedInt64Dictionary: {
delete ImputedValue_.imputedint64dictionary_;
break;
}
case IMPUTEDVALUE_NOT_SET: {
break;
}
}
_oneof_case_[0] = IMPUTEDVALUE_NOT_SET;
}
void Imputer::clear_ReplaceValue() {
// @@protoc_insertion_point(one_of_clear_start:CoreML.Specification.Imputer)
switch (ReplaceValue_case()) {
case kReplaceDoubleValue: {
// No need to clear
break;
}
case kReplaceInt64Value: {
// No need to clear
break;
}
case kReplaceStringValue: {
ReplaceValue_.replacestringvalue_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
break;
}
case REPLACEVALUE_NOT_SET: {
break;
}
}
_oneof_case_[1] = REPLACEVALUE_NOT_SET;
}
void Imputer::Clear() {
// @@protoc_insertion_point(message_clear_start:CoreML.Specification.Imputer)
clear_ImputedValue();
clear_ReplaceValue();
}
bool Imputer::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:CoreML.Specification.Imputer)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// double imputedDoubleValue = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(9u)) {
clear_ImputedValue();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &ImputedValue_.imputeddoublevalue_)));
set_has_imputeddoublevalue();
} else {
goto handle_unusual;
}
break;
}
// int64 imputedInt64Value = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u)) {
clear_ImputedValue();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, &ImputedValue_.imputedint64value_)));
set_has_imputedint64value();
} else {
goto handle_unusual;
}
break;
}
// string imputedStringValue = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(26u)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_imputedstringvalue()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->imputedstringvalue().data(), this->imputedstringvalue().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"CoreML.Specification.Imputer.imputedStringValue"));
} else {
goto handle_unusual;
}
break;
}
// .CoreML.Specification.DoubleVector imputedDoubleArray = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(34u)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_imputeddoublearray()));
} else {
goto handle_unusual;
}
break;
}
// .CoreML.Specification.Int64Vector imputedInt64Array = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(42u)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_imputedint64array()));
} else {
goto handle_unusual;
}
break;
}
// .CoreML.Specification.StringToDoubleMap imputedStringDictionary = 6;
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(50u)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_imputedstringdictionary()));
} else {
goto handle_unusual;
}
break;
}
// .CoreML.Specification.Int64ToDoubleMap imputedInt64Dictionary = 7;
case 7: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(58u)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_imputedint64dictionary()));
} else {
goto handle_unusual;
}
break;
}
// double replaceDoubleValue = 11;
case 11: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(89u)) {
clear_ReplaceValue();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &ReplaceValue_.replacedoublevalue_)));
set_has_replacedoublevalue();
} else {
goto handle_unusual;
}
break;
}
// int64 replaceInt64Value = 12;
case 12: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(96u)) {
clear_ReplaceValue();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, &ReplaceValue_.replaceint64value_)));
set_has_replaceint64value();
} else {
goto handle_unusual;
}
break;
}
// string replaceStringValue = 13;
case 13: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(106u)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_replacestringvalue()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->replacestringvalue().data(), this->replacestringvalue().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"CoreML.Specification.Imputer.replaceStringValue"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:CoreML.Specification.Imputer)
return true;
failure:
// @@protoc_insertion_point(parse_failure:CoreML.Specification.Imputer)
return false;
#undef DO_
}
void Imputer::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:CoreML.Specification.Imputer)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// double imputedDoubleValue = 1;
if (has_imputeddoublevalue()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->imputeddoublevalue(), output);
}
// int64 imputedInt64Value = 2;
if (has_imputedint64value()) {
::google::protobuf::internal::WireFormatLite::WriteInt64(2, this->imputedint64value(), output);
}
// string imputedStringValue = 3;
if (has_imputedstringvalue()) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->imputedstringvalue().data(), this->imputedstringvalue().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"CoreML.Specification.Imputer.imputedStringValue");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
3, this->imputedstringvalue(), output);
}
// .CoreML.Specification.DoubleVector imputedDoubleArray = 4;
if (has_imputeddoublearray()) {
::google::protobuf::internal::WireFormatLite::WriteMessage(
4, *ImputedValue_.imputeddoublearray_, output);
}
// .CoreML.Specification.Int64Vector imputedInt64Array = 5;
if (has_imputedint64array()) {
::google::protobuf::internal::WireFormatLite::WriteMessage(
5, *ImputedValue_.imputedint64array_, output);
}
// .CoreML.Specification.StringToDoubleMap imputedStringDictionary = 6;
if (has_imputedstringdictionary()) {
::google::protobuf::internal::WireFormatLite::WriteMessage(
6, *ImputedValue_.imputedstringdictionary_, output);
}
// .CoreML.Specification.Int64ToDoubleMap imputedInt64Dictionary = 7;
if (has_imputedint64dictionary()) {
::google::protobuf::internal::WireFormatLite::WriteMessage(
7, *ImputedValue_.imputedint64dictionary_, output);
}
// double replaceDoubleValue = 11;
if (has_replacedoublevalue()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(11, this->replacedoublevalue(), output);
}
// int64 replaceInt64Value = 12;
if (has_replaceint64value()) {
::google::protobuf::internal::WireFormatLite::WriteInt64(12, this->replaceint64value(), output);
}
// string replaceStringValue = 13;
if (has_replacestringvalue()) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->replacestringvalue().data(), this->replacestringvalue().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"CoreML.Specification.Imputer.replaceStringValue");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
13, this->replacestringvalue(), output);
}
// @@protoc_insertion_point(serialize_end:CoreML.Specification.Imputer)
}
size_t Imputer::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:CoreML.Specification.Imputer)
size_t total_size = 0;
switch (ImputedValue_case()) {
// double imputedDoubleValue = 1;
case kImputedDoubleValue: {
total_size += 1 + 8;
break;
}
// int64 imputedInt64Value = 2;
case kImputedInt64Value: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int64Size(
this->imputedint64value());
break;
}
// string imputedStringValue = 3;
case kImputedStringValue: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->imputedstringvalue());
break;
}
// .CoreML.Specification.DoubleVector imputedDoubleArray = 4;
case kImputedDoubleArray: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*ImputedValue_.imputeddoublearray_);
break;
}
// .CoreML.Specification.Int64Vector imputedInt64Array = 5;
case kImputedInt64Array: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*ImputedValue_.imputedint64array_);
break;
}
// .CoreML.Specification.StringToDoubleMap imputedStringDictionary = 6;
case kImputedStringDictionary: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*ImputedValue_.imputedstringdictionary_);
break;
}
// .CoreML.Specification.Int64ToDoubleMap imputedInt64Dictionary = 7;
case kImputedInt64Dictionary: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*ImputedValue_.imputedint64dictionary_);
break;
}
case IMPUTEDVALUE_NOT_SET: {
break;
}
}
switch (ReplaceValue_case()) {
// double replaceDoubleValue = 11;
case kReplaceDoubleValue: {
total_size += 1 + 8;
break;
}
// int64 replaceInt64Value = 12;
case kReplaceInt64Value: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int64Size(
this->replaceint64value());
break;
}
// string replaceStringValue = 13;
case kReplaceStringValue: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->replacestringvalue());
break;
}
case REPLACEVALUE_NOT_SET: {
break;
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Imputer::CheckTypeAndMergeFrom(
const ::google::protobuf::MessageLite& from) {
MergeFrom(*::google::protobuf::down_cast<const Imputer*>(&from));
}
void Imputer::MergeFrom(const Imputer& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:CoreML.Specification.Imputer)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
switch (from.ImputedValue_case()) {
case kImputedDoubleValue: {
set_imputeddoublevalue(from.imputeddoublevalue());
break;
}
case kImputedInt64Value: {
set_imputedint64value(from.imputedint64value());
break;
}
case kImputedStringValue: {
set_imputedstringvalue(from.imputedstringvalue());
break;
}
case kImputedDoubleArray: {
mutable_imputeddoublearray()->::CoreML::Specification::DoubleVector::MergeFrom(from.imputeddoublearray());
break;
}
case kImputedInt64Array: {
mutable_imputedint64array()->::CoreML::Specification::Int64Vector::MergeFrom(from.imputedint64array());
break;
}
case kImputedStringDictionary: {
mutable_imputedstringdictionary()->::CoreML::Specification::StringToDoubleMap::MergeFrom(from.imputedstringdictionary());
break;
}
case kImputedInt64Dictionary: {
mutable_imputedint64dictionary()->::CoreML::Specification::Int64ToDoubleMap::MergeFrom(from.imputedint64dictionary());
break;
}
case IMPUTEDVALUE_NOT_SET: {
break;
}
}
switch (from.ReplaceValue_case()) {
case kReplaceDoubleValue: {
set_replacedoublevalue(from.replacedoublevalue());
break;
}
case kReplaceInt64Value: {
set_replaceint64value(from.replaceint64value());
break;
}
case kReplaceStringValue: {
set_replacestringvalue(from.replacestringvalue());
break;
}
case REPLACEVALUE_NOT_SET: {
break;
}
}
}
void Imputer::CopyFrom(const Imputer& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:CoreML.Specification.Imputer)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Imputer::IsInitialized() const {
return true;
}
void Imputer::Swap(Imputer* other) {
if (other == this) return;
InternalSwap(other);
}
void Imputer::InternalSwap(Imputer* other) {
std::swap(ImputedValue_, other->ImputedValue_);
std::swap(_oneof_case_[0], other->_oneof_case_[0]);
std::swap(ReplaceValue_, other->ReplaceValue_);
std::swap(_oneof_case_[1], other->_oneof_case_[1]);
std::swap(_cached_size_, other->_cached_size_);
}
::std::string Imputer::GetTypeName() const {
return "CoreML.Specification.Imputer";
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// Imputer
// double imputedDoubleValue = 1;
bool Imputer::has_imputeddoublevalue() const {
return ImputedValue_case() == kImputedDoubleValue;
}
void Imputer::set_has_imputeddoublevalue() {
_oneof_case_[0] = kImputedDoubleValue;
}
void Imputer::clear_imputeddoublevalue() {
if (has_imputeddoublevalue()) {
ImputedValue_.imputeddoublevalue_ = 0;
clear_has_ImputedValue();
}
}
double Imputer::imputeddoublevalue() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.Imputer.imputedDoubleValue)
if (has_imputeddoublevalue()) {
return ImputedValue_.imputeddoublevalue_;
}
return 0;
}
void Imputer::set_imputeddoublevalue(double value) {
if (!has_imputeddoublevalue()) {
clear_ImputedValue();
set_has_imputeddoublevalue();
}
ImputedValue_.imputeddoublevalue_ = value;
// @@protoc_insertion_point(field_set:CoreML.Specification.Imputer.imputedDoubleValue)
}
// int64 imputedInt64Value = 2;
bool Imputer::has_imputedint64value() const {
return ImputedValue_case() == kImputedInt64Value;
}
void Imputer::set_has_imputedint64value() {
_oneof_case_[0] = kImputedInt64Value;
}
void Imputer::clear_imputedint64value() {
if (has_imputedint64value()) {
ImputedValue_.imputedint64value_ = GOOGLE_LONGLONG(0);
clear_has_ImputedValue();
}
}
::google::protobuf::int64 Imputer::imputedint64value() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.Imputer.imputedInt64Value)
if (has_imputedint64value()) {
return ImputedValue_.imputedint64value_;
}
return GOOGLE_LONGLONG(0);
}
void Imputer::set_imputedint64value(::google::protobuf::int64 value) {
if (!has_imputedint64value()) {
clear_ImputedValue();
set_has_imputedint64value();
}
ImputedValue_.imputedint64value_ = value;
// @@protoc_insertion_point(field_set:CoreML.Specification.Imputer.imputedInt64Value)
}
// string imputedStringValue = 3;
bool Imputer::has_imputedstringvalue() const {
return ImputedValue_case() == kImputedStringValue;
}
void Imputer::set_has_imputedstringvalue() {
_oneof_case_[0] = kImputedStringValue;
}
void Imputer::clear_imputedstringvalue() {
if (has_imputedstringvalue()) {
ImputedValue_.imputedstringvalue_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_ImputedValue();
}
}
const ::std::string& Imputer::imputedstringvalue() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.Imputer.imputedStringValue)
if (has_imputedstringvalue()) {
return ImputedValue_.imputedstringvalue_.GetNoArena();
}
return *&::google::protobuf::internal::GetEmptyStringAlreadyInited();
}
void Imputer::set_imputedstringvalue(const ::std::string& value) {
// @@protoc_insertion_point(field_set:CoreML.Specification.Imputer.imputedStringValue)
if (!has_imputedstringvalue()) {
clear_ImputedValue();
set_has_imputedstringvalue();
ImputedValue_.imputedstringvalue_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
ImputedValue_.imputedstringvalue_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:CoreML.Specification.Imputer.imputedStringValue)
}
#if LANG_CXX11
void Imputer::set_imputedstringvalue(::std::string&& value) {
// @@protoc_insertion_point(field_set:CoreML.Specification.Imputer.imputedStringValue)
if (!has_imputedstringvalue()) {
clear_ImputedValue();
set_has_imputedstringvalue();
ImputedValue_.imputedstringvalue_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
ImputedValue_.imputedstringvalue_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:CoreML.Specification.Imputer.imputedStringValue)
}
#endif
void Imputer::set_imputedstringvalue(const char* value) {
GOOGLE_DCHECK(value != NULL);
if (!has_imputedstringvalue()) {
clear_ImputedValue();
set_has_imputedstringvalue();
ImputedValue_.imputedstringvalue_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
ImputedValue_.imputedstringvalue_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(value));
// @@protoc_insertion_point(field_set_char:CoreML.Specification.Imputer.imputedStringValue)
}
void Imputer::set_imputedstringvalue(const char* value, size_t size) {
if (!has_imputedstringvalue()) {
clear_ImputedValue();
set_has_imputedstringvalue();
ImputedValue_.imputedstringvalue_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
ImputedValue_.imputedstringvalue_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:CoreML.Specification.Imputer.imputedStringValue)
}
::std::string* Imputer::mutable_imputedstringvalue() {
if (!has_imputedstringvalue()) {
clear_ImputedValue();
set_has_imputedstringvalue();
ImputedValue_.imputedstringvalue_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_mutable:CoreML.Specification.Imputer.imputedStringValue)
return ImputedValue_.imputedstringvalue_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* Imputer::release_imputedstringvalue() {
// @@protoc_insertion_point(field_release:CoreML.Specification.Imputer.imputedStringValue)
if (has_imputedstringvalue()) {
clear_has_ImputedValue();
return ImputedValue_.imputedstringvalue_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
} else {
return NULL;
}
}
void Imputer::set_allocated_imputedstringvalue(::std::string* imputedstringvalue) {
if (!has_imputedstringvalue()) {
ImputedValue_.imputedstringvalue_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
clear_ImputedValue();
if (imputedstringvalue != NULL) {
set_has_imputedstringvalue();
ImputedValue_.imputedstringvalue_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
imputedstringvalue);
}
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.Imputer.imputedStringValue)
}
// .CoreML.Specification.DoubleVector imputedDoubleArray = 4;
bool Imputer::has_imputeddoublearray() const {
return ImputedValue_case() == kImputedDoubleArray;
}
void Imputer::set_has_imputeddoublearray() {
_oneof_case_[0] = kImputedDoubleArray;
}
void Imputer::clear_imputeddoublearray() {
if (has_imputeddoublearray()) {
delete ImputedValue_.imputeddoublearray_;
clear_has_ImputedValue();
}
}
const ::CoreML::Specification::DoubleVector& Imputer::imputeddoublearray() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.Imputer.imputedDoubleArray)
return has_imputeddoublearray()
? *ImputedValue_.imputeddoublearray_
: ::CoreML::Specification::DoubleVector::default_instance();
}
::CoreML::Specification::DoubleVector* Imputer::mutable_imputeddoublearray() {
if (!has_imputeddoublearray()) {
clear_ImputedValue();
set_has_imputeddoublearray();
ImputedValue_.imputeddoublearray_ = new ::CoreML::Specification::DoubleVector;
}
// @@protoc_insertion_point(field_mutable:CoreML.Specification.Imputer.imputedDoubleArray)
return ImputedValue_.imputeddoublearray_;
}
::CoreML::Specification::DoubleVector* Imputer::release_imputeddoublearray() {
// @@protoc_insertion_point(field_release:CoreML.Specification.Imputer.imputedDoubleArray)
if (has_imputeddoublearray()) {
clear_has_ImputedValue();
::CoreML::Specification::DoubleVector* temp = ImputedValue_.imputeddoublearray_;
ImputedValue_.imputeddoublearray_ = NULL;
return temp;
} else {
return NULL;
}
}
void Imputer::set_allocated_imputeddoublearray(::CoreML::Specification::DoubleVector* imputeddoublearray) {
clear_ImputedValue();
if (imputeddoublearray) {
set_has_imputeddoublearray();
ImputedValue_.imputeddoublearray_ = imputeddoublearray;
}
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.Imputer.imputedDoubleArray)
}
// .CoreML.Specification.Int64Vector imputedInt64Array = 5;
bool Imputer::has_imputedint64array() const {
return ImputedValue_case() == kImputedInt64Array;
}
void Imputer::set_has_imputedint64array() {
_oneof_case_[0] = kImputedInt64Array;
}
void Imputer::clear_imputedint64array() {
if (has_imputedint64array()) {
delete ImputedValue_.imputedint64array_;
clear_has_ImputedValue();
}
}
const ::CoreML::Specification::Int64Vector& Imputer::imputedint64array() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.Imputer.imputedInt64Array)
return has_imputedint64array()
? *ImputedValue_.imputedint64array_
: ::CoreML::Specification::Int64Vector::default_instance();
}
::CoreML::Specification::Int64Vector* Imputer::mutable_imputedint64array() {
if (!has_imputedint64array()) {
clear_ImputedValue();
set_has_imputedint64array();
ImputedValue_.imputedint64array_ = new ::CoreML::Specification::Int64Vector;
}
// @@protoc_insertion_point(field_mutable:CoreML.Specification.Imputer.imputedInt64Array)
return ImputedValue_.imputedint64array_;
}
::CoreML::Specification::Int64Vector* Imputer::release_imputedint64array() {
// @@protoc_insertion_point(field_release:CoreML.Specification.Imputer.imputedInt64Array)
if (has_imputedint64array()) {
clear_has_ImputedValue();
::CoreML::Specification::Int64Vector* temp = ImputedValue_.imputedint64array_;
ImputedValue_.imputedint64array_ = NULL;
return temp;
} else {
return NULL;
}
}
void Imputer::set_allocated_imputedint64array(::CoreML::Specification::Int64Vector* imputedint64array) {
clear_ImputedValue();
if (imputedint64array) {
set_has_imputedint64array();
ImputedValue_.imputedint64array_ = imputedint64array;
}
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.Imputer.imputedInt64Array)
}
// .CoreML.Specification.StringToDoubleMap imputedStringDictionary = 6;
bool Imputer::has_imputedstringdictionary() const {
return ImputedValue_case() == kImputedStringDictionary;
}
void Imputer::set_has_imputedstringdictionary() {
_oneof_case_[0] = kImputedStringDictionary;
}
void Imputer::clear_imputedstringdictionary() {
if (has_imputedstringdictionary()) {
delete ImputedValue_.imputedstringdictionary_;
clear_has_ImputedValue();
}
}
const ::CoreML::Specification::StringToDoubleMap& Imputer::imputedstringdictionary() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.Imputer.imputedStringDictionary)
return has_imputedstringdictionary()
? *ImputedValue_.imputedstringdictionary_
: ::CoreML::Specification::StringToDoubleMap::default_instance();
}
::CoreML::Specification::StringToDoubleMap* Imputer::mutable_imputedstringdictionary() {
if (!has_imputedstringdictionary()) {
clear_ImputedValue();
set_has_imputedstringdictionary();
ImputedValue_.imputedstringdictionary_ = new ::CoreML::Specification::StringToDoubleMap;
}
// @@protoc_insertion_point(field_mutable:CoreML.Specification.Imputer.imputedStringDictionary)
return ImputedValue_.imputedstringdictionary_;
}
::CoreML::Specification::StringToDoubleMap* Imputer::release_imputedstringdictionary() {
// @@protoc_insertion_point(field_release:CoreML.Specification.Imputer.imputedStringDictionary)
if (has_imputedstringdictionary()) {
clear_has_ImputedValue();
::CoreML::Specification::StringToDoubleMap* temp = ImputedValue_.imputedstringdictionary_;
ImputedValue_.imputedstringdictionary_ = NULL;
return temp;
} else {
return NULL;
}
}
void Imputer::set_allocated_imputedstringdictionary(::CoreML::Specification::StringToDoubleMap* imputedstringdictionary) {
clear_ImputedValue();
if (imputedstringdictionary) {
set_has_imputedstringdictionary();
ImputedValue_.imputedstringdictionary_ = imputedstringdictionary;
}
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.Imputer.imputedStringDictionary)
}
// .CoreML.Specification.Int64ToDoubleMap imputedInt64Dictionary = 7;
bool Imputer::has_imputedint64dictionary() const {
return ImputedValue_case() == kImputedInt64Dictionary;
}
void Imputer::set_has_imputedint64dictionary() {
_oneof_case_[0] = kImputedInt64Dictionary;
}
void Imputer::clear_imputedint64dictionary() {
if (has_imputedint64dictionary()) {
delete ImputedValue_.imputedint64dictionary_;
clear_has_ImputedValue();
}
}
const ::CoreML::Specification::Int64ToDoubleMap& Imputer::imputedint64dictionary() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.Imputer.imputedInt64Dictionary)
return has_imputedint64dictionary()
? *ImputedValue_.imputedint64dictionary_
: ::CoreML::Specification::Int64ToDoubleMap::default_instance();
}
::CoreML::Specification::Int64ToDoubleMap* Imputer::mutable_imputedint64dictionary() {
if (!has_imputedint64dictionary()) {
clear_ImputedValue();
set_has_imputedint64dictionary();
ImputedValue_.imputedint64dictionary_ = new ::CoreML::Specification::Int64ToDoubleMap;
}
// @@protoc_insertion_point(field_mutable:CoreML.Specification.Imputer.imputedInt64Dictionary)
return ImputedValue_.imputedint64dictionary_;
}
::CoreML::Specification::Int64ToDoubleMap* Imputer::release_imputedint64dictionary() {
// @@protoc_insertion_point(field_release:CoreML.Specification.Imputer.imputedInt64Dictionary)
if (has_imputedint64dictionary()) {
clear_has_ImputedValue();
::CoreML::Specification::Int64ToDoubleMap* temp = ImputedValue_.imputedint64dictionary_;
ImputedValue_.imputedint64dictionary_ = NULL;
return temp;
} else {
return NULL;
}
}
void Imputer::set_allocated_imputedint64dictionary(::CoreML::Specification::Int64ToDoubleMap* imputedint64dictionary) {
clear_ImputedValue();
if (imputedint64dictionary) {
set_has_imputedint64dictionary();
ImputedValue_.imputedint64dictionary_ = imputedint64dictionary;
}
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.Imputer.imputedInt64Dictionary)
}
// double replaceDoubleValue = 11;
bool Imputer::has_replacedoublevalue() const {
return ReplaceValue_case() == kReplaceDoubleValue;
}
void Imputer::set_has_replacedoublevalue() {
_oneof_case_[1] = kReplaceDoubleValue;
}
void Imputer::clear_replacedoublevalue() {
if (has_replacedoublevalue()) {
ReplaceValue_.replacedoublevalue_ = 0;
clear_has_ReplaceValue();
}
}
double Imputer::replacedoublevalue() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.Imputer.replaceDoubleValue)
if (has_replacedoublevalue()) {
return ReplaceValue_.replacedoublevalue_;
}
return 0;
}
void Imputer::set_replacedoublevalue(double value) {
if (!has_replacedoublevalue()) {
clear_ReplaceValue();
set_has_replacedoublevalue();
}
ReplaceValue_.replacedoublevalue_ = value;
// @@protoc_insertion_point(field_set:CoreML.Specification.Imputer.replaceDoubleValue)
}
// int64 replaceInt64Value = 12;
bool Imputer::has_replaceint64value() const {
return ReplaceValue_case() == kReplaceInt64Value;
}
void Imputer::set_has_replaceint64value() {
_oneof_case_[1] = kReplaceInt64Value;
}
void Imputer::clear_replaceint64value() {
if (has_replaceint64value()) {
ReplaceValue_.replaceint64value_ = GOOGLE_LONGLONG(0);
clear_has_ReplaceValue();
}
}
::google::protobuf::int64 Imputer::replaceint64value() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.Imputer.replaceInt64Value)
if (has_replaceint64value()) {
return ReplaceValue_.replaceint64value_;
}
return GOOGLE_LONGLONG(0);
}
void Imputer::set_replaceint64value(::google::protobuf::int64 value) {
if (!has_replaceint64value()) {
clear_ReplaceValue();
set_has_replaceint64value();
}
ReplaceValue_.replaceint64value_ = value;
// @@protoc_insertion_point(field_set:CoreML.Specification.Imputer.replaceInt64Value)
}
// string replaceStringValue = 13;
bool Imputer::has_replacestringvalue() const {
return ReplaceValue_case() == kReplaceStringValue;
}
void Imputer::set_has_replacestringvalue() {
_oneof_case_[1] = kReplaceStringValue;
}
void Imputer::clear_replacestringvalue() {
if (has_replacestringvalue()) {
ReplaceValue_.replacestringvalue_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_ReplaceValue();
}
}
const ::std::string& Imputer::replacestringvalue() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.Imputer.replaceStringValue)
if (has_replacestringvalue()) {
return ReplaceValue_.replacestringvalue_.GetNoArena();
}
return *&::google::protobuf::internal::GetEmptyStringAlreadyInited();
}
void Imputer::set_replacestringvalue(const ::std::string& value) {
// @@protoc_insertion_point(field_set:CoreML.Specification.Imputer.replaceStringValue)
if (!has_replacestringvalue()) {
clear_ReplaceValue();
set_has_replacestringvalue();
ReplaceValue_.replacestringvalue_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
ReplaceValue_.replacestringvalue_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:CoreML.Specification.Imputer.replaceStringValue)
}
#if LANG_CXX11
void Imputer::set_replacestringvalue(::std::string&& value) {
// @@protoc_insertion_point(field_set:CoreML.Specification.Imputer.replaceStringValue)
if (!has_replacestringvalue()) {
clear_ReplaceValue();
set_has_replacestringvalue();
ReplaceValue_.replacestringvalue_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
ReplaceValue_.replacestringvalue_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:CoreML.Specification.Imputer.replaceStringValue)
}
#endif
void Imputer::set_replacestringvalue(const char* value) {
GOOGLE_DCHECK(value != NULL);
if (!has_replacestringvalue()) {
clear_ReplaceValue();
set_has_replacestringvalue();
ReplaceValue_.replacestringvalue_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
ReplaceValue_.replacestringvalue_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(value));
// @@protoc_insertion_point(field_set_char:CoreML.Specification.Imputer.replaceStringValue)
}
void Imputer::set_replacestringvalue(const char* value, size_t size) {
if (!has_replacestringvalue()) {
clear_ReplaceValue();
set_has_replacestringvalue();
ReplaceValue_.replacestringvalue_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
ReplaceValue_.replacestringvalue_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:CoreML.Specification.Imputer.replaceStringValue)
}
::std::string* Imputer::mutable_replacestringvalue() {
if (!has_replacestringvalue()) {
clear_ReplaceValue();
set_has_replacestringvalue();
ReplaceValue_.replacestringvalue_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_mutable:CoreML.Specification.Imputer.replaceStringValue)
return ReplaceValue_.replacestringvalue_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* Imputer::release_replacestringvalue() {
// @@protoc_insertion_point(field_release:CoreML.Specification.Imputer.replaceStringValue)
if (has_replacestringvalue()) {
clear_has_ReplaceValue();
return ReplaceValue_.replacestringvalue_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
} else {
return NULL;
}
}
void Imputer::set_allocated_replacestringvalue(::std::string* replacestringvalue) {
if (!has_replacestringvalue()) {
ReplaceValue_.replacestringvalue_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
clear_ReplaceValue();
if (replacestringvalue != NULL) {
set_has_replacestringvalue();
ReplaceValue_.replacestringvalue_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
replacestringvalue);
}
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.Imputer.replaceStringValue)
}
bool Imputer::has_ImputedValue() const {
return ImputedValue_case() != IMPUTEDVALUE_NOT_SET;
}
void Imputer::clear_has_ImputedValue() {
_oneof_case_[0] = IMPUTEDVALUE_NOT_SET;
}
bool Imputer::has_ReplaceValue() const {
return ReplaceValue_case() != REPLACEVALUE_NOT_SET;
}
void Imputer::clear_has_ReplaceValue() {
_oneof_case_[1] = REPLACEVALUE_NOT_SET;
}
Imputer::ImputedValueCase Imputer::ImputedValue_case() const {
return Imputer::ImputedValueCase(_oneof_case_[0]);
}
Imputer::ReplaceValueCase Imputer::ReplaceValue_case() const {
return Imputer::ReplaceValueCase(_oneof_case_[1]);
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace Specification
} // namespace CoreML
// @@protoc_insertion_point(global_scope)
| 16,811 |
474 | <gh_stars>100-1000
/* Copyright 2016 Samsung Electronics Co., LTD
*
* 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.gearvrf;
/**
* An interface for event receivers. An event receiver
* contains a list of event listeners, and an event can be
* delivered to it.
*/
public interface IEventReceiver {
/**
* Returns the event receiver implementation so that events can be delivered.
* @return event receiver
*/
GVREventReceiver getEventReceiver();
} | 270 |
1,806 | /*
* -\-\-
* Spotify Apollo Testing Helpers
* --
* Copyright (C) 2013 - 2015 Spotify AB
* --
* 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.spotify.apollo.test;
import com.google.inject.multibindings.Multibinder;
import com.spotify.apollo.environment.ClientDecorator;
import com.spotify.apollo.environment.IncomingRequestAwareClient;
import com.spotify.apollo.module.AbstractApolloModule;
import com.spotify.apollo.module.ApolloModule;
class ForwardingStubClientModule extends AbstractApolloModule
implements ClientDecorator {
private final boolean forward;
private final IncomingRequestAwareClient stubClient;
private ForwardingStubClientModule(boolean forward, IncomingRequestAwareClient stubClient) {
this.forward = forward;
this.stubClient = stubClient;
}
public static ApolloModule create(boolean forward, IncomingRequestAwareClient stubClient) {
return new ForwardingStubClientModule(forward, stubClient);
}
@Override
protected void configure() {
Multibinder.newSetBinder(binder(), ClientDecorator.class)
.addBinding().toInstance(this);
}
@Override
public String getId() {
return "forwarding-stub-client";
}
@Override
public IncomingRequestAwareClient apply(IncomingRequestAwareClient client) {
return forward ? new FallbackClient(stubClient, client) : stubClient;
}
}
| 554 |
1,318 | from unittest import TestCase
from inspect import Signature, Parameter, signature
from ...traitlets import HasTraits, Int, Unicode
from ..decorators import signature_has_traits
class TestExpandSignature(TestCase):
def test_no_init(self):
@signature_has_traits
class Foo(HasTraits):
number1 = Int()
number2 = Int()
value = Unicode('Hello')
parameters = signature(Foo).parameters
parameter_names = list(parameters)
self.assertIs(parameters['args'].kind, Parameter.VAR_POSITIONAL)
self.assertEqual('args', parameter_names[0])
self.assertIs(parameters['number1'].kind, Parameter.KEYWORD_ONLY)
self.assertIs(parameters['number2'].kind, Parameter.KEYWORD_ONLY)
self.assertIs(parameters['value'].kind, Parameter.KEYWORD_ONLY)
self.assertIs(parameters['kwargs'].kind, Parameter.VAR_KEYWORD)
self.assertEqual('kwargs', parameter_names[-1])
f = Foo(number1=32, value='World')
self.assertEqual(f.number1, 32)
self.assertEqual(f.number2, 0)
self.assertEqual(f.value, 'World')
def test_partial_init(self):
@signature_has_traits
class Foo(HasTraits):
number1 = Int()
number2 = Int()
value = Unicode('Hello')
def __init__(self, arg1, **kwargs):
self.arg1 = arg1
super(Foo, self).__init__(**kwargs)
parameters = signature(Foo).parameters
parameter_names = list(parameters)
self.assertIs(parameters['arg1'].kind, Parameter.POSITIONAL_OR_KEYWORD)
self.assertEqual('arg1', parameter_names[0])
self.assertIs(parameters['number1'].kind, Parameter.KEYWORD_ONLY)
self.assertIs(parameters['number2'].kind, Parameter.KEYWORD_ONLY)
self.assertIs(parameters['value'].kind, Parameter.KEYWORD_ONLY)
self.assertIs(parameters['kwargs'].kind, Parameter.VAR_KEYWORD)
self.assertEqual('kwargs', parameter_names[-1])
f = Foo(1, number1=32, value='World')
self.assertEqual(f.arg1, 1)
self.assertEqual(f.number1, 32)
self.assertEqual(f.number2, 0)
self.assertEqual(f.value, 'World')
def test_duplicate_init(self):
@signature_has_traits
class Foo(HasTraits):
number1 = Int()
number2 = Int()
def __init__(self, number1, **kwargs):
self.test = number1
super(Foo, self).__init__(number1=number1, **kwargs)
parameters = signature(Foo).parameters
parameter_names = list(parameters)
self.assertListEqual(parameter_names, ['number1', 'number2', 'kwargs'])
f = Foo(number1=32, number2=36)
self.assertEqual(f.test, 32)
self.assertEqual(f.number1, 32)
self.assertEqual(f.number2, 36)
def test_full_init(self):
@signature_has_traits
class Foo(HasTraits):
number1 = Int()
number2 = Int()
value = Unicode('Hello')
def __init__(self, arg1, arg2=None, *pos_args, **kw_args):
self.arg1 = arg1
self.arg2 = arg2
self.pos_args = pos_args
self.kw_args = kw_args
super(Foo, self).__init__(*pos_args, **kw_args)
parameters = signature(Foo).parameters
parameter_names = list(parameters)
self.assertIs(parameters['arg1'].kind, Parameter.POSITIONAL_OR_KEYWORD)
self.assertEqual('arg1', parameter_names[0])
self.assertIs(parameters['arg2'].kind, Parameter.POSITIONAL_OR_KEYWORD)
self.assertEqual('arg2', parameter_names[1])
self.assertIs(parameters['pos_args'].kind, Parameter.VAR_POSITIONAL)
self.assertEqual('pos_args', parameter_names[2])
self.assertIs(parameters['number1'].kind, Parameter.KEYWORD_ONLY)
self.assertIs(parameters['number2'].kind, Parameter.KEYWORD_ONLY)
self.assertIs(parameters['value'].kind, Parameter.KEYWORD_ONLY)
self.assertIs(parameters['kw_args'].kind, Parameter.VAR_KEYWORD)
self.assertEqual('kw_args', parameter_names[-1])
f = Foo(1, 3, 45, 'hey', number1=32, value='World')
self.assertEqual(f.arg1, 1)
self.assertEqual(f.arg2, 3)
self.assertTupleEqual(f.pos_args, (45, 'hey'))
self.assertEqual(f.number1, 32)
self.assertEqual(f.number2, 0)
self.assertEqual(f.value, 'World')
def test_no_kwargs(self):
with self.assertRaises(RuntimeError):
@signature_has_traits
class Foo(HasTraits):
number1 = Int()
number2 = Int()
def __init__(self, arg1, arg2=None):
pass
| 2,275 |
5,541 | import os, sys
sys.path.insert(0, os.path.abspath(".."))
import pandas as pd
import numpy as np
import pytest
import pycaret.classification
import pycaret.regression
import pycaret.datasets
def test_classification_convert_model():
# loading dataset
data = pycaret.datasets.get_data("blood")
# initialize setup
clf1 = pycaret.classification.setup(
data,
target="Class",
silent=True,
html=False,
n_jobs=1,
)
# train model
lr = pycaret.classification.create_model("lr")
# convert model
lr_java = pycaret.classification.convert_model(lr, "java")
assert isinstance(lr_java, str)
def test_regression_convert_model():
# loading dataset
data = pycaret.datasets.get_data("boston")
# initialize setup
reg1 = pycaret.regression.setup(
data,
target="medv",
silent=True,
html=False,
n_jobs=1,
)
# train model
lr = pycaret.regression.create_model("lr")
# convert model
lr_java = pycaret.regression.convert_model(lr, "java")
assert isinstance(lr_java, str)
if __name__ == "__main__":
test_classification_convert_model()
test_regression_convert_model() | 514 |
2,123 | #include "stdlib.h"
#include "util.h"
#include "dataset.h"
void __attribute__((noinline)) matmul(const int coreid, const int ncores, const int lda, const data_t A[], const data_t B[], data_t C[] )
{
// ***************************** //
// **** ADD YOUR CODE HERE ***** //
// ***************************** //
//
// feel free to make a separate function for MI and MSI versions.
int i, j, k, ii, jj, bsize, start;
bsize = 16;
start = bsize*coreid;
for ( jj = start; jj < lda; jj += bsize*ncores) {
int first = 1;
for ( ii = start; ii !=start || first; ii=(bsize+ii) % lda) {
first = 0;
for ( j = jj; j < lda && j < jj + bsize; j+=4) {
for ( i = ii; i < lda && i < ii + bsize; i+=2) {
data_t c1 = C[i + j*lda];
data_t c2 = C[i + j*lda + 1];
data_t c3 = C[i + (j+1)*lda];
data_t c4 = C[i + (j+1)*lda + 1];
data_t c5 = C[i + (j+2)*lda];
data_t c6 = C[i + (j+2)*lda + 1];
data_t c7 = C[i + (j+3)*lda];
data_t c8 = C[i + (j+3)*lda + 1];
for ( k = 0; k < lda; k+=8){
for (int x = 0; x < 8; x++) {
data_t a = A[j*lda + k+x];
data_t a1 = A[(j+1)*lda +k+x];
data_t a2 = A[(j+2)*lda +k+x];
data_t a3 = A[(j+3)*lda +k+x];
data_t b1 = B[(k+x)*lda + i];
data_t b2 = B[(k+x)*lda + i + 1];
c1 += a * b1;
c2 += a * b2;
c3 += a1* b1;
c4 += a1* b2;
c5 += a2* b1;
c6 += a2* b2;
c7 += a3* b1;
c8 += a3* b2;
}
}
C[i + j*lda] = c1;
C[i + j*lda + 1] = c2;
C[i + (j+1)*lda] = c3;
C[i + (j+1)*lda + 1] = c4;
C[i + (j+2)*lda] = c5;
C[i + (j+2)*lda + 1] = c6;
C[i + (j+3)*lda] = c7;
C[i + (j+3)*lda + 1] = c8;
}
}
}
}
}
| 922 |
423 | // The MIT License (MIT)
// Copyright © 2015 AppsLandia. All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package com.appslandia.plum.base;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServletRequest;
import org.junit.Assert;
import org.junit.Test;
import com.appslandia.common.caching.AppCacheManager;
import com.appslandia.common.utils.MimeTypes;
import com.appslandia.plum.results.TextResult;
/**
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public class EnableCacheTest extends MockTestBase {
@Override
protected void initialize() {
container.register(TestController.class, TestController.class);
MemAppCacheManager appCacheManager = container.getObject(AppCacheManager.class);
appCacheManager.createCache(EnableCache.DEFAULT_CACHE, 32);
}
private void initCacheResponse() throws Exception {
execute(container.createRequest("GET", "http://localhost/app/testController/testCache"), container.createResponse());
}
@Test
public void test_testCache() {
try {
executeCurrent("GET", "http://localhost/app/testController/testCache");
Assert.assertEquals(getCurrentResponse().getStatus(), 200);
Assert.assertEquals(getCurrentResponse().getContent().toString(StandardCharsets.UTF_8), "data");
Assert.assertNotNull(getCurrentResponse().getHeader("Content-Length"));
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
}
@Test
public void test_testCache_HEAD() {
try {
executeCurrent("HEAD", "http://localhost/app/testController/testCache");
Assert.assertEquals(getCurrentResponse().getStatus(), 200);
Assert.assertNotNull(getCurrentResponse().getHeader("Content-Length"));
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
}
@Test
public void test_testCache_next() {
try {
initCacheResponse();
getCurrentRequest().addParameter("next", "true");
executeCurrent("GET", "http://localhost/app/testController/testCache");
Assert.assertEquals(getCurrentResponse().getStatus(), 200);
Assert.assertEquals(getCurrentResponse().getContent().toString(StandardCharsets.UTF_8), "data");
Assert.assertNotNull(getCurrentResponse().getHeader("Content-Length"));
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
}
@Test
public void test_testCache_next_HEAD() {
try {
initCacheResponse();
getCurrentRequest().addParameter("next", "true");
executeCurrent("HEAD", "http://localhost/app/testController/testCache");
Assert.assertEquals(getCurrentResponse().getStatus(), 200);
Assert.assertNotNull(getCurrentResponse().getHeader("Content-Length"));
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
}
@Controller("testController")
public static class TestController {
@HttpGet
@EnableCache(cacheKey = "/{controller}/{action}")
public ActionResult testCache(HttpServletRequest request) throws Exception {
if (request.getParameter("next") != null) {
throw new Exception();
}
return new TextResult("data", MimeTypes.TEXT_PLAIN);
}
}
}
| 1,266 |
1,018 | /*
* Copyright 2017-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.glowroot.common.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import com.google.common.io.Files;
import static com.google.common.base.Charsets.ISO_8859_1;
public class PropertiesFiles {
private PropertiesFiles() {}
public static Properties load(File propFile) throws IOException {
Properties props = new Properties();
InputStream in = new FileInputStream(propFile);
try {
props.load(in);
} finally {
in.close();
}
return props;
}
public static void upgradeIfNeeded(File propFile, Map<String, String> findReplacePairs)
throws IOException {
// properties files must be ISO_8859_1
String content = Files.toString(propFile, ISO_8859_1);
boolean modified = false;
for (Map.Entry<String, String> entry : findReplacePairs.entrySet()) {
String find = entry.getKey();
if (content.contains(find)) {
content = content.replace(find, entry.getValue());
modified = true;
}
}
if (modified) {
Files.write(content, propFile, ISO_8859_1);
}
}
}
| 705 |
637 | <reponame>Nekoer/uncle-novel
package com.unclezs.novel.app.main.views.components.cell;
import cn.hutool.core.io.FileUtil;
import com.unclezs.novel.analyzer.spider.Spider;
import com.unclezs.novel.analyzer.util.StringUtils;
import com.unclezs.novel.app.framework.components.ModalBox;
import com.unclezs.novel.app.framework.components.Toast;
import com.unclezs.novel.app.framework.components.icon.Icon;
import com.unclezs.novel.app.framework.components.icon.IconFont;
import com.unclezs.novel.app.framework.util.DesktopUtils;
import com.unclezs.novel.app.framework.util.NodeHelper;
import com.unclezs.novel.app.main.core.spider.SpiderWrapper;
import com.unclezs.novel.app.main.util.EbookUtils;
import com.unclezs.novel.app.main.views.home.DownloadManagerView;
import javafx.beans.InvalidationListener;
import javafx.scene.control.TableCell;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import java.io.File;
/**
* @author <EMAIL>
* @date 2021/4/30 11:54
*/
public class DownloadActionTableCell extends TableCell<SpiderWrapper, SpiderWrapper> {
private final HBox box;
private final Icon start;
private final Icon pause;
private final Icon stop;
private final Icon retry;
private final Icon folder;
private final Icon save;
private final InvalidationListener stateListener;
private SpiderWrapper item;
public DownloadActionTableCell() {
NodeHelper.addClass(this, "download-action-cell");
setGraphic(null);
this.start = NodeHelper.addClass(new Icon(IconFont.RUN));
this.start.setTooltip(new Tooltip("开始"));
this.pause = NodeHelper.addClass(new Icon(IconFont.PAUSE_RUN));
this.pause.setTooltip(new Tooltip("暂停"));
this.retry = NodeHelper.addClass(new Icon(IconFont.RETRY));
this.retry.setTooltip(new Tooltip("重试失败章节"));
this.save = NodeHelper.addClass(new Icon(IconFont.SAVE));
this.save.setTooltip(new Tooltip("忽略错误"));
this.stop = NodeHelper.addClass(new Icon(IconFont.STOP), "delete");
stop.setTooltip(new Tooltip("停止"));
this.folder = NodeHelper.addClass(new Icon(IconFont.FOLDER));
folder.setTooltip(new Tooltip("文件夹"));
this.box = NodeHelper.addClass(new HBox(start, stop, folder), "action-cell", "download-action");
start.setOnMouseClicked(event -> {
item.runTask();
Toast.success("启动");
});
pause.setOnMouseClicked(e -> {
item.pause();
Toast.success("暂停");
});
retry.setOnMouseClicked(e -> item.retry());
save.setOnMouseClicked(e -> ModalBox.confirm(confirmSave -> {
if (Boolean.TRUE.equals(confirmSave)) {
item.save();
}
}).title("确定忽略错误吗").message("忽略错误可能出现章节内容不完整的情况").show());
stop.setOnMouseClicked(event -> {
String savePath = item.getSpider().getSavePath();
String name = StringUtils.removeInvalidSymbol(item.getName());
item.stop();
getTableView().getItems().remove(item);
// 删除临时文件
if (StringUtils.isNotBlank(savePath) && StringUtils.isNotBlank(name)) {
FileUtil.del(FileUtil.file(savePath, name));
FileUtil.del(FileUtil.file(savePath, name + EbookUtils.EBOOK_TMP_SUFFIX));
}
// 删除缓存
FileUtil.del(FileUtil.file(DownloadManagerView.TMP_DIR, item.getId()));
});
folder.setOnMouseClicked(e -> DesktopUtils.openDir(new File(item.getSpider().getSavePath())));
// 状态监听
this.stateListener = e -> setState();
}
@Override
protected void updateItem(SpiderWrapper item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setGraphic(null);
setText(null);
} else {
// 移除旧的监听
if (this.item != null) {
this.item.getState().removeListener(stateListener);
}
// 添加新的监听
this.item = item;
setState();
item.getState().addListener(stateListener);
setGraphic(box);
}
}
private void setState() {
Integer state = item.getState().get();
pause.setDisable(false);
switch (state) {
case Spider.COMPLETE:
box.getChildren().setAll(retry, stop, folder, save);
break;
case Spider.RUNNING:
case SpiderWrapper.WAIT_RUN:
box.getChildren().setAll(pause, stop, folder);
break;
case Spider.PIPELINE:
box.getChildren().setAll(pause, stop, folder);
pause.setDisable(true);
break;
case Spider.PAUSED:
default:
box.getChildren().setAll(start, stop, folder);
}
}
}
| 1,897 |
852 | #ifndef EgammaCandidates_Electron_h
#define EgammaCandidates_Electron_h
/** \class reco::Electron
*
* Reco Candidates with an Electron component
*
* \author <NAME>, INFN
*
*
*/
#include "DataFormats/RecoCandidate/interface/RecoCandidate.h"
#include "DataFormats/GsfTrackReco/interface/GsfTrack.h"
namespace reco {
class Electron : public RecoCandidate {
public:
/// default constructor
Electron() : RecoCandidate() {}
/// constructor from values
Electron(Charge q, const LorentzVector& p4, const Point& vtx = Point(0, 0, 0))
: RecoCandidate(q, p4, vtx, -11 * q) {}
/// destructor
~Electron() override;
/// returns a clone of the candidate
Electron* clone() const override;
/// reference to a Track
using reco::RecoCandidate::track; // avoid hiding the base
reco::TrackRef track() const override;
/// reference to a SuperCluster
reco::SuperClusterRef superCluster() const override;
/// reference to a GsfTrack
reco::GsfTrackRef gsfTrack() const override;
/// set refrence to Photon component
void setSuperCluster(const reco::SuperClusterRef& r) { superCluster_ = r; }
/// set refrence to Track component
void setTrack(const reco::TrackRef& r) { track_ = r; }
/// set reference to GsfTrack component
void setGsfTrack(const reco::GsfTrackRef& r) { gsfTrack_ = r; }
bool isElectron() const override;
private:
/// check overlap with another candidate
bool overlap(const Candidate&) const override;
/// reference to a SuperCluster
reco::SuperClusterRef superCluster_;
/// reference to a Track
reco::TrackRef track_;
/// reference to a GsfTrack;
reco::GsfTrackRef gsfTrack_;
};
} // namespace reco
#endif
| 616 |
2,757 | <gh_stars>1000+
"""Interface to the Expat non-validating XML parser."""
__version__ = '$Revision$'
from pyexpat import *
| 46 |
2,440 | from cyberbrain import InitialValue, Binding, Symbol, Return
def f():
return 1
def test_ref_outside(trace, check_golden_file):
@trace
def test_ref_outside_inner():
a = f()
test_ref_outside_inner()
| 85 |
1,168 | <reponame>wcalandro/kythe
// Checks that we correctly attribute class template instantiation
// via C++17 constructor argument deduction and guides.
//- @S defines/binding StructS
struct S {};
template <typename T>
//- @C defines/binding TemplC
struct C {
//- @C defines/binding Ctor0
C() { }
//- @C defines/binding CtorT
C(T) { }
template <typename U>
//- @C defines/binding CtorU
C(U, U) { }
};
//- @#1C ref TemplC
//- @S ref StructS
C() -> C<S>;
// TODO(shahms): This should not be considered an implicit ref.
//- @#1C ref/implicit TemplC
template <typename U> C(U, U) -> C<U>;
void f() {
//- @C ref TemplC
//- @cz ref/call Ctor0App
//- Ctor0App param.0 Ctor0
C cz;
//- @C ref TemplC
//- @"ct(S{})" ref/call CtorTApp
//- CtorTApp param.0 CtorT
C ct(S{});
//- @C ref TemplC
//- @"cu(S{}, S{})" ref/call CtorUApp
//- CtorUApp param.0 CtorU
C cu(S{}, S{});
}
| 381 |
777 | <filename>net/nqe/network_quality_estimator_params.cc<gh_stars>100-1000
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/nqe/network_quality_estimator_params.h"
#include <stdint.h>
#include "base/strings/string_number_conversions.h"
#include "base/time/time.h"
namespace {
// Minimum valid value of the variation parameter that holds RTT (in
// milliseconds) values.
static const int kMinimumRTTVariationParameterMsec = 1;
// Minimum valid value of the variation parameter that holds throughput (in
// kilobits per second) values.
static const int kMinimumThroughputVariationParameterKbps = 1;
// Returns the value of |parameter_name| read from |variation_params|. If the
// value is unavailable from |variation_params|, then |default_value| is
// returned.
int64_t GetValueForVariationParam(
const std::map<std::string, std::string>& variation_params,
const std::string& parameter_name,
int64_t default_value) {
const auto it = variation_params.find(parameter_name);
int64_t variations_value = default_value;
if (it != variation_params.end() &&
base::StringToInt64(it->second, &variations_value)) {
return variations_value;
}
return default_value;
}
// Returns the variation value for |parameter_name|. If the value is
// unavailable, |default_value| is returned.
double GetDoubleValueForVariationParamWithDefaultValue(
const std::map<std::string, std::string>& variation_params,
const std::string& parameter_name,
double default_value) {
const auto it = variation_params.find(parameter_name);
if (it == variation_params.end())
return default_value;
double variations_value = default_value;
if (!base::StringToDouble(it->second, &variations_value))
return default_value;
return variations_value;
}
// Returns the variation value for |parameter_name|. If the value is
// unavailable, |default_value| is returned.
std::string GetStringValueForVariationParamWithDefaultValue(
const std::map<std::string, std::string>& variation_params,
const std::string& parameter_name,
const std::string& default_value) {
const auto it = variation_params.find(parameter_name);
if (it == variation_params.end())
return default_value;
return it->second;
}
} // namespace
namespace net {
namespace nqe {
namespace internal {
std::string GetEffectiveConnectionTypeAlgorithm(
const std::map<std::string, std::string>& variation_params) {
const auto it = variation_params.find("effective_connection_type_algorithm");
if (it == variation_params.end())
return std::string();
return it->second;
}
double GetWeightMultiplierPerSecond(
const std::map<std::string, std::string>& variation_params) {
// Default value of the half life (in seconds) for computing time weighted
// percentiles. Every half life, the weight of all observations reduces by
// half. Lowering the half life would reduce the weight of older values
// faster.
int half_life_seconds = 60;
int32_t variations_value = 0;
auto it = variation_params.find("HalfLifeSeconds");
if (it != variation_params.end() &&
base::StringToInt(it->second, &variations_value) &&
variations_value >= 1) {
half_life_seconds = variations_value;
}
DCHECK_GT(half_life_seconds, 0);
return pow(0.5, 1.0 / half_life_seconds);
}
double GetWeightMultiplierPerDbm(
const std::map<std::string, std::string>& variation_params) {
// The default weight is set to 1.0, so by default, RSSI has no effect on the
// observation's weight.
return GetDoubleValueForVariationParamWithDefaultValue(
variation_params, "rssi_weight_per_dbm", 1.0);
}
const char* GetNameForConnectionType(
net::NetworkChangeNotifier::ConnectionType connection_type) {
switch (connection_type) {
case net::NetworkChangeNotifier::CONNECTION_UNKNOWN:
return "Unknown";
case net::NetworkChangeNotifier::CONNECTION_ETHERNET:
return "Ethernet";
case net::NetworkChangeNotifier::CONNECTION_WIFI:
return "WiFi";
case net::NetworkChangeNotifier::CONNECTION_2G:
return "2G";
case net::NetworkChangeNotifier::CONNECTION_3G:
return "3G";
case net::NetworkChangeNotifier::CONNECTION_4G:
return "4G";
case net::NetworkChangeNotifier::CONNECTION_NONE:
return "None";
case net::NetworkChangeNotifier::CONNECTION_BLUETOOTH:
return "Bluetooth";
default:
NOTREACHED();
break;
}
return "";
}
void ObtainDefaultObservations(
const std::map<std::string, std::string>& variation_params,
NetworkQuality default_observations[]) {
for (size_t i = 0; i < NetworkChangeNotifier::CONNECTION_LAST; ++i) {
DCHECK_EQ(InvalidRTT(), default_observations[i].http_rtt());
DCHECK_EQ(InvalidRTT(), default_observations[i].transport_rtt());
DCHECK_EQ(kInvalidThroughput,
default_observations[i].downstream_throughput_kbps());
}
// Default observations for HTTP RTT, transport RTT, and downstream throughput
// Kbps for the various connection types. These may be overridden by
// variations params. The default observation for a connection type
// corresponds to typical network quality for that connection type.
default_observations[NetworkChangeNotifier::CONNECTION_UNKNOWN] =
NetworkQuality(base::TimeDelta::FromMilliseconds(115),
base::TimeDelta::FromMilliseconds(55), 1961);
default_observations[NetworkChangeNotifier::CONNECTION_ETHERNET] =
NetworkQuality(base::TimeDelta::FromMilliseconds(90),
base::TimeDelta::FromMilliseconds(33), 1456);
default_observations[NetworkChangeNotifier::CONNECTION_WIFI] =
NetworkQuality(base::TimeDelta::FromMilliseconds(116),
base::TimeDelta::FromMilliseconds(66), 2658);
default_observations[NetworkChangeNotifier::CONNECTION_2G] =
NetworkQuality(base::TimeDelta::FromMilliseconds(1726),
base::TimeDelta::FromMilliseconds(1531), 74);
default_observations[NetworkChangeNotifier::CONNECTION_3G] =
NetworkQuality(base::TimeDelta::FromMilliseconds(272),
base::TimeDelta::FromMilliseconds(209), 749);
default_observations[NetworkChangeNotifier::CONNECTION_4G] =
NetworkQuality(base::TimeDelta::FromMilliseconds(137),
base::TimeDelta::FromMilliseconds(80), 1708);
default_observations[NetworkChangeNotifier::CONNECTION_NONE] =
NetworkQuality(base::TimeDelta::FromMilliseconds(163),
base::TimeDelta::FromMilliseconds(83), 575);
default_observations[NetworkChangeNotifier::CONNECTION_BLUETOOTH] =
NetworkQuality(base::TimeDelta::FromMilliseconds(385),
base::TimeDelta::FromMilliseconds(318), 476);
// Override using the values provided via variation params.
for (size_t i = 0; i <= NetworkChangeNotifier::CONNECTION_LAST; ++i) {
NetworkChangeNotifier::ConnectionType type =
static_cast<NetworkChangeNotifier::ConnectionType>(i);
int32_t variations_value = kMinimumRTTVariationParameterMsec - 1;
std::string parameter_name = std::string(GetNameForConnectionType(type))
.append(".DefaultMedianRTTMsec");
auto it = variation_params.find(parameter_name);
if (it != variation_params.end() &&
base::StringToInt(it->second, &variations_value) &&
variations_value >= kMinimumRTTVariationParameterMsec) {
default_observations[i] =
NetworkQuality(base::TimeDelta::FromMilliseconds(variations_value),
default_observations[i].transport_rtt(),
default_observations[i].downstream_throughput_kbps());
}
variations_value = kMinimumRTTVariationParameterMsec - 1;
parameter_name = std::string(GetNameForConnectionType(type))
.append(".DefaultMedianTransportRTTMsec");
it = variation_params.find(parameter_name);
if (it != variation_params.end() &&
base::StringToInt(it->second, &variations_value) &&
variations_value >= kMinimumRTTVariationParameterMsec) {
default_observations[i] =
NetworkQuality(default_observations[i].http_rtt(),
base::TimeDelta::FromMilliseconds(variations_value),
default_observations[i].downstream_throughput_kbps());
}
variations_value = kMinimumThroughputVariationParameterKbps - 1;
parameter_name = std::string(GetNameForConnectionType(type))
.append(".DefaultMedianKbps");
it = variation_params.find(parameter_name);
if (it != variation_params.end() &&
base::StringToInt(it->second, &variations_value) &&
variations_value >= kMinimumThroughputVariationParameterKbps) {
default_observations[i] = NetworkQuality(
default_observations[i].http_rtt(),
default_observations[i].transport_rtt(), variations_value);
}
}
}
void ObtainTypicalNetworkQuality(NetworkQuality typical_network_quality[]) {
for (size_t i = 0; i < EFFECTIVE_CONNECTION_TYPE_LAST; ++i) {
DCHECK_EQ(InvalidRTT(), typical_network_quality[i].http_rtt());
DCHECK_EQ(InvalidRTT(), typical_network_quality[i].transport_rtt());
DCHECK_EQ(kInvalidThroughput,
typical_network_quality[i].downstream_throughput_kbps());
}
typical_network_quality[EFFECTIVE_CONNECTION_TYPE_SLOW_2G] = NetworkQuality(
// Set to the 83rd percentile of 2G RTT observations on Android. This
// corresponds to the median RTT observation when effective connection
// type is Slow 2G.
base::TimeDelta::FromMilliseconds(3600),
base::TimeDelta::FromMilliseconds(3000), kInvalidThroughput);
typical_network_quality[EFFECTIVE_CONNECTION_TYPE_2G] = NetworkQuality(
// Set to the 58th percentile of 2G RTT observations on Android. This
// corresponds to the median RTT observation when effective connection
// type is 2G.
base::TimeDelta::FromMilliseconds(1800),
base::TimeDelta::FromMilliseconds(1500), kInvalidThroughput);
typical_network_quality[EFFECTIVE_CONNECTION_TYPE_3G] = NetworkQuality(
// Set to the 75th percentile of 3G RTT observations on Android. This
// corresponds to the median RTT observation when effective connection
// type is 3G.
base::TimeDelta::FromMilliseconds(450),
base::TimeDelta::FromMilliseconds(400), kInvalidThroughput);
// Set to the 25th percentile of 3G RTT observations on Android.
typical_network_quality[EFFECTIVE_CONNECTION_TYPE_4G] = NetworkQuality(
base::TimeDelta::FromMilliseconds(175),
base::TimeDelta::FromMilliseconds(125), kInvalidThroughput);
static_assert(
EFFECTIVE_CONNECTION_TYPE_4G + 1 == EFFECTIVE_CONNECTION_TYPE_LAST,
"Missing effective connection type");
}
void ObtainEffectiveConnectionTypeModelParams(
const std::map<std::string, std::string>& variation_params,
NetworkQuality connection_thresholds[]) {
// First set the default thresholds.
NetworkQuality default_effective_connection_type_thresholds
[EffectiveConnectionType::EFFECTIVE_CONNECTION_TYPE_LAST];
default_effective_connection_type_thresholds
[EFFECTIVE_CONNECTION_TYPE_SLOW_2G] = NetworkQuality(
// Set to the 66th percentile of 2G RTT observations on Android.
base::TimeDelta::FromMilliseconds(2010),
base::TimeDelta::FromMilliseconds(1870), kInvalidThroughput);
default_effective_connection_type_thresholds[EFFECTIVE_CONNECTION_TYPE_2G] =
NetworkQuality(
// Set to the 50th percentile of RTT observations on Android.
base::TimeDelta::FromMilliseconds(1420),
base::TimeDelta::FromMilliseconds(1280), kInvalidThroughput);
default_effective_connection_type_thresholds[EFFECTIVE_CONNECTION_TYPE_3G] =
NetworkQuality(
// Set to the 50th percentile of 3G RTT observations on Android.
base::TimeDelta::FromMilliseconds(273),
base::TimeDelta::FromMilliseconds(204), kInvalidThroughput);
// Connection threshold should not be set for 4G effective connection type
// since it is the fastest.
static_assert(
EFFECTIVE_CONNECTION_TYPE_3G + 1 == EFFECTIVE_CONNECTION_TYPE_4G,
"Missing effective connection type");
static_assert(
EFFECTIVE_CONNECTION_TYPE_4G + 1 == EFFECTIVE_CONNECTION_TYPE_LAST,
"Missing effective connection type");
for (size_t i = 0; i <= EFFECTIVE_CONNECTION_TYPE_3G; ++i) {
EffectiveConnectionType effective_connection_type =
static_cast<EffectiveConnectionType>(i);
DCHECK_EQ(InvalidRTT(), connection_thresholds[i].http_rtt());
DCHECK_EQ(InvalidRTT(), connection_thresholds[i].transport_rtt());
DCHECK_EQ(kInvalidThroughput,
connection_thresholds[i].downstream_throughput_kbps());
if (effective_connection_type == EFFECTIVE_CONNECTION_TYPE_UNKNOWN)
continue;
std::string connection_type_name = std::string(
GetNameForEffectiveConnectionType(effective_connection_type));
connection_thresholds[i].set_http_rtt(
base::TimeDelta::FromMilliseconds(GetValueForVariationParam(
variation_params,
connection_type_name + ".ThresholdMedianHttpRTTMsec",
default_effective_connection_type_thresholds[i]
.http_rtt()
.InMilliseconds())));
connection_thresholds[i].set_transport_rtt(
base::TimeDelta::FromMilliseconds(GetValueForVariationParam(
variation_params,
connection_type_name + ".ThresholdMedianTransportRTTMsec",
default_effective_connection_type_thresholds[i]
.transport_rtt()
.InMilliseconds())));
connection_thresholds[i].set_downstream_throughput_kbps(
GetValueForVariationParam(
variation_params, connection_type_name + ".ThresholdMedianKbps",
default_effective_connection_type_thresholds[i]
.downstream_throughput_kbps()));
DCHECK(i == 0 ||
connection_thresholds[i].IsFaster(connection_thresholds[i - 1]));
}
}
double correlation_uma_logging_probability(
const std::map<std::string, std::string>& variation_params) {
double correlation_uma_logging_probability =
GetDoubleValueForVariationParamWithDefaultValue(
variation_params, "correlation_logging_probability", 0.01);
DCHECK_LE(0.0, correlation_uma_logging_probability);
DCHECK_GE(1.0, correlation_uma_logging_probability);
return correlation_uma_logging_probability;
}
bool forced_effective_connection_type_set(
const std::map<std::string, std::string>& variation_params) {
return !GetStringValueForVariationParamWithDefaultValue(
variation_params, "force_effective_connection_type", "")
.empty();
}
EffectiveConnectionType forced_effective_connection_type(
const std::map<std::string, std::string>& variation_params) {
EffectiveConnectionType forced_effective_connection_type =
EFFECTIVE_CONNECTION_TYPE_UNKNOWN;
std::string forced_value = GetStringValueForVariationParamWithDefaultValue(
variation_params, "force_effective_connection_type",
GetNameForEffectiveConnectionType(EFFECTIVE_CONNECTION_TYPE_UNKNOWN));
DCHECK(!forced_value.empty());
bool effective_connection_type_available = GetEffectiveConnectionTypeForName(
forced_value, &forced_effective_connection_type);
DCHECK(effective_connection_type_available);
// Silence unused variable warning in release builds.
(void)effective_connection_type_available;
return forced_effective_connection_type;
}
} // namespace internal
} // namespace nqe
} // namespace net
| 5,722 |
703 | <reponame>wangyuxin11/NewsRecommendSystem
package top.qianxinyao.model;
import top.qianxinyao.model.base.BaseUsers;
/**
* Generated by JFinal.
*/
@SuppressWarnings("serial")
public class Users extends BaseUsers<Users> {
public static final Users dao = new Users().dao();
}
| 96 |
703 | //
// {{args.Prefix}}GlobalEnums.h
// {{args.ProductName}}
//
// Created by Baitianyu on 05/12/2016.
// Copyright © 2016 Netease. All rights reserved.
//
#import <Foundation/Foundation.h>
/**
红点的类型,用于未读消息这类场景。
@constant {{args.Prefix}}BadgeTypeText 带有文字的圆点
@constant {{args.Prefix}}BadgeTypeDot 不含有文字的圆点
*/
typedef NS_ENUM(NSUInteger, {{args.Prefix}}BadgeType) {
/// 带有文字的圆点
{{args.Prefix}}BadgeTypeText,
/// 不含有文字的圆点
{{args.Prefix}}BadgeTypeDot,
};
/**
状态栏样式
@constant {{args.Prefix}}StatusBarStyleInvalid 无效
@constant {{args.Prefix}}StatusBarStyleDefault 默认样式:黑色
@constant {{args.Prefix}}StatusBarStyleLightContent 白色
*/
typedef NS_ENUM(NSInteger, StatusBarStyle) {
/// 无效
{{args.Prefix}}StatusBarStyleInvalid = 0,
/// 黑色
{{args.Prefix}}StatusBarStyleDefault,
/// 白色
{{args.Prefix}}StatusBarStyleLightContent,
};
@interface {{args.Prefix}}GlobalEnums : NSObject
@end
| 498 |
335 | # *****************************************************************************
#
# Copyright (c) 2020, the pyEX authors.
#
# This file is part of the pyEX library, distributed under the terms of
# the Apache License 2.0. The full license can be found in the LICENSE file.
#
# for Coverage
from mock import MagicMock, patch
SYMBOL = "aapl"
class TestAll:
def test_other(self):
from pyEX.streaming.sse import DeepChannelsSSE, _runSSE
with patch("pyEX.streaming.sse._streamSSE"):
# coverage
_runSSE("test")
_runSSE("test", symbols=["test"])
# coverage
DeepChannelsSSE.options()
def test_tops(self):
from pyEX import Client
with patch("requests.get") as mock:
mock.return_value = MagicMock()
mock.return_value.status_code = 200
c = Client(version="sandbox")
| 359 |
5,249 | <reponame>leo0519/TensorRT<gh_stars>1000+
#
# Copyright (c) 2021, NVIDIA 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.
#
import argparse
import onnx
import pycuda.autoinit
import pycuda.driver as cuda
import sys
import tensorrt as trt
from os.path import join
from trt_utils import build_engine, parse_dynamic_size
def parse_args(parser):
"""
Parse commandline arguments.
"""
parser.add_argument('-o', '--output', required=True,
help='output folder to save audio (file per phrase)')
parser.add_argument('--encoder', type=str, default="",
help='full path to the Encoder ONNX')
parser.add_argument('--decoder', type=str, default="",
help='full path to the Decoder or DecoderIter ONNX.')
parser.add_argument('--postnet', type=str, default="",
help='full path to the Postnet ONNX')
parser.add_argument('--waveglow', type=str, default="",
help='full path to the WaveGlow ONNX')
parser.add_argument('--encoder_out', type=str,
help='Filename of the exported encoder engine')
parser.add_argument('--decoder_out', type=str,
help='Filename of the exported decoder engine')
parser.add_argument('--postnet_out', type=str,
help='Filename of the exported postnet engine')
parser.add_argument('--waveglow_out', type=str,
help='Filename of the exported waveglow engine')
parser.add_argument('--fp16', action='store_true',
help='inference with FP16')
parser.add_argument('-bs', '--batch-size', type=str, default="1",
help='One or three comma separated integers specifying the batch size. Specify "min,opt,max" for dynamic shape')
parser.add_argument('--mel-size', type=str, default="32,768,1664",
help='One or three comma separated integers specifying the mels size for waveglow.')
parser.add_argument('--z-size', type=str, default="1024,24576,53248",
help='One or three comma separated integers specifying the z size for waveglow.')
parser.add_argument('--loop', dest='loop', action='store_true',
help='Includes the outer decoder loop in the ONNX model. Enabled by default and only supported on TensorRT 8.0 or later.')
parser.add_argument('--no-loop', dest='loop', action='store_false',
help='Excludes outer decoder loop from decoder ONNX model. Default behavior and necessary for TensorRT 7.2 or earlier.')
parser.set_defaults(loop=int(trt.__version__[0]) >= 8)
return parser
def main():
parser = argparse.ArgumentParser(
description='Export from ONNX to TensorRT for Tacotron 2 and WaveGlow')
parser = parse_args(parser)
args = parser.parse_args()
precision = "fp16" if args.fp16 else "fp32"
encoder_path = join(args.output, args.encoder_out if args.encoder_out else f"encoder_{precision}.engine")
decoder_path = join(args.output, args.decoder_out if args.decoder_out else f"decoder_with_outer_loop_{precision}.engine" if args.loop else f"decoder_iter_{precision}.engine")
postnet_path = join(args.output, args.postnet_out if args.postnet_out else f"postnet_{precision}.engine")
waveglow_path = join(args.output, args.waveglow_out if args.waveglow_out else f"waveglow_{precision}.engine")
bs_min, bs_opt, bs_max = parse_dynamic_size(args.batch_size)
mel_min, mel_opt, mel_max = parse_dynamic_size(args.mel_size)
z_min, z_opt, z_max = parse_dynamic_size(args.z_size)
# Encoder
shapes=[{"name": "sequences", "min": (bs_min,4), "opt": (bs_opt,128), "max": (bs_max,256)},
{"name": "sequence_lengths", "min": (bs_min,), "opt": (bs_opt,), "max": (bs_max,)}]
if args.encoder != "":
print("Building Encoder ...")
encoder_engine = build_engine(args.encoder, shapes=shapes, fp16=args.fp16)
if encoder_engine is not None:
with open(encoder_path, 'wb') as f:
f.write(encoder_engine.serialize())
else:
print("Failed to build engine from", args.encoder)
sys.exit(1)
if args.loop:
# Decoder
shapes=[{"name": "decoder_input_0", "min": (bs_min,80), "opt": (bs_opt,80), "max": (bs_max,80)},
{"name": "attention_hidden_0", "min": (bs_min,1024), "opt": (bs_opt,1024), "max": (bs_max,1024)},
{"name": "attention_cell_0", "min": (bs_min,1024), "opt": (bs_opt,1024), "max": (bs_max,1024)},
{"name": "decoder_hidden_0", "min": (bs_min,1024), "opt": (bs_opt,1024), "max": (bs_max,1024)},
{"name": "decoder_cell_0", "min": (bs_min,1024), "opt": (bs_opt,1024), "max": (bs_max,1024)},
{"name": "attention_weights_0", "min": (bs_min,4), "opt": (bs_opt,128), "max": (bs_max,256)},
{"name": "attention_weights_cum_0", "min": (bs_min,4), "opt": (bs_opt,128), "max": (bs_max,256)},
{"name": "attention_context_0", "min": (bs_min,512), "opt": (bs_opt,512), "max": (bs_max,512)},
{"name": "memory", "min": (bs_min,4,512), "opt": (bs_opt,128,512), "max": (bs_max,256,512)},
{"name": "processed_memory", "min": (bs_min,4,128), "opt": (bs_opt,128,128), "max": (bs_max,256,128)},
{"name": "mask", "min": (bs_min,4), "opt": (bs_opt,128), "max": (bs_max,256)}]
if args.decoder != "":
print("Building Decoder with loop...")
decoder_engine = build_engine(args.decoder, shapes=shapes, fp16=args.fp16)
if decoder_engine is not None:
with open(decoder_path, 'wb') as f:
f.write(decoder_engine.serialize())
else:
print("Failed to build engine from", args.decoder)
sys.exit(1)
else:
# DecoderIter
shapes=[{"name": "decoder_input", "min": (bs_min,80), "opt": (bs_opt,80), "max": (bs_max,80)},
{"name": "attention_hidden", "min": (bs_min,1024), "opt": (bs_opt,1024), "max": (bs_max,1024)},
{"name": "attention_cell", "min": (bs_min,1024), "opt": (bs_opt,1024), "max": (bs_max,1024)},
{"name": "decoder_hidden", "min": (bs_min,1024), "opt": (bs_opt,1024), "max": (bs_max,1024)},
{"name": "decoder_cell", "min": (bs_min,1024), "opt": (bs_opt,1024), "max": (bs_max,1024)},
{"name": "attention_weights", "min": (bs_min,4), "opt": (bs_opt,128), "max": (bs_max,256)},
{"name": "attention_weights_cum", "min": (bs_min,4), "opt": (bs_opt,128), "max": (bs_max,256)},
{"name": "attention_context", "min": (bs_min,512), "opt": (bs_opt,512), "max": (bs_max,512)},
{"name": "memory", "min": (bs_min,4,512), "opt": (bs_opt,128,512), "max": (bs_max,256,512)},
{"name": "processed_memory", "min": (bs_min,4,128), "opt": (bs_opt,128,128), "max": (bs_max,256,128)},
{"name": "mask", "min": (bs_min,4), "opt": (bs_opt,128), "max": (bs_max,256)}]
if args.decoder != "":
print("Building Decoder ...")
decoder_iter_engine = build_engine(args.decoder, shapes=shapes, fp16=args.fp16)
if decoder_iter_engine is not None:
with open(decoder_path, 'wb') as f:
f.write(decoder_iter_engine.serialize())
else:
print("Failed to build engine from", args.decoder)
sys.exit(1)
# Postnet
shapes=[{"name": "mel_outputs", "min": (bs_min,80,32), "opt": (bs_opt,80,768), "max": (bs_max,80,1664)}]
if args.postnet != "":
print("Building Postnet ...")
postnet_engine = build_engine(args.postnet, shapes=shapes, fp16=args.fp16)
if postnet_engine is not None:
with open(postnet_path, 'wb') as f:
f.write(postnet_engine.serialize())
else:
print("Failed to build engine from", args.postnet)
sys.exit(1)
# WaveGlow
shapes=[{"name": "mel", "min": (bs_min,80,mel_min,1), "opt": (bs_opt,80,mel_opt,1), "max": (bs_max,80,mel_max,1)},
{"name": "z", "min": (bs_min,8,z_min,1), "opt": (bs_opt,8,z_opt,1), "max": (bs_max,8,z_max,1)}]
if args.waveglow != "":
print("Building WaveGlow ...")
waveglow_engine = build_engine(args.waveglow, shapes=shapes, fp16=args.fp16)
if waveglow_engine is not None:
with open(waveglow_path, 'wb') as f:
f.write(waveglow_engine.serialize())
else:
print("Failed to build engine from", args.waveglow)
sys.exit(1)
if __name__ == '__main__':
main()
| 4,540 |
860 | <reponame>xiefan46/samza
/*
* 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.samza.operators.spec;
import org.apache.samza.operators.functions.ScheduledFunction;
import org.apache.samza.operators.functions.WatermarkFunction;
/**
* The spec for an operator that outputs a {@link org.apache.samza.operators.MessageStream} to a
* {@link org.apache.samza.system.SystemStream}.
*
* @param <M> the type of input message
*/
public class OutputOperatorSpec<M> extends OperatorSpec<M, M> {
private final OutputStreamImpl<M> outputStream;
/**
* Constructs an {@link OutputOperatorSpec} to send messages to the provided {@code outStream}
*
* @param outputStream the {@link OutputStreamImpl} to send messages to
* @param opId the unique ID of this {@link SinkOperatorSpec} in the graph
*/
OutputOperatorSpec(OutputStreamImpl<M> outputStream, String opId) {
super(OpCode.SEND_TO, opId);
this.outputStream = outputStream;
}
/**
* The {@link OutputStreamImpl} that this operator is sending its output to.
* @return the {@link OutputStreamImpl} for this operator if any, else null.
*/
public OutputStreamImpl<M> getOutputStream() {
return this.outputStream;
}
@Override
public WatermarkFunction getWatermarkFn() {
return null;
}
@Override
public ScheduledFunction getScheduledFn() {
return null;
}
}
| 633 |
3,358 | <gh_stars>1000+
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<<EMAIL>>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include <ql/math/integrals/segmentintegral.hpp>
namespace QuantLib {
SegmentIntegral::SegmentIntegral(Size intervals)
: Integrator(1, 1), intervals_(intervals) {
QL_REQUIRE(intervals > 0, "at least 1 interval needed, 0 given");
}
}
| 323 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.