code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * Copyright 2014 - 2016 Real Logic 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 io.aeron.driver; import io.aeron.driver.media.ReceiveChannelEndpoint; import io.aeron.driver.media.UdpChannel; import org.agrona.concurrent.status.ReadablePosition; import java.util.IdentityHashMap; import java.util.Map; /** * Subscription registration from a client used for liveness tracking */ public class SubscriptionLink implements DriverManagedResource { private final long registrationId; private final long clientLivenessTimeoutNs; private final int streamId; private final boolean isReliable; private final String channelUri; private final ReceiveChannelEndpoint channelEndpoint; private final AeronClient aeronClient; private final Map<PublicationImage, ReadablePosition> positionByImageMap = new IdentityHashMap<>(); private final IpcPublication ipcPublication; private final ReadablePosition ipcPublicationSubscriberPosition; private final UdpChannel spiedChannel; private NetworkPublication spiedPublication = null; private ReadablePosition spiedPosition = null; private boolean reachedEndOfLife = false; public SubscriptionLink( final long registrationId, final ReceiveChannelEndpoint channelEndpoint, final int streamId, final String channelUri, final AeronClient aeronClient, final long clientLivenessTimeoutNs, final boolean isReliable) { this.registrationId = registrationId; this.channelEndpoint = channelEndpoint; this.streamId = streamId; this.channelUri = channelUri; this.aeronClient = aeronClient; this.ipcPublication = null; this.ipcPublicationSubscriberPosition = null; this.spiedChannel = null; this.clientLivenessTimeoutNs = clientLivenessTimeoutNs; this.isReliable = isReliable; } public SubscriptionLink( final long registrationId, final int streamId, final String channelUri, final IpcPublication ipcPublication, final ReadablePosition subscriberPosition, final AeronClient aeronClient, final long clientLivenessTimeoutNs) { this.registrationId = registrationId; this.channelEndpoint = null; // will prevent matches between PublicationImages and IpcPublications this.streamId = streamId; this.channelUri = channelUri; this.aeronClient = aeronClient; this.ipcPublication = ipcPublication; ipcPublication.incRef(); this.ipcPublicationSubscriberPosition = subscriberPosition; this.spiedChannel = null; this.clientLivenessTimeoutNs = clientLivenessTimeoutNs; this.isReliable = true; } public SubscriptionLink( final long registrationId, final UdpChannel spiedChannel, final int streamId, final String channelUri, final AeronClient aeronClient, final long clientLivenessTimeoutNs) { this.registrationId = registrationId; this.channelEndpoint = null; this.streamId = streamId; this.channelUri = channelUri; this.aeronClient = aeronClient; this.ipcPublication = null; this.ipcPublicationSubscriberPosition = null; this.spiedChannel = spiedChannel; this.clientLivenessTimeoutNs = clientLivenessTimeoutNs; this.isReliable = true; } public long registrationId() { return registrationId; } public ReceiveChannelEndpoint channelEndpoint() { return channelEndpoint; } public int streamId() { return streamId; } public String channelUri() { return channelUri; } public boolean isReliable() { return isReliable; } public boolean matches(final ReceiveChannelEndpoint channelEndpoint, final int streamId) { return channelEndpoint == this.channelEndpoint && streamId == this.streamId; } public boolean matches(final NetworkPublication publication) { boolean result = false; if (null != spiedChannel) { result = streamId == publication.streamId() && publication.sendChannelEndpoint().udpChannel().canonicalForm().equals(spiedChannel.canonicalForm()); } return result; } public void addImage(final PublicationImage image, final ReadablePosition position) { positionByImageMap.put(image, position); } public void removeImage(final PublicationImage image) { positionByImageMap.remove(image); } public void addSpiedPublication(final NetworkPublication publication, final ReadablePosition position) { spiedPublication = publication; spiedPosition = position; } public void removeSpiedPublication() { spiedPublication = null; spiedPosition = null; } public void close() { positionByImageMap.forEach(PublicationImage::removeSubscriber); if (null != ipcPublication) { ipcPublication.removeSubscription(ipcPublicationSubscriberPosition); ipcPublication.decRef(); } else if (null != spiedPublication) { spiedPublication.removeSpyPosition(spiedPosition); } } public void onTimeEvent(final long time, final DriverConductor conductor) { if (time > (aeronClient.timeOfLastKeepalive() + clientLivenessTimeoutNs)) { reachedEndOfLife = true; conductor.cleanupSubscriptionLink(SubscriptionLink.this); } } public boolean hasReachedEndOfLife() { return reachedEndOfLife; } public void timeOfLastStateChange(final long time) { // not set this way } public long timeOfLastStateChange() { return aeronClient.timeOfLastKeepalive(); } public void delete() { close(); } }
tbrooks8/Aeron
aeron-driver/src/main/java/io/aeron/driver/SubscriptionLink.java
Java
apache-2.0
6,539
/* */ package com.webbuilder.interact; /* */ /* */ import com.webbuilder.controls.Query; /* */ import com.webbuilder.utils.CompressUtil; /* */ import com.webbuilder.utils.DateUtil; /* */ import com.webbuilder.utils.DbUtil; /* */ import com.webbuilder.utils.FileUtil; /* */ import com.webbuilder.utils.StringUtil; /* */ import com.webbuilder.utils.SysUtil; /* */ import com.webbuilder.utils.WebUtil; /* */ import com.webbuilder.utils.XMLParser; /* */ import java.awt.Color; /* */ import java.awt.Graphics; /* */ import java.awt.image.BufferedImage; /* */ import java.io.File; /* */ import java.io.FileInputStream; /* */ import java.io.InputStream; /* */ import java.io.PrintWriter; /* */ import java.sql.Connection; /* */ import java.sql.PreparedStatement; /* */ import java.sql.Timestamp; /* */ import java.util.Calendar; /* */ import java.util.Date; /* */ import java.util.HashMap; /* */ import java.util.HashSet; /* */ import java.util.Iterator; /* */ import javax.imageio.ImageIO; /* */ import javax.servlet.http.HttpServletRequest; /* */ import javax.servlet.http.HttpServletResponse; /* */ import javax.servlet.http.HttpSession; /* */ import javax.swing.Icon; /* */ import javax.swing.filechooser.FileSystemView; /* */ import org.dom4j.Attribute; /* */ import org.dom4j.Document; /* */ import org.dom4j.Element; /* */ import org.json.JSONArray; /* */ import org.json.JSONObject; /* */ /* */ public class Explorer /* */ { /* */ public void getRcvFilter(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 42 */ String find = StringUtil.fetchString(request, "findCombo"); /* */ /* 44 */ if (!StringUtil.isEmpty(find)) { /* 45 */ request.setAttribute("findValue", "%" + find + "%"); /* 46 */ String sql = " and WB_NAME like {?findValue?}"; /* 47 */ request.setAttribute("whereSql", sql); /* */ } else { /* 49 */ DbUtil.getDefaultWhere(request, response, "WB_DATE,WB_CODE=b", /* 50 */ false); /* */ } /* */ } /* */ /* */ public void sendFile(HttpServletRequest request, HttpServletResponse response) throws Exception { /* 55 */ Connection conn = DbUtil.fetchConnection(request, request.getAttribute( /* 56 */ "sys.jndi").toString()); /* 57 */ String depts = request.getAttribute("WB_RDEPT").toString(); /* 58 */ String roles = request.getAttribute("WB_RROLE").toString(); /* 59 */ String users = request.getAttribute("WB_RUSER").toString(); /* 60 */ String scope = request.getAttribute("sys.scope").toString(); /* 61 */ String dbType = request.getAttribute("sys.dbType").toString(); /* 62 */ HashSet userList = new HashSet(); /* */ /* 64 */ userList = DbUtil.getUserList(conn, dbType, scope, depts, roles, users); /* 65 */ conn.setAutoCommit(false); /* */ try { /* 67 */ PreparedStatement stm = null; /* 68 */ int k = 0; int l = userList.size(); /* 69 */ boolean commitAll = false; boolean added = false; /* 70 */ stm = conn /* 71 */ .prepareStatement("insert into WB_FILERECEIVE values(?,?,?,?,null)"); /* */ try { /* 73 */ stm.setString(1, scope); /* 74 */ stm.setTimestamp(2, /* 75 */ new Timestamp(DateUtil.stringToStdDate( /* 75 */ request.getAttribute("sys.now").toString()).getTime())); /* 76 */ stm.setString(3, request.getAttribute("sys.code").toString()); /* 77 */ while ( userList.iterator().hasNext()) { String s=userList.iterator().next().toString(); /* 78 */ k++; /* 79 */ stm.setString(4, s); /* 80 */ stm.addBatch(); /* 81 */ if (!added) /* 82 */ added = true; /* 83 */ if (k % 1000 == 0) { /* 84 */ if (k == l) /* 85 */ commitAll = true; /* 86 */ stm.executeBatch(); /* */ } /* */ } /* 89 */ if ((added) && (!commitAll)) /* 90 */ stm.executeBatch(); /* */ } finally { /* 92 */ DbUtil.closeStatement(stm); /* */ } /* 94 */ conn.commit(); /* */ } catch (Exception e) { /* 96 */ conn.rollback(); /* 97 */ throw new Exception(e); /* */ } finally { /* 99 */ conn.setAutoCommit(true); /* */ } /* */ } /* */ /* */ private String createUserDir(String root) throws Exception { /* 104 */ Date dt = new Date(); /* 105 */ String y = "y" + Integer.toString(DateUtil.yearOf(dt)); /* 106 */ String d = "d" + Integer.toString(DateUtil.dayOfYear(dt)); /* 107 */ String h = "h" + Integer.toString(DateUtil.hourOfDay(dt)); /* 108 */ Calendar cal = Calendar.getInstance(); /* 109 */ cal.setTime(dt); /* 110 */ int m = cal.get(12); /* 111 */ h = h + "m" + Integer.toString(m / 10); /* 112 */ String rel = y + "/" + d + "/" + h + "/"; /* 113 */ File file = FileUtil.getUniqueFile(new File(root + "/" + rel + "s" + /* 114 */ DateUtil.formatDate(dt, "ssSSS"))); /* 115 */ rel = rel + file.getName(); /* 116 */ File dir = new File(root + "/" + rel); /* 117 */ if (!dir.mkdirs()) /* 118 */ throw new Exception("不能创建目录。"); /* 119 */ return rel; /* */ } /* */ /* */ public void createPubDir(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 124 */ String root = request.getAttribute("sys.path").toString() + /* 125 */ "WEB-INF/myfile"; /* 126 */ String scope = request.getAttribute("sys.scope").toString(); /* */ /* 128 */ String sysPubDir = FileUtil.fetchPubDir(root, scope); /* 129 */ request.setAttribute("sysPubDir", sysPubDir); /* */ } /* */ /* */ public void createUserDir(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 134 */ String userPath = request.getAttribute("sys.rootpath").toString(); /* */ /* 136 */ if (StringUtil.isEmpty(userPath)) { /* 137 */ String root = request.getAttribute("sys.path").toString() + /* 138 */ "WEB-INF/myfile"; /* 139 */ String path = createUserDir(root); /* 140 */ Query query = new Query(); /* 141 */ query.setRequest(request); /* 142 */ query.type = "update"; /* 143 */ request.setAttribute("rootPath", path); /* 144 */ query.sql = "update WB_USER set ROOT_PATH={?rootPath?} where USERNAME={?sys.user?}"; /* 145 */ query.jndi = StringUtil.fetchString(request, "sys.jndi"); /* 146 */ query.setName("query.updateUser"); /* 147 */ query.create(); /* 148 */ request.getSession(false).setAttribute("sys.rootpath", /* 149 */ root + "/" + path); /* 150 */ request.setAttribute("sys.rootpath", root + "/" + path); /* */ } else { /* 152 */ File dir = new File(userPath); /* 153 */ if ((!dir.exists()) && (!dir.mkdirs())) /* 154 */ throw new Exception("不能创建用户目录。"); /* */ } /* */ } /* */ /* */ public void setOrder(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 160 */ JSONArray files = new JSONArray(request.getParameter("orderTree")); /* 161 */ int j = files.length(); /* 162 */ if (j == 0) /* 163 */ return; /* 164 */ File dir = new File(request.getParameter("orderDir")); /* */ /* 168 */ HashMap hashMap = new HashMap(); /* */ /* 170 */ XMLParser mapXml = new XMLParser(FileUtil.getUserIndex(dir, request.getAttribute( /* 171 */ "sys.scope").toString(), false)); /* 172 */ Element root = mapXml.document.getRootElement(); /* 173 */ Iterator iterator = root.elementIterator(); /* 174 */ while (iterator.hasNext()) { /* 175 */ Element el = (Element)iterator.next(); /* 176 */ hashMap.put(el.attribute("name").getText(), el); /* */ } /* 178 */ for (int i = 0; i < j; i++) { /* 179 */ String name = new JSONObject(files.getString(i)).getString("filename"); /* 180 */ Element el = (Element)hashMap.get(name); /* 181 */ if (el != null) { /* 182 */ root.add(el.createCopy()); /* 183 */ root.remove(el); /* */ } /* */ } /* 186 */ mapXml.save(); /* */ } /* */ /* */ public void getOrder(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 195 */ StringBuilder buf = new StringBuilder(); /* 196 */ boolean added = false; /* */ /* 198 */ buf.append("["); /* 199 */ File file = new File(request.getParameter("dir")); /* 200 */ File mapFile = FileUtil.getUserIndex(file, request.getAttribute("sys.scope") /* 201 */ .toString(), false); /* 202 */ if (mapFile.exists()) { /* 203 */ XMLParser mapXml = new XMLParser(mapFile); /* 204 */ Element el = mapXml.document.getRootElement(); /* 205 */ if (el != null) { /* 206 */ Iterator iterator = el.elementIterator(); /* 207 */ while (iterator.hasNext()) { /* 208 */ el = (Element)iterator.next(); /* 209 */ if (added) /* 210 */ buf.append(","); /* */ else /* 212 */ added = true; /* 213 */ buf.append("{text:\""); /* 214 */ String text = StringUtil.replaceParameters(request, el.attribute( /* 215 */ "caption").getValue()); /* 216 */ String name = el.attribute("name").getValue(); /* 217 */ if (StringUtil.isEmpty(text)) /* 218 */ text = name; /* 219 */ buf.append(StringUtil.toExpress(text)); /* 220 */ text = el.attribute("icon").getValue(); /* 221 */ if (!StringUtil.isEmpty(text)) { /* 222 */ buf.append("\",iconCls:\""); /* 223 */ buf.append(text); /* */ } /* 225 */ buf.append("\",filename:\""); /* 226 */ buf.append(name); /* 227 */ buf.append("\",leaf:true}"); /* */ } /* */ } /* */ } /* 231 */ buf.append("]"); /* 232 */ response.getWriter().print(buf); /* */ } /* */ /* */ public void getProperty(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 243 */ File file = new File(request.getParameter("fileName")); /* 244 */ File mapFile = FileUtil.getUserIndex(file.getParentFile(), request /* 245 */ .getAttribute("sys.scope").toString(), false); /* 246 */ if (mapFile.exists()) { /* 247 */ String fileName = file.getName(); /* 248 */ XMLParser mapXml = new XMLParser(mapFile); /* 249 */ Element el = mapXml.document.getRootElement(); /* 250 */ if (el != null) { /* 251 */ Iterator iterator = el.elementIterator(); /* 252 */ while (iterator.hasNext()) { /* 253 */ el = (Element)iterator.next(); /* 254 */ if (!StringUtil.isSame(el.attribute("name").getText(), /* 255 */ fileName)) continue; /* 256 */ StringBuilder buf = new StringBuilder(); /* 257 */ buf.append("{fileCaption:\""); /* 258 */ Attribute attr = el.attribute("caption"); /* 259 */ if (attr != null) /* 260 */ buf.append(StringUtil.toExpress(attr.getText())); /* 261 */ buf.append("\",fileRole:\""); /* 262 */ attr = el.attribute("role"); /* 263 */ if (attr != null) /* 264 */ buf.append(StringUtil.toExpress(attr.getText())); /* 265 */ buf.append("\",fileIcon:\""); /* 266 */ attr = el.attribute("icon"); /* 267 */ if (attr != null) /* 268 */ buf.append(attr.getText()); /* 269 */ buf.append("\",fileHint:\""); /* 270 */ attr = el.attribute("hint"); /* 271 */ if (attr != null) /* 272 */ buf.append(attr.getText()); /* 273 */ buf.append("\",fileHidden:\""); /* 274 */ attr = el.attribute("hidden"); /* 275 */ if (attr != null) /* 276 */ buf.append(StringUtil.toExpress(attr.getText())); /* */ else /* 278 */ buf.append("0"); /* 279 */ buf.append("\"}"); /* 280 */ response.getWriter().print(buf); /* 281 */ return; /* */ } /* */ } /* */ } /* */ } /* */ /* */ public void setPropertyCopy(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 290 */ innerSetProperty(request, response, true); /* */ } /* */ /* */ public void setProperty(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 295 */ innerSetProperty(request, response, false); /* */ } /* */ /* */ private void innerSetProperty(HttpServletRequest request, HttpServletResponse response, boolean createCopy) /* */ throws Exception /* */ { /* 304 */ String caption = request.getParameter("fileCaption"); /* 305 */ String role = request.getParameter("fileRole"); /* 306 */ String icon = request.getParameter("fileIcon"); /* 307 */ String hint = request.getParameter("fileHint"); /* 308 */ String hidden = request.getParameter("fileHidden"); /* 309 */ JSONArray files = new JSONArray(request.getParameter("setFile")); /* 310 */ HashMap map = new HashMap(); /* */ /* 313 */ File file = new File(files.getString(0)); /* 314 */ File dir = file.getParentFile(); /* 315 */ XMLParser mapXml = new XMLParser(FileUtil.getUserIndex(dir, request.getAttribute( /* 316 */ "sys.scope").toString(), createCopy)); /* 317 */ Element root = mapXml.document.getRootElement(); /* 318 */ if (root != null) { /* 319 */ Iterator iterator = root.elementIterator(); /* 320 */ while (iterator.hasNext()) { /* 321 */ Element el = (Element)iterator.next(); /* 322 */ String name = el.attribute("name").getText(); /* 323 */ file = new File(dir, name); /* 324 */ if ((!file.exists()) || (map.containsKey(name))) /* 325 */ root.remove(el); /* */ else /* 327 */ map.put(name, el); /* */ } /* */ } else { /* 330 */ root = mapXml.document.addElement("map"); /* 331 */ }int j = files.length(); /* 332 */ for (int i = 0; i < j; i++) { /* 333 */ String name = FileUtil.extractFileName(files.getString(i)); /* 334 */ Element el = (Element)map.get(name); /* 335 */ if (el == null) { /* 336 */ el = root.addElement("file"); /* 337 */ el.addAttribute("name", name); /* 338 */ el.addAttribute("caption", caption); /* 339 */ el.addAttribute("role", role); /* 340 */ el.addAttribute("icon", icon); /* 341 */ el.addAttribute("hint", hint); /* 342 */ el.addAttribute("hidden", hidden); /* */ } else { /* 344 */ el.attribute("name").setText(name); /* 345 */ el.attribute("caption").setText(caption); /* 346 */ el.attribute("role").setText(role); /* 347 */ el.attribute("icon").setText(icon); /* 348 */ el.attribute("hint").setText(hint); /* 349 */ el.attribute("hidden").setText(hidden); /* */ } /* */ } /* 352 */ mapXml.save(); /* */ } /* */ /* */ public void importFile(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 357 */ String importDir = request.getAttribute("importDir").toString(); /* 358 */ FileUtil.checkRight(request, new File(importDir)); /* 359 */ InputStream stream = (InputStream)request.getAttribute("importFile"); /* 360 */ String fn = request.getAttribute("importFile__file").toString(); /* */ /* 362 */ if (StringUtil.isEqual(request.getAttribute("importType").toString(), /* 363 */ "1")) { /* 364 */ if (StringUtil.isSame(FileUtil.extractFileExt(fn), "zip")) /* 365 */ CompressUtil.unzip(stream, new File(importDir), /* 366 */ (String)request.getAttribute("sys.fileCharset")); /* */ else /* 368 */ throw new Exception("请选择一个zip格式的压缩文件。"); /* */ } /* 370 */ else FileUtil.saveInputStreamToFile(stream, new File(importDir, fn)); /* */ } /* */ /* */ public void exportFile(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 375 */ String[] list = StringUtil.split(request.getParameter("exportFiles"), /* 376 */ "|"); /* 378 */ int i = 0; int j = list.length; /* */ /* 380 */ File[] files = new File[j]; /* */ /* 382 */ for (i = 0; i < j; i++) { /* 383 */ WebUtil.recordLog(request, "explorer导出:" + list[i], 1); /* 384 */ files[i] = new File(list[i]); /* 385 */ FileUtil.checkRight(request, files[i]); /* */ } /* */ String fileName; /* 387 */ if (j == 1) { /* 388 */ fileName = FileUtil.extractFileNameNoExt(files[0].getName()); /* */ } else { /* 390 */ File parentFile = files[0].getParentFile(); /* 391 */ fileName = ""; /* 392 */ if (parentFile != null) /* 393 */ fileName = FileUtil.extractFileNameNoExt(parentFile.getName()); /* 394 */ if (StringUtil.isEmpty(fileName)) /* 395 */ fileName = "data"; /* */ } /* 397 */ boolean useZip = (StringUtil.isEqual(request.getParameter("exportType"), "1")) || /* 398 */ (j > 1) || (files[0].isDirectory()); /* 399 */ response.reset(); /* 400 */ if (!useZip) { /* 401 */ response.setHeader("content-length", Long.toString(files[0] /* 402 */ .length())); /* 403 */ fileName = files[0].getName(); /* */ } else { /* 405 */ fileName = fileName + ".zip"; /* 406 */ }response.setHeader("content-type", "application/force-download"); /* 407 */ String charset = (String)request.getAttribute("sys.fileCharset"); /* 408 */ response.setHeader("content-disposition", "attachment;filename=" + /* 409 */ WebUtil.getFileName(fileName, charset)); /* 410 */ if (useZip) { /* 411 */ CompressUtil.zip(files, response.getOutputStream(), /* 412 */ (String)request.getAttribute("sys.fileCharset")); /* */ } else { /* 414 */ FileInputStream inputStream = new FileInputStream(files[0]); /* 415 */ SysUtil.inputStreamToOutputStream(inputStream, response /* 416 */ .getOutputStream()); /* 417 */ inputStream.close(); /* */ } /* */ } /* */ /* */ public void exportFile2(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* */ String root = request.getAttribute("sys.path").toString() + "WEB-INF/myfile.doc"; /* 378 */ int i = 0; int j = 1; /* */ /* 380 */ File[] files = new File[j]; /* */ /* 382 */ /* 383 */ WebUtil.recordLog(request, "explorer导出:" + root, 1); /* 384 */ files[i] = new File(root); /* 385 */ FileUtil.checkRight(request, files[i]); /* */ /* */ String fileName; /* 387 */ if (j == 1) { /* 388 */ fileName = FileUtil.extractFileNameNoExt(files[0].getName()); /* */ } else { /* 390 */ File parentFile = files[0].getParentFile(); /* 391 */ fileName = ""; /* 392 */ if (parentFile != null) /* 393 */ fileName = FileUtil.extractFileNameNoExt(parentFile.getName()); /* 394 */ if (StringUtil.isEmpty(fileName)) /* 395 */ fileName = "data"; /* */ } /* 397 */ boolean useZip = (StringUtil.isEqual(request.getParameter("exportType"), "1")) || /* 398 */ (j > 1) || (files[0].isDirectory()); /* 399 */ response.reset(); /* 400 */ if (!useZip) { /* 401 */ response.setHeader("content-length", Long.toString(files[0] /* 402 */ .length())); /* 403 */ fileName = files[0].getName(); /* */ } else { /* 405 */ fileName = fileName + ".zip"; /* 406 */ }response.setHeader("content-type", "application/force-download"); /* 407 */ String charset = (String)request.getAttribute("sys.fileCharset"); /* 408 */ response.setHeader("content-disposition", "attachment;filename=" + /* 409 */ WebUtil.getFileName(fileName, charset)); /* 410 */ if (useZip) { /* 411 */ CompressUtil.zip(files, response.getOutputStream(), /* 412 */ (String)request.getAttribute("sys.fileCharset")); /* */ } else { /* 414 */ FileInputStream inputStream = new FileInputStream(files[0]); /* 415 */ SysUtil.inputStreamToOutputStream(inputStream, response /* 416 */ .getOutputStream()); /* 417 */ inputStream.close(); /* */ } /* */ } /* */ /* */ public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 423 */ String fileName = request.getParameter("file"); /* */ try { /* 425 */ Runtime.getRuntime().exec(fileName); /* */ } catch (Exception e) { /* 427 */ throw new Exception("执行 \"" + FileUtil.extractFileName(fileName) + /* 428 */ "\"错误。"); /* */ } /* */ } /* */ /* */ public void openFile(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 434 */ FileUtil.checkRight(request, new File(request.getParameter("file"))); /* 435 */ String charset = request.getParameter("charset"); /* */ /* 437 */ if (StringUtil.isEmpty(charset)) /* 438 */ charset = (String)request.getAttribute("sys.charset"); /* 439 */ response.getWriter().print( /* 440 */ FileUtil.readText(request.getParameter("file"), charset)); /* */ } /* */ /* */ public void saveFile(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 445 */ FileUtil.checkRight(request, new File(request.getParameter("file"))); /* 446 */ String charset = request.getParameter("charset"); /* 447 */ if (StringUtil.isEmpty(charset)) /* 448 */ charset = (String)request.getAttribute("sys.charset"); /* 449 */ FileUtil.writeText(request.getParameter("file"), request /* 450 */ .getParameter("text"), charset); /* */ } /* */ /* */ public void deleteFiles(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 457 */ JSONArray files = new JSONArray(request.getParameter("files")); /* 458 */ int j = files.length(); /* */ /* 460 */ for (int i = 0; i < j; i++) { /* 461 */ String fileName = files.getString(i); /* 462 */ File file = new File(fileName); /* 463 */ FileUtil.checkRight(request, file); /* 464 */ WebUtil.recordLog(request, "explorer删除:" + fileName, 1); /* 465 */ if (file.isDirectory()) /* 466 */ FileUtil.deleteFolder(file); /* 467 */ else if (!file.delete()) /* 468 */ throw new Exception("不能删除文件 \"" + file.getName() + "\"。"); /* */ } /* */ } /* */ /* */ public void pasteFiles(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 474 */ String filesParam = request.getParameter("files"); /* 475 */ String dir = request.getParameter("dir") + "/"; /* 476 */ File destFile = new File(dir); /* 477 */ JSONArray files = new JSONArray(filesParam); /* 478 */ boolean isCut = StringUtil.getStringBool(request.getParameter("isCut")); /* 479 */ int j = files.length(); /* */ /* 481 */ for (int i = 0; i < j; i++) { /* 482 */ File file = new File(files.getString(i)); /* 483 */ File dest = new File(dir + file.getName()); /* 484 */ FileUtil.checkRight(request, file); /* 485 */ FileUtil.checkRight(request, dest); /* 486 */ WebUtil.recordLog(request, "explorer贴粘:" + (isCut ? "剪切" : "复制") + /* 487 */ "," + files.getString(i) + "至" + dir, 1); /* 488 */ if (file.isDirectory()) { /* 489 */ if (FileUtil.isSubFolder(file, destFile)) /* 490 */ throw new Exception("不能复制相同的文件夹。"); /* 491 */ FileUtil.copyFolder(file, dest, true, isCut); /* */ } else { /* 493 */ FileUtil.copyFile(file, dest, true, isCut); /* */ } /* */ } /* */ } /* */ /* */ public void rename(HttpServletRequest request, HttpServletResponse response) throws Exception { /* 499 */ String fileName = request.getParameter("fileName"); /* 500 */ String rename = request.getParameter("fileValue"); /* 501 */ File file = new File(fileName); /* 502 */ FileUtil.checkRight(request, file); /* 503 */ if ((rename.indexOf("/") > -1) || /* 504 */ (rename.indexOf("\\") > -1) || /* 505 */ (!file.renameTo( /* 506 */ new File(FileUtil.extractFilePath(fileName) + /* 506 */ rename)))) /* 507 */ throw new Exception("重命名失败。"); /* */ } /* */ /* */ public void newFile(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 512 */ String name = request.getParameter("fileValue"); /* 513 */ String fileName = request.getParameter("dir") + "/" + name; /* 514 */ String type = request.getParameter("type"); /* */ /* 517 */ File file = new File(fileName); /* 518 */ FileUtil.checkRight(request, file); /* */ boolean flag; /* */ /* 519 */ if (type.equals("dir")) /* 520 */ flag = file.mkdir(); /* */ else /* 522 */ flag = file.createNewFile(); /* 523 */ if (!flag) /* 524 */ throw new Exception("不能创建\"" + name + "\""); /* */ } /* */ /* */ public void getPubDir(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 529 */ String dir = request.getParameter("dir"); /* 530 */ StringBuilder buf = new StringBuilder(); /* 531 */ String root = request.getAttribute("sys.path").toString() + /* 532 */ "WEB-INF/myfile"; /* 533 */ String scope = request.getAttribute("sys.scope").toString(); /* */ /* 535 */ if (StringUtil.isEmpty(dir)) { /* 536 */ loadPubDir(FileUtil.fetchPubDir(root, scope), buf); /* */ } else { /* 538 */ File fl = new File(dir); /* 539 */ FileUtil.checkRight(request, fl); /* 540 */ File[] files = fl.listFiles(); /* 541 */ FileUtil.sortFiles(files); /* 542 */ loadFilesBuf(files, buf); /* */ } /* 544 */ response.getWriter().print(buf); /* */ } /* */ /* */ public void getUserDir(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 549 */ String dir = request.getParameter("dir"); /* 550 */ StringBuilder buf = new StringBuilder(); /* */ /* 552 */ if (StringUtil.isEmpty(dir)) { /* 553 */ loadUserDir((String)request.getAttribute("sys.rootpath"), buf); /* */ } else { /* 555 */ File fl = new File(dir); /* 556 */ FileUtil.checkRight(request, fl); /* 557 */ File[] files = fl.listFiles(); /* 558 */ FileUtil.sortFiles(files); /* 559 */ loadFilesBuf(files, buf); /* */ } /* 561 */ response.getWriter().print(buf); /* */ } /* */ /* */ public void getDir(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 566 */ String dir = request.getParameter("dir"); /* 567 */ boolean appRoot = StringUtil.getStringBool(request /* 568 */ .getParameter("setAppRoot")); /* 569 */ StringBuilder buf = new StringBuilder(); /* */ /* 571 */ if (StringUtil.isEmpty(dir)) { /* 572 */ if ((appRoot) || (!loadFilesBuf(File.listRoots(), buf))) { /* 573 */ buf = new StringBuilder(); /* 574 */ loadAppDir((String)request.getAttribute("sys.path"), buf); /* */ } /* */ } else { /* 577 */ File[] files = new File(dir).listFiles(); /* 578 */ FileUtil.sortFiles(files); /* 579 */ loadFilesBuf(files, buf); /* */ } /* 581 */ response.getWriter().print(buf); /* */ } /* */ /* */ public void getFile(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 586 */ String dir = request.getParameter("dir"); /* 587 */ File dirFile = new File(dir); /* 588 */ FileUtil.checkRight(request, dirFile); /* 589 */ File[] files = dirFile.listFiles(); /* 590 */ if (files == null) { /* 591 */ response.getWriter().print("{total:0,row:[]}"); /* 592 */ return; /* */ } /* 594 */ FileUtil.sortFiles(files); /* 595 */ StringBuilder buf = new StringBuilder(); /* 596 */ FileSystemView fileView = FileSystemView.getFileSystemView(); /* 597 */ boolean isFirst = true; /* 598 */ String start = request.getParameter("start"); /* 599 */ String limit = request.getParameter("limit"); /* 600 */ int count = 0; /* */ int startValue; /* */ /* 602 */ if (start == null) /* 603 */ startValue = 1; /* */ else /* 605 */ startValue = Integer.parseInt(start) + 1; /* */ int limitValue; /* */ /* 606 */ if (limit == null) /* 607 */ limitValue = 2147483647 - startValue; /* */ else /* 609 */ limitValue = Integer.parseInt(limit); /* 610 */ int end = startValue + limitValue - 1; /* 611 */ buf.append("{total:"); /* 612 */ buf.append(files.length); /* 613 */ buf.append(",row:["); /* 614 */ for (File file : files) { /* 615 */ count++; /* 616 */ if (count < startValue) /* */ continue; /* 618 */ if (count > end) /* */ break; /* 620 */ if (isFirst) /* 621 */ isFirst = false; /* */ else /* 623 */ buf.append(","); /* 624 */ boolean isDir = file.isDirectory(); /* 625 */ buf.append("{filename:\""); /* 626 */ if (isDir) /* 627 */ buf.append("0"); /* */ else /* 629 */ buf.append("1"); /* 630 */ String fileName = file.getName(); /* 631 */ buf.append(fileName); /* 632 */ buf.append("\",size:"); /* 633 */ if (isDir) /* 634 */ buf.append(-1); /* */ else /* 636 */ buf.append(file.length()); /* 637 */ buf.append(",file:\""); /* 638 */ buf.append(StringUtil.replace(file.getAbsolutePath(), "\\", "/")); /* 639 */ buf.append("\",type:\""); /* 640 */ if (isDir) { /* 641 */ buf.append("0文件夹"); } else { /* */ String type; /* */ try { type = fileView.getSystemTypeDescription(file); /* */ } /* */ catch (Exception e) /* */ { /* */ /* 646 */ type = null; /* */ } /* 648 */ if (type != null) { /* 649 */ buf.append("1" + StringUtil.toExpress(type)); /* */ } else { /* 651 */ String ext = FileUtil.extractFileExt(fileName); /* 652 */ if (StringUtil.isEmpty(ext)) { /* 653 */ buf.append("1文件"); /* */ } else { /* 655 */ buf.append("1" + ext); /* 656 */ buf.append(" 文件"); /* */ } /* */ } /* */ } /* 660 */ buf.append("\",modifyTime:\""); /* 661 */ buf.append(DateUtil.dateToString(new Date(file.lastModified()))); /* 662 */ buf.append("\"}"); /* */ } /* 664 */ buf.append("]}"); /* 665 */ response.getWriter().print(buf); /* */ } /* */ /* */ public void getIcon(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 671 */ File file = new File(new String(request.getParameter("file") /* 671 */ .getBytes("ISO-8859-1"), "utf-8")); FileSystemView fileView = FileSystemView.getFileSystemView(); Icon icon = fileView.getSystemIcon(file); response.reset(); if (icon == null) { response.setContentType("image/gif"); InputStream is = new FileInputStream(request.getAttribute("sys.path") + "webbuilder/images/file.gif"); SysUtil.inputStreamToOutputStream(is, response.getOutputStream()); is.close(); } else { response.setContentType("image/jpeg"); int width = icon.getIconWidth(); int height = icon.getIconHeight(); BufferedImage image = new BufferedImage(width, height, 1); Graphics graphics = image.getGraphics(); graphics.setColor(Color.white); graphics.fillRect(0, 0, width, height); icon.paintIcon(null, graphics, 0, 0); ImageIO.write(image, "jpeg", response.getOutputStream()); graphics.dispose(); /* */ } /* */ } /* */ /* */ private void loadPubDir(String pubDir, StringBuilder buf) /* */ { /* 697 */ buf.append("["); /* 698 */ buf.append("{text:\"公共文件\",dir:\""); /* 699 */ buf.append(StringUtil.toExpress(pubDir)); /* 700 */ buf.append("\"}"); /* 701 */ buf.append("]"); /* */ } /* */ /* */ private void loadUserDir(String userDir, StringBuilder buf) { /* 705 */ buf.append("["); /* 706 */ buf.append("{text:\"我的文件\",dir:\""); /* 707 */ buf.append(StringUtil.toExpress(userDir)); /* 708 */ buf.append("\"}"); /* 709 */ buf.append("]"); /* */ } /* */ /* */ private void loadAppDir(String appDir, StringBuilder buf) { /* 713 */ String s = FileUtil.extractFileDir(appDir); /* 714 */ buf.append("["); /* 715 */ buf.append("{text:\""); /* 716 */ buf.append(StringUtil.toExpress(s)); /* 717 */ buf.append("\",dir:\""); /* 718 */ buf.append(StringUtil.toExpress(s)); /* 719 */ buf.append("\"}"); /* 720 */ buf.append("]"); /* */ } /* */ /* */ private boolean loadFilesBuf(File[] files, StringBuilder buf) { /* 724 */ boolean isOk = false; boolean isFirst = true; /* */ /* 727 */ buf.append("["); /* 728 */ for (File file : files) { /* 729 */ if (file.isDirectory()) { /* 730 */ isOk = true; /* 731 */ if (isFirst) /* 732 */ isFirst = false; /* */ else /* 734 */ buf.append(","); /* 735 */ buf.append("{text:\""); /* 736 */ String name = file.getName(); /* 737 */ String dir = StringUtil.replace(file.getAbsolutePath(), "\\", "/"); /* 738 */ if (StringUtil.isEmpty(name)) /* 739 */ name = FileUtil.extractFileDir(dir); /* 740 */ buf.append(StringUtil.toExpress(name)); /* 741 */ buf.append("\",dir:\""); /* 742 */ buf.append(StringUtil.replace(dir, "\\", "/")); /* 743 */ if (FileUtil.hasSubFile(file, true)) /* 744 */ buf.append("\"}"); /* */ else /* 746 */ buf.append("\",leaf:true,iconCls:\"icon_folder\"}"); /* */ } /* */ } /* 749 */ buf.append("]"); /* 750 */ return isOk; /* */ } /* */ } /* Location: Z:\EXT\WebBuilderServer (1)\WEB-INF\lib\webbuilder2.jar * Qualified Name: com.webbuilder.interact.Explorer * JD-Core Version: 0.6.0 */
fuhongliang/partmanager
src/com/webbuilder/interact/Explorer.java
Java
apache-2.0
36,158
package org.fax4j.spi.email; import java.io.IOException; import javax.mail.Message; import javax.mail.Transport; import org.fax4j.FaxException; import org.fax4j.FaxJob; import org.fax4j.common.Logger; import org.fax4j.spi.AbstractFax4JClientSpi; import org.fax4j.util.Connection; import org.fax4j.util.ReflectionHelper; /** * This class implements the fax client service provider interface.<br> * This parial implementation will invoke the requests by sending emails to a mail server that supports * conversion between email messages and fax messages.<br> * The mail SPI supports persistent connection to enable to reuse the same connection for all fax * operation invocations or to create a new connection for each fax operation invocation.<br> * By default the SPI will create a new connection for each operation invocation however the * <b>org.fax4j.spi.mail.persistent.connection</b> set to true will enable to reuse the connection.<br> * To set the user/password values of the mail connection the following 2 properties must be defined: * <b>org.fax4j.spi.mail.user.name</b> and <b>org.fax4j.spi.mail.password</b><br> * All properties defined in the fax4j configuration will be passed to the mail connection therefore it is * possible to define mail specific properties (see java mail for more info) in the fax4j properties.<br> * Implementing SPI class will have to implement the createXXXFaxJobMessage methods.<br> * These methods will return the message to be sent for that fax job operation. In case the method * returns null, this class will throw an UnsupportedOperationException exception. * <br> * The configuration of the fax4j framework is made up of 3 layers.<br> * The configuration is based on simple properties.<br> * Each layer overrides the lower layers by adding/changing the property values.<br> * The first layer is the internal fax4j.properties file located in the fax4j jar.<br> * This layer contains the preconfigured values for the fax4j framework and can be changed * by updating these properties in the higher layers.<br> * The second layer is the external fax4j.properties file that is located on the classpath.<br> * This file is optional and provides the ability to override the internal configuration for the * entire fax4j framework.<br> * The top most layer is the optional java.util.Properties object provided by the external classes * when creating a new fax client.<br> * These properties enable to override the configuration of the lower 2 layers.<br> * <br> * <b>SPI Status (Draft, Beta, Stable): </b>Stable<br> * <br> * Below table describes the configuration values relevant for this class.<br> * <b>Configuration:</b> * <table summary="" border="1"> * <tr> * <td>Name</td> * <td>Description</td> * <td>Preconfigured Value</td> * <td>Default Value</td> * <td>Mandatory</td> * </tr> * <tr> * <td>org.fax4j.spi.mail.persistent.connection</td> * <td>True to reuse the same mail connection for all fax activites, false to create a * new mail connection for each fax activity.</td> * <td>false</td> * <td>false</td> * <td>false</td> * </tr> * <tr> * <td>org.fax4j.spi.mail.connection.factory.class.name</td> * <td>The connection factory class name</td> * <td>org.fax4j.spi.email.MailConnectionFactoryImpl</td> * <td>org.fax4j.spi.email.MailConnectionFactoryImpl</td> * <td>false</td> * </tr> * <tr> * <td>org.fax4j.spi.mail.user.name</td> * <td>The mail account user name.</td> * <td>none</td> * <td>none</td> * <td>false</td> * </tr> * <tr> * <td>org.fax4j.spi.mail.password</td> * <td>The mail account password.</td> * <td>none</td> * <td>none</td> * <td>false</td> * </tr> * <tr> * <td>javax mail properties</td> * <td>Any of the javax mail properties can be defined in the fax4j properties.<br> * These properties will be passed to the java mail framework.</td> * <td>mail.transport.protocol=smtp<br> * mail.smtp.port=25</td> * <td>none</td> * <td>false</td> * </tr> * </table> * <br> * <b>Limitations:</b><br> * <ul> * <li>This SPI is based on the java mail infrastructure, therefore this SPI cannot * connect to mail servers through a proxy server. * <li>This SPI provides only partial implementation (this is an abstract class). * </ul> * <br> * <b>Dependencies:</b><br> * <ul> * <li>Required jar files: mail-1.4.jar, activation-1.1.jar * </ul> * <br> * * @author Sagie Gur-Ari * @version 1.12 * @since 0.1 */ public abstract class AbstractMailFaxClientSpi extends AbstractFax4JClientSpi { /** * The use persistent connection flag which defines if the SPI will use a new * connection for each request or will reuse the same connection */ private boolean usePersistentConnection; /**The mail connection factory*/ private MailConnectionFactory connectionFactory; /**The mail connection*/ private Connection<MailResourcesHolder> connection; /** * This class holds the SPI configuration constants. * * @author Sagie Gur-Ari * @version 1.03 * @since 0.1 */ public enum FaxClientSpiConfigurationConstants { /** * The use persistent connection property key which defines if the SPI will use a new * connection for each request or will reuse the same connection */ USE_PERSISTENT_CONNECTION_PROPERTY_KEY("org.fax4j.spi.mail.persistent.connection"), /**The connection factory class name*/ CONNECTION_FACTORY_CLASS_NAME_PROPERTY_KEY("org.fax4j.spi.mail.connection.factory.class.name"), /**The user name used to connect to the mail server*/ USER_NAME_PROPERTY_KEY("org.fax4j.spi.mail.user.name"), /**The password used to connect to the mail server*/ PASSWORD_PROPERTY_KEY("org.fax4j.spi.mail.password"); /**The string value*/ private String value; /** * This is the class constructor. * * @param value * The string value */ private FaxClientSpiConfigurationConstants(String value) { this.value=value; } /** * This function returns the string value. * * @return The string value */ @Override public final String toString() { return this.value; } } /** * This is the default constructor. */ public AbstractMailFaxClientSpi() { super(); } /** * This function initializes the fax client SPI. */ @Override protected void initializeImpl() { //get logger Logger logger=this.getLogger(); //get use persistent connection value this.usePersistentConnection=Boolean.parseBoolean(this.getConfigurationValue(FaxClientSpiConfigurationConstants.USE_PERSISTENT_CONNECTION_PROPERTY_KEY)); logger.logDebug(new Object[]{"Using persistent connection: ",String.valueOf(this.usePersistentConnection)},null); //setup connection factory String className=this.getConfigurationValue(FaxClientSpiConfigurationConstants.CONNECTION_FACTORY_CLASS_NAME_PROPERTY_KEY); this.connectionFactory=this.createMailConnectionFactoryImpl(className); if(this.connectionFactory==null) { throw new FaxException("Mail connection factory is not available."); } } /** * Creates and returns the mail connection factory. * * @param className * The connection factory class name * @return The mail connection factory */ protected final MailConnectionFactory createMailConnectionFactoryImpl(String className) { String factoryClassName=className; if(factoryClassName==null) { factoryClassName=MailConnectionFactoryImpl.class.getName(); } //create new instance MailConnectionFactory factory=(MailConnectionFactory)ReflectionHelper.createInstance(factoryClassName); //initialize factory.initialize(this); return factory; } /** * Releases the connection if open. * * @throws Throwable * Any throwable */ @Override protected void finalize() throws Throwable { //get reference Connection<MailResourcesHolder> mailConnection=this.connection; //release connection this.closeMailConnection(mailConnection); super.finalize(); } /** * Creates and returns the mail connection to be used to send the fax * via mail. * * @return The mail connection */ protected Connection<MailResourcesHolder> createMailConnection() { //create new connection Connection<MailResourcesHolder> mailConnection=this.connectionFactory.createConnection(); //log debug Logger logger=this.getLogger(); logger.logInfo(new Object[]{"Created mail connection."},null); return mailConnection; } /** * This function closes the provided mail connection. * * @param mailConnection * The mail connection to close * @throws IOException * Never thrown */ protected void closeMailConnection(Connection<MailResourcesHolder> mailConnection) throws IOException { if(mailConnection!=null) { //get logger Logger logger=this.getLogger(); //release connection logger.logInfo(new Object[]{"Closing mail connection."},null); mailConnection.close(); } } /** * Returns the mail connection to be used to send the fax * via mail. * * @return The mail connection */ protected Connection<MailResourcesHolder> getMailConnection() { Connection<MailResourcesHolder> mailConnection=null; if(this.usePersistentConnection) { synchronized(this) { if(this.connection==null) { //create new connection this.connection=this.createMailConnection(); } } //get connection mailConnection=this.connection; } else { //create new connection mailConnection=this.createMailConnection(); } return mailConnection; } /** * This function will send the mail message. * * @param faxJob * The fax job object containing the needed information * @param mailConnection * The mail connection (will be released if not persistent) * @param message * The message to send */ protected void sendMail(FaxJob faxJob,Connection<MailResourcesHolder> mailConnection,Message message) { if(message==null) { this.throwUnsupportedException(); } else { //get holder MailResourcesHolder mailResourcesHolder=mailConnection.getResource(); //get transport Transport transport=mailResourcesHolder.getTransport(); try { //send message message.saveChanges(); if(transport==null) { Transport.send(message,message.getAllRecipients()); } else { transport.sendMessage(message,message.getAllRecipients()); } } catch(Throwable throwable) { throw new FaxException("Unable to send message.",throwable); } finally { if(!this.usePersistentConnection) { try { //close connection this.closeMailConnection(mailConnection); } catch(Exception exception) { //log error Logger logger=this.getLogger(); logger.logInfo(new Object[]{"Error while releasing mail connection."},exception); } } } } } /** * This function will submit a new fax job.<br> * The fax job ID may be populated by this method in the provided * fax job object. * * @param faxJob * The fax job object containing the needed information */ @Override protected void submitFaxJobImpl(FaxJob faxJob) { //get connection Connection<MailResourcesHolder> mailConnection=this.getMailConnection(); //get holder MailResourcesHolder mailResourcesHolder=mailConnection.getResource(); //create message Message message=this.createSubmitFaxJobMessage(faxJob,mailResourcesHolder); //send message this.sendMail(faxJob,mailConnection,message); } /** * This function will suspend an existing fax job. * * @param faxJob * The fax job object containing the needed information */ @Override protected void suspendFaxJobImpl(FaxJob faxJob) { //get connection Connection<MailResourcesHolder> mailConnection=this.getMailConnection(); //get holder MailResourcesHolder mailResourcesHolder=mailConnection.getResource(); //create message Message message=this.createSuspendFaxJobMessage(faxJob,mailResourcesHolder); //send message this.sendMail(faxJob,mailConnection,message); } /** * This function will resume an existing fax job. * * @param faxJob * The fax job object containing the needed information */ @Override protected void resumeFaxJobImpl(FaxJob faxJob) { //get connection Connection<MailResourcesHolder> mailConnection=this.getMailConnection(); //get holder MailResourcesHolder mailResourcesHolder=mailConnection.getResource(); //create message Message message=this.createResumeFaxJobMessage(faxJob,mailResourcesHolder); //send message this.sendMail(faxJob,mailConnection,message); } /** * This function will cancel an existing fax job. * * @param faxJob * The fax job object containing the needed information */ @Override protected void cancelFaxJobImpl(FaxJob faxJob) { //get connection Connection<MailResourcesHolder> mailConnection=this.getMailConnection(); //get holder MailResourcesHolder mailResourcesHolder=mailConnection.getResource(); //create message Message message=this.createCancelFaxJobMessage(faxJob,mailResourcesHolder); //send message this.sendMail(faxJob,mailConnection,message); } /** * This function will create the message used to invoke the fax * job action.<br> * If this method returns null, the SPI will throw an UnsupportedOperationException. * * @param faxJob * The fax job object containing the needed information * @param mailResourcesHolder * The mail resources holder * @return The message to send (if null, the SPI will throw an UnsupportedOperationException) */ protected abstract Message createSubmitFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder); /** * This function will create the message used to invoke the fax * job action.<br> * If this method returns null, the SPI will throw an UnsupportedOperationException. * * @param faxJob * The fax job object containing the needed information * @param mailResourcesHolder * The mail resources holder * @return The message to send (if null, the SPI will throw an UnsupportedOperationException) */ protected abstract Message createSuspendFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder); /** * This function will create the message used to invoke the fax * job action.<br> * If this method returns null, the SPI will throw an UnsupportedOperationException. * * @param faxJob * The fax job object containing the needed information * @param mailResourcesHolder * The mail resources holder * @return The message to send (if null, the SPI will throw an UnsupportedOperationException) */ protected abstract Message createResumeFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder); /** * This function will create the message used to invoke the fax * job action.<br> * If this method returns null, the SPI will throw an UnsupportedOperationException. * * @param faxJob * The fax job object containing the needed information * @param mailResourcesHolder * The mail resources holder * @return The message to send (if null, the SPI will throw an UnsupportedOperationException) */ protected abstract Message createCancelFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder); }
ZhernakovMikhail/fax4j
src/main/java/org/fax4j/spi/email/AbstractMailFaxClientSpi.java
Java
apache-2.0
15,447
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_1435 { }
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_1435.java
Java
apache-2.0
151
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Mvc; using Cats.Helpers; using Cats.Models; using Cats.Models.PSNP; using Cats.Data; using Cats.Services.Administration; using Cats.Services.PSNP; using Cats.Services.Security; using Cats.Services.Transaction; using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; using Cats.Services.EarlyWarning; using Cats.Services.Common; using Cats.Infrastructure; using log4net; using IAdminUnitService = Cats.Services.EarlyWarning.IAdminUnitService; namespace Cats.Areas.PSNP { public class RegionalPSNPPlanController : Controller { private int _regionalPsnpId = 0; private readonly IRegionalPSNPPlanService _regionalPSNPPlanService; private readonly IAdminUnitService _adminUnitService; private readonly IRationService _rationService; private readonly IBusinessProcessService _BusinessProcessService; private readonly IBusinessProcessStateService _BusinessProcessStateService; private readonly IApplicationSettingService _ApplicationSettingService; private readonly ILog _log; private readonly IPlanService _planService; private readonly IUserAccountService _userAccountService; private readonly Cats.Services.Transaction.ITransactionService _transactionService; private readonly IUserProfileService _userProfileService; public RegionalPSNPPlanController(IRegionalPSNPPlanService regionalPSNPPlanServiceParam , IRationService rationServiceParam , IAdminUnitService adminUnitServiceParam , IBusinessProcessService BusinessProcessServiceParam , IBusinessProcessStateService BusinessProcessStateServiceParam , IApplicationSettingService ApplicationSettingParam , ILog log , IPlanService planService ,IUserAccountService userAccountService, ITransactionService transactionService, IUserProfileService userProfileService) { this._regionalPSNPPlanService = regionalPSNPPlanServiceParam; this._rationService = rationServiceParam; this._adminUnitService = adminUnitServiceParam; this._BusinessProcessService = BusinessProcessServiceParam; this._BusinessProcessStateService = BusinessProcessStateServiceParam; this._ApplicationSettingService = ApplicationSettingParam; this._log = log; this._planService = planService; this._userAccountService = userAccountService; _transactionService = transactionService; this._userProfileService = userProfileService; } public IEnumerable<RegionalPSNPPlanViewModel> toViewModel(IEnumerable<Cats.Models.RegionalPSNPPlan> list) { var datePref = _userAccountService.GetUserInfo(HttpContext.User.Identity.Name).DatePreference; try { return (from plan in list select new RegionalPSNPPlanViewModel { RegionalPSNPPlanID = plan.RegionalPSNPPlanID, Duration = plan.Duration, PlanName = plan.Plan.PlanName, Year = plan.Year, // RegionName = plan.Region.Name, RationName = plan.Ration.RefrenceNumber, From = plan.Plan.StartDate.ToCTSPreferedDateFormat(datePref), To = plan.Plan.EndDate.ToCTSPreferedDateFormat(datePref), StatusName = plan.AttachedBusinessProcess.CurrentState.BaseStateTemplate.Name, UserId = plan.User }); } catch (Exception e) { var log = new Logger(); log.LogAllErrorsMesseges(e,_log); } return new List<RegionalPSNPPlanViewModel>(); } public void LoadLookups() { ViewBag.RegionID = new SelectList(_adminUnitService.FindBy(t => t.AdminUnitTypeID == 2), "AdminUnitID", "Name"); ViewBag.RationID = new SelectList(_rationService.GetAllRation(), "RationID", "RefrenceNumber"); var psnpPlans = _planService.FindBy(p => p.ProgramID == 2); ViewBag.PlanId = new SelectList(_planService.FindBy(p => p.ProgramID == 2), "PlanID", "PlanName"); } // // GET: /PSNP/RegionalPSNPPlan/ public ActionResult Index() { IEnumerable<RegionalPSNPPlan> list = (IEnumerable<Cats.Models.RegionalPSNPPlan>)_regionalPSNPPlanService.GetAllRegionalPSNPPlan(); return View(list); } public ActionResult GetListAjax([DataSourceRequest] DataSourceRequest request) { IEnumerable<Cats.Models.RegionalPSNPPlan> list = (IEnumerable<Cats.Models.RegionalPSNPPlan>)_regionalPSNPPlanService.GetAllRegionalPSNPPlan().OrderByDescending(m=>m.RegionalPSNPPlanID); return Json(toViewModel(list).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); } public ActionResult Print(int id = 0) { if (id == 0) { RedirectToAction("Index"); } var reportPath = Server.MapPath("~/Report/PSNP/AnnualPlan.rdlc"); var reportData = _regionalPSNPPlanService.GetAnnualPlanRpt(id); var dataSourceName = "annualplan"; var result = ReportHelper.PrintReport(reportPath, reportData, dataSourceName); return File(result.RenderBytes, result.MimeType); } public ActionResult Details(int id = 0) { RegionalPSNPPlan regionalpsnpplan = _regionalPSNPPlanService.FindById(id); if (regionalpsnpplan == null) { return HttpNotFound(); } return View(regionalpsnpplan); } public ActionResult Promote(BusinessProcessState st) { var isReject = _BusinessProcessService.CheckPlanBeforeReject(st); if (isReject) { } _BusinessProcessService.PromotWorkflow(st); return RedirectToAction("Index"); } public ActionResult promotWorkflow(int id, int nextState) { RegionalPSNPPlan item = _regionalPSNPPlanService.FindById(id); item.StatusID = nextState; _regionalPSNPPlanService.UpdateRegionalPSNPPlan(item); if (item.StatusID == (int) Cats.Models.Constant.PSNPWorkFlow.Completed) PostPSNP(item); return RedirectToAction("Index"); } public void PostPSNP(RegionalPSNPPlan plan) { try { var ration = _rationService.FindBy(r => r.RationID == plan.RationID).FirstOrDefault(); _transactionService.PostPSNPPlan(plan, ration); } catch (Exception ex) { _log.Error("Error in posting psnp:",new Exception(ex.Message)); } } // // GET: /PSNP/RegionalPSNPPlan/Create public ActionResult Create() { LoadLookups(); return View(); } // // POST: /PSNP/RegionalPSNPPlan/Create [HttpPost] public ActionResult Create(RegionalPSNPPlan regionalpsnpplan) { var planName = regionalpsnpplan.Plan.PlanName; var startDate = regionalpsnpplan.Plan.StartDate; var firstDayOfTheMonth = startDate.AddDays(1 - startDate.Day); var endDate = firstDayOfTheMonth.AddMonths(regionalpsnpplan.Duration).AddDays(-1); UserProfile user = _userProfileService.GetUser(User.Identity.Name); if (ModelState.IsValid) { _regionalPSNPPlanService.AddPsnpPlan(planName, firstDayOfTheMonth, endDate); var plan = _planService.Get(m => m.PlanName == planName,null,"Program").FirstOrDefault(); regionalpsnpplan.Plan = plan; //check if this psnp plan exitsts for this year and Plan var exists = plan != null && _regionalPSNPPlanService.DoesPsnpPlanExistForThisRegion(plan.PlanID, regionalpsnpplan.Year); if (!exists) { int BP_PSNP = _ApplicationSettingService.getPSNPWorkflow(); if (BP_PSNP != 0) { BusinessProcessState createdstate = new BusinessProcessState { DatePerformed = DateTime.Now, PerformedBy = "System", Comment = "Created workflow for PSNP Plan" }; var psnpPlan= _regionalPSNPPlanService.CreatePsnpPlan(regionalpsnpplan.Year,regionalpsnpplan.Duration,regionalpsnpplan.RationID,regionalpsnpplan.StatusID,plan.PlanID,user.UserProfileID); //_planService.ChangePlanStatus(regionalpsnpplan.PlanId); BusinessProcess bp = _BusinessProcessService.CreateBusinessProcess(BP_PSNP, regionalpsnpplan. RegionalPSNPPlanID, "PSNP", createdstate); psnpPlan.StatusID = bp.BusinessProcessID; _regionalPSNPPlanService.UpdateRegionalPSNPPlan(psnpPlan); return RedirectToAction("Index"); } ViewBag.ErrorMessage1 = "The workflow assosiated with PSNP planning doesnot exist."; ViewBag.ErrorMessage2 = "Please make sure the workflow is created and configured."; } LoadLookups(); ModelState.AddModelError("Errors", @"PSNP plan already made for this period and plan Name."); return View(regionalpsnpplan); } LoadLookups(); return View(regionalpsnpplan); } // // GET: /PSNP/RegionalPSNPPlan/Edit/5 public ActionResult Edit(int id = 0) { LoadLookups(); RegionalPSNPPlan regionalpsnpplan = _regionalPSNPPlanService.FindById(id); if (regionalpsnpplan == null) { return HttpNotFound(); } return View(regionalpsnpplan); } [HttpPost] public ActionResult Edit(RegionalPSNPPlan regionalpsnpplan) { if (ModelState.IsValid) { _regionalPSNPPlanService.UpdateRegionalPSNPPlan(regionalpsnpplan); return RedirectToAction("Index"); } LoadLookups(); return View(regionalpsnpplan); } // // GET: /PSNP/RegionalPSNPPlan/Delete/5 public ActionResult Delete(int id = 0) { RegionalPSNPPlan regionalpsnpplan = _regionalPSNPPlanService.FindById(id); if (regionalpsnpplan == null) { return HttpNotFound(); } return View(regionalpsnpplan); } // // POST: /PSNP/RegionalPSNPPlan/Delete/5 [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id) { _regionalPSNPPlanService.DeleteById(id); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } } }
ndrmc/cats
Web/Areas/PSNP/Controllers/RegionalPSNPPlanController.cs
C#
apache-2.0
12,466
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Gtk; namespace SailorsTab.Common { public class UIHelper { public static void ShowErrorDialog(Gtk.Widget parent, string message, params object[] parameters) { MessageDialog messagedialog1 = new MessageDialog(findParentWindow(parent), (DialogFlags)3, MessageType.Error, ButtonsType.Ok, message, parameters); messagedialog1.Run(); messagedialog1.Destroy(); } public static int ShowInfoDialog(Gtk.Widget parent, string message, params object[] parameters) { MessageDialog messagedialog1 = new MessageDialog(findParentWindow(parent), (DialogFlags)3, MessageType.Question, ButtonsType.YesNo, false, message, parameters); int num1 = messagedialog1.Run(); messagedialog1.Destroy(); return num1; } private static Window findParentWindow(Gtk.Widget parent) { Window window = null; do { if (parent is Window) { window = (Window)parent; } else { parent = parent.Parent; } } while (window == null); return window; } } }
reinkrul/SailorsTab
SailorsTab.Common/UIHelper.cs
C#
apache-2.0
1,446
// // ======================================================================== // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.spdy.parser; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.jetty.spdy.SessionException; import org.eclipse.jetty.spdy.api.SessionStatus; import org.eclipse.jetty.spdy.frames.ControlFrameType; import org.eclipse.jetty.spdy.frames.CredentialFrame; public class CredentialBodyParser extends ControlFrameBodyParser { private final List<Certificate> certificates = new ArrayList<>(); private final ControlFrameParser controlFrameParser; private State state = State.SLOT; private int totalLength; private int cursor; private short slot; private int proofLength; private byte[] proof; private int certificateLength; private byte[] certificate; public CredentialBodyParser(ControlFrameParser controlFrameParser) { this.controlFrameParser = controlFrameParser; } @Override public boolean parse(ByteBuffer buffer) { while (buffer.hasRemaining()) { switch (state) { case SLOT: { if (buffer.remaining() >= 2) { slot = buffer.getShort(); checkSlotValid(); state = State.PROOF_LENGTH; } else { state = State.SLOT_BYTES; cursor = 2; } break; } case SLOT_BYTES: { byte currByte = buffer.get(); --cursor; slot += (currByte & 0xFF) << 8 * cursor; if (cursor == 0) { checkSlotValid(); state = State.PROOF_LENGTH; } break; } case PROOF_LENGTH: { if (buffer.remaining() >= 4) { proofLength = buffer.getInt() & 0x7F_FF_FF_FF; state = State.PROOF; } else { state = State.PROOF_LENGTH_BYTES; cursor = 4; } break; } case PROOF_LENGTH_BYTES: { byte currByte = buffer.get(); --cursor; proofLength += (currByte & 0xFF) << 8 * cursor; if (cursor == 0) { proofLength &= 0x7F_FF_FF_FF; state = State.PROOF; } break; } case PROOF: { totalLength = controlFrameParser.getLength() - 2 - 4 - proofLength; proof = new byte[proofLength]; if (buffer.remaining() >= proofLength) { buffer.get(proof); state = State.CERTIFICATE_LENGTH; if (totalLength == 0) { onCredential(); return true; } } else { state = State.PROOF_BYTES; cursor = proofLength; } break; } case PROOF_BYTES: { proof[proofLength - cursor] = buffer.get(); --cursor; if (cursor == 0) { state = State.CERTIFICATE_LENGTH; if (totalLength == 0) { onCredential(); return true; } } break; } case CERTIFICATE_LENGTH: { if (buffer.remaining() >= 4) { certificateLength = buffer.getInt() & 0x7F_FF_FF_FF; state = State.CERTIFICATE; } else { state = State.CERTIFICATE_LENGTH_BYTES; cursor = 4; } break; } case CERTIFICATE_LENGTH_BYTES: { byte currByte = buffer.get(); --cursor; certificateLength += (currByte & 0xFF) << 8 * cursor; if (cursor == 0) { certificateLength &= 0x7F_FF_FF_FF; state = State.CERTIFICATE; } break; } case CERTIFICATE: { totalLength -= 4 + certificateLength; certificate = new byte[certificateLength]; if (buffer.remaining() >= certificateLength) { buffer.get(certificate); if (onCertificate()) return true; } else { state = State.CERTIFICATE_BYTES; cursor = certificateLength; } break; } case CERTIFICATE_BYTES: { certificate[certificateLength - cursor] = buffer.get(); --cursor; if (cursor == 0) { if (onCertificate()) return true; } break; } default: { throw new IllegalStateException(); } } } return false; } private void checkSlotValid() { if (slot <= 0) throw new SessionException(SessionStatus.PROTOCOL_ERROR, "Invalid slot " + slot + " for " + ControlFrameType.CREDENTIAL + " frame"); } private boolean onCertificate() { certificates.add(deserializeCertificate(certificate)); if (totalLength == 0) { onCredential(); return true; } else { certificateLength = 0; state = State.CERTIFICATE_LENGTH; } return false; } private Certificate deserializeCertificate(byte[] bytes) { try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); return certificateFactory.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException x) { throw new SessionException(SessionStatus.PROTOCOL_ERROR, x); } } private void onCredential() { CredentialFrame frame = new CredentialFrame(controlFrameParser.getVersion(), slot, Arrays.copyOf(proof, proof.length), certificates.toArray(new Certificate[certificates.size()])); controlFrameParser.onControlFrame(frame); reset(); } private void reset() { state = State.SLOT; totalLength = 0; cursor = 0; slot = 0; proofLength = 0; proof = null; certificateLength = 0; certificate = null; certificates.clear(); } public enum State { SLOT, SLOT_BYTES, PROOF_LENGTH, PROOF_LENGTH_BYTES, PROOF, PROOF_BYTES, CERTIFICATE_LENGTH, CERTIFICATE_LENGTH_BYTES, CERTIFICATE, CERTIFICATE_BYTES } }
xmpace/jetty-read
jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/parser/CredentialBodyParser.java
Java
apache-2.0
9,058
package com.ctrip.xpipe.redis.core.protocal; /** * @author wenchao.meng * * 2016年3月24日 下午6:27:48 */ public interface RedisProtocol { int REDIS_PORT_DEFAULT = 6379; int KEEPER_PORT_DEFAULT = 6380; int RUN_ID_LENGTH = 40; String CRLF = "\r\n"; String OK = "OK"; String KEEPER_ROLE_PREFIX = "keeperrole"; static String booleanToString(boolean yes){ if(yes){ return "yes"; } return "no"; } }
ctripcorp/x-pipe
redis/redis-core/src/main/java/com/ctrip/xpipe/redis/core/protocal/RedisProtocol.java
Java
apache-2.0
432
<? namespace CodeCraft; use CodeCraft\Helpers\LanguageLink; class SiteRouter { private $language = []; private $defaultLanguage = 'ru'; private $languageUrlMap = []; private $languageList = ['ru' => ['ru', 'be', 'uk', 'ky', 'ab', 'mo', 'et', 'lv'], 'en' => 'en']; /** * @param array $languageUrlMap - ['language' => 'url', ..., 'default' => 'url'] */ public function __construct($languageUrlMap) { $this->setLanguageUrlMap($languageUrlMap); if (($list = strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']))) { if (preg_match_all('/([a-z]{1,8}(?:-[a-z]{1,8})?)(?:;q=([0-9.]+))?/', $list, $list)) { $this->language = array_combine($list[1], $list[2]); foreach ($this->language as $n => $v) { $this->language[$n] = $v ? $v : 1; } arsort($this->language, SORT_NUMERIC); } } else { $this->language = []; } } /** * @param array $languageUrlMap */ public function setLanguageUrlMap(array $languageUrlMap) { $this->languageUrlMap = $languageUrlMap; } /** * @return array */ public function getLanguageUrlMap() { return $this->languageUrlMap; } /** * @param array $languageList * * @return string */ private function getBestMatch(array $languageList) { $languages = array(); foreach ($languageList as $lang => $alias) { if (is_array($alias)) { foreach ($alias as $alias_lang) { $languages[strtolower($alias_lang)] = strtolower($lang); } } else { $languages[strtolower($alias)] = strtolower($lang); } } foreach ($this->language as $l => $v) { $s = strtok($l, '-'); if (isset($languages[$s])) { return $languages[$s]; } } return $this->defaultLanguage; } /** * @param array $languageList */ public function setLanguageList(array $languageList) { $this->languageList = $languageList; } /** * @param string $pathTo404 */ public function route($pathTo404 = '') { $language = $this->getBestMatch($this->languageList); $languageUrlMap = $this->getLanguageUrlMap(); LanguageLink::setRootAlternateHeader($language); if ($languageUrlMap[$language] || $languageUrlMap['default']) { LocalRedirect($languageUrlMap[$language] ?: $languageUrlMap['default'], false, '301 Moved Permanently'); } else { $this->showNotFoundPage($pathTo404); } } /** * @param string $pathTo404 * * @buffer_restart * * @require 404 page * * @die */ public function showNotFoundPage($pathTo404 = '') { if (!$pathTo404) { $pathTo404 = $_SERVER['DOCUMENT_ROOT'] . '/' . $this->getBestMatch($this->languageList) . '/404.php'; } global $APPLICATION; $APPLICATION->RestartBuffer(); try { require_once($pathTo404); } catch (\Exception $e) { \CHTTP::SetStatus('404 Not Found'); echo '<h1>404 Not Found</h1>'; } die; } }
code-craft-ru/bx-features
local/php_interface/include/classes/CodeCraft/SiteRouter.php
PHP
apache-2.0
3,685
package com.pi.xerosync.dbconnect; /** * User: thomas Date: 18/02/14 */ public interface XeroCredentials { String getXeroConsumerKey(); String getXeroConsumerSecret(); String getPrivateKeyPath(); }
tom-haines/patricia-xero-sync
patricia-xero-webapp/src/main/java/com/pi/xerosync/dbconnect/XeroCredentials.java
Java
apache-2.0
207
# coding=utf-8 # Copyright 2022 The Tensor2Tensor 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. """Base classes and utilities for image datasets.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import io import os import numpy as np from tensor2tensor.data_generators import generator_utils from tensor2tensor.data_generators import problem from tensor2tensor.data_generators import text_encoder from tensor2tensor.layers import common_layers from tensor2tensor.layers import modalities from tensor2tensor.utils import contrib from tensor2tensor.utils import metrics import tensorflow.compat.v1 as tf def matplotlib_pyplot(): import matplotlib # pylint: disable=g-import-not-at-top matplotlib.use("agg") import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top return plt def image_to_tf_summary_value(image, tag): """Converts a NumPy image to a tf.Summary.Value object. Args: image: 3-D NumPy array. tag: name for tf.Summary.Value for display in tensorboard. Returns: image_summary: A tf.Summary.Value object. """ curr_image = np.asarray(image, dtype=np.uint8) height, width, n_channels = curr_image.shape # If monochrome image, then reshape to [height, width] if n_channels == 1: curr_image = np.reshape(curr_image, [height, width]) s = io.BytesIO() matplotlib_pyplot().imsave(s, curr_image, format="png") img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(), height=height, width=width, colorspace=n_channels) return tf.Summary.Value(tag=tag, image=img_sum) def convert_predictions_to_image_summaries(hook_args): """Optionally converts images from hooks_args to image summaries. Args: hook_args: DecodeHookArgs namedtuple Returns: summaries: list of tf.Summary values if hook_args.decode_hpara """ decode_hparams = hook_args.decode_hparams if not decode_hparams.display_decoded_images: return [] predictions = hook_args.predictions[0] # Display ten random inputs and outputs so that tensorboard does not hang. all_summaries = [] rand_predictions = np.random.choice(predictions, size=10) for ind, prediction in enumerate(rand_predictions): output_summary = image_to_tf_summary_value( prediction["outputs"], tag="%d_output" % ind) input_summary = image_to_tf_summary_value( prediction["inputs"], tag="%d_input" % ind) all_summaries.append(input_summary) all_summaries.append(output_summary) return all_summaries def resize_by_area(img, size): """image resize function used by quite a few image problems.""" return tf.to_int64( tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA)) def make_multiscale(image, resolutions, resize_method=tf.image.ResizeMethod.BICUBIC, num_channels=3): """Returns list of scaled images, one for each resolution. Args: image: Tensor of shape [height, height, num_channels]. resolutions: List of heights that image's height is resized to. resize_method: tf.image.ResizeMethod. num_channels: Number of channels in image. Returns: List of Tensors, one for each resolution with shape given by [resolutions[i], resolutions[i], num_channels]. """ scaled_images = [] for height in resolutions: scaled_image = tf.image.resize_images( image, size=[height, height], # assuming that height = width method=resize_method) scaled_image = tf.to_int64(scaled_image) scaled_image.set_shape([height, height, num_channels]) scaled_images.append(scaled_image) return scaled_images def make_multiscale_dilated(image, resolutions, num_channels=3): """Returns list of scaled images, one for each resolution. Resizes by skipping every nth pixel. Args: image: Tensor of shape [height, height, num_channels]. resolutions: List of heights that image's height is resized to. The function assumes VALID padding, so the original image's height must be divisible by each resolution's height to return the exact resolution size. num_channels: Number of channels in image. Returns: List of Tensors, one for each resolution with shape given by [resolutions[i], resolutions[i], num_channels] if resolutions properly divide the original image's height; otherwise shape height and width is up to valid skips. """ image_height = common_layers.shape_list(image)[0] scaled_images = [] for height in resolutions: dilation_rate = image_height // height # assuming height = width scaled_image = image[::dilation_rate, ::dilation_rate] scaled_image = tf.to_int64(scaled_image) scaled_image.set_shape([None, None, num_channels]) scaled_images.append(scaled_image) return scaled_images class ImageProblem(problem.Problem): """Base class for problems with images.""" @property def num_channels(self): """Number of color channels.""" return 3 @property def vocab_size(self): """Number of pixel values.""" return 256 def example_reading_spec(self): data_fields = { "image/encoded": tf.FixedLenFeature((), tf.string), "image/format": tf.FixedLenFeature((), tf.string), } data_items_to_decoders = { "inputs": contrib.slim().tfexample_decoder.Image( image_key="image/encoded", format_key="image/format", channels=self.num_channels), } return data_fields, data_items_to_decoders def preprocess_example(self, example, mode, hparams): if not self._was_reversed: example["inputs"] = tf.image.per_image_standardization(example["inputs"]) return example def eval_metrics(self): eval_metrics = [ metrics.Metrics.ACC, metrics.Metrics.ACC_TOP5, metrics.Metrics.ACC_PER_SEQ, metrics.Metrics.NEG_LOG_PERPLEXITY ] if self._was_reversed: eval_metrics += [metrics.Metrics.IMAGE_SUMMARY] return eval_metrics @property def decode_hooks(self): return [convert_predictions_to_image_summaries] class Image2ClassProblem(ImageProblem): """Base class for image classification problems.""" @property def is_small(self): raise NotImplementedError() @property def num_classes(self): raise NotImplementedError() @property def train_shards(self): raise NotImplementedError() @property def dev_shards(self): return 1 @property def class_labels(self): return ["ID_%d" % i for i in range(self.num_classes)] def feature_encoders(self, data_dir): del data_dir return { "inputs": text_encoder.ImageEncoder(channels=self.num_channels), "targets": text_encoder.ClassLabelEncoder(self.class_labels) } def generator(self, data_dir, tmp_dir, is_training): raise NotImplementedError() def example_reading_spec(self): label_key = "image/class/label" data_fields, data_items_to_decoders = ( super(Image2ClassProblem, self).example_reading_spec()) data_fields[label_key] = tf.FixedLenFeature((1,), tf.int64) data_items_to_decoders["targets"] = contrib.slim().tfexample_decoder.Tensor( label_key) return data_fields, data_items_to_decoders def hparams(self, defaults, unused_model_hparams): p = defaults p.modality = {"inputs": modalities.ModalityType.IMAGE, "targets": modalities.ModalityType.CLASS_LABEL} p.vocab_size = {"inputs": 256, "targets": self.num_classes} p.batch_size_multiplier = 4 if self.is_small else 256 p.loss_multiplier = 3.0 if self.is_small else 1.0 if self._was_reversed: p.loss_multiplier = 1.0 p.input_space_id = problem.SpaceID.IMAGE p.target_space_id = problem.SpaceID.IMAGE_LABEL def generate_data(self, data_dir, tmp_dir, task_id=-1): generator_utils.generate_dataset_and_shuffle( self.generator(data_dir, tmp_dir, True), self.training_filepaths(data_dir, self.train_shards, shuffled=False), self.generator(data_dir, tmp_dir, False), self.dev_filepaths(data_dir, self.dev_shards, shuffled=False)) def encode_images_as_png(images): """Yield images encoded as pngs.""" if tf.executing_eagerly(): for image in images: yield tf.image.encode_png(image).numpy() else: (height, width, channels) = images[0].shape with tf.Graph().as_default(): image_t = tf.placeholder(dtype=tf.uint8, shape=(height, width, channels)) encoded_image_t = tf.image.encode_png(image_t) with tf.Session() as sess: for image in images: enc_string = sess.run(encoded_image_t, feed_dict={image_t: image}) yield enc_string def image_generator(images, labels): """Generator for images that takes image and labels lists and creates pngs. Args: images: list of images given as [width x height x channels] numpy arrays. labels: list of ints, same length as images. Yields: A dictionary representing the images with the following fields: * image/encoded: the string encoding the image as PNG, * image/format: the string "png" representing image format, * image/class/label: an integer representing the label, * image/height: an integer representing the height, * image/width: an integer representing the width. Every field is actually a singleton list of the corresponding type. Raises: ValueError: if images is an empty list. """ if not images: raise ValueError("Must provide some images for the generator.") width, height, _ = images[0].shape for (enc_image, label) in zip(encode_images_as_png(images), labels): yield { "image/encoded": [enc_image], "image/format": ["png"], "image/class/label": [int(label)], "image/height": [height], "image/width": [width] } class Image2TextProblem(ImageProblem): """Base class for image-to-text problems.""" @property def is_character_level(self): raise NotImplementedError() @property def vocab_problem(self): raise NotImplementedError() # Not needed if self.is_character_level. @property def target_space_id(self): raise NotImplementedError() @property def train_shards(self): raise NotImplementedError() @property def dev_shards(self): raise NotImplementedError() def generator(self, data_dir, tmp_dir, is_training): raise NotImplementedError() def example_reading_spec(self): label_key = "image/class/label" data_fields, data_items_to_decoders = ( super(Image2TextProblem, self).example_reading_spec()) data_fields[label_key] = tf.VarLenFeature(tf.int64) data_items_to_decoders["targets"] = contrib.slim().tfexample_decoder.Tensor( label_key) return data_fields, data_items_to_decoders def feature_encoders(self, data_dir): if self.is_character_level: encoder = text_encoder.ByteTextEncoder() else: vocab_filename = os.path.join( data_dir, self.vocab_problem.vocab_filename) encoder = text_encoder.SubwordTextEncoder(vocab_filename) input_encoder = text_encoder.ImageEncoder(channels=self.num_channels) return {"inputs": input_encoder, "targets": encoder} def hparams(self, defaults, unused_model_hparams): p = defaults p.modality = {"inputs": modalities.ModalityType.IMAGE, "targets": modalities.ModalityType.SYMBOL} p.vocab_size = {"inputs": 256, "targets": self._encoders["targets"].vocab_size} p.batch_size_multiplier = 256 p.loss_multiplier = 1.0 p.input_space_id = problem.SpaceID.IMAGE p.target_space_id = self.target_space_id def generate_data(self, data_dir, tmp_dir, task_id=-1): generator_utils.generate_dataset_and_shuffle( self.generator(data_dir, tmp_dir, True), self.training_filepaths(data_dir, self.train_shards, shuffled=False), self.generator(data_dir, tmp_dir, False), self.dev_filepaths(data_dir, self.dev_shards, shuffled=False)) def image_augmentation(images, do_colors=False, crop_size=None): """Image augmentation: cropping, flipping, and color transforms.""" if crop_size is None: crop_size = [299, 299] images = tf.random_crop(images, crop_size + [3]) images = tf.image.random_flip_left_right(images) if do_colors: # More augmentation, but might be slow. images = tf.image.random_brightness(images, max_delta=32. / 255.) images = tf.image.random_saturation(images, lower=0.5, upper=1.5) images = tf.image.random_hue(images, max_delta=0.2) images = tf.image.random_contrast(images, lower=0.5, upper=1.5) return images def cifar_image_augmentation(images): """Image augmentation suitable for CIFAR-10/100. As described in https://arxiv.org/pdf/1608.06993v3.pdf (page 5). Args: images: a Tensor. Returns: Tensor of the same shape as images. """ images = tf.image.resize_image_with_crop_or_pad(images, 40, 40) images = tf.random_crop(images, [32, 32, 3]) images = tf.image.random_flip_left_right(images) return images def random_shift(image, wsr=0.1, hsr=0.1): """Apply random horizontal and vertical shift to images. This is the default data-augmentation strategy used on CIFAR in Glow. Args: image: a 3-D Tensor wsr: Width shift range, as a float fraction of the width. hsr: Height shift range, as a float fraction of the width. Returns: images: images translated by the provided wsr and hsr. """ height, width, _ = common_layers.shape_list(image) width_range, height_range = wsr*width, hsr*height height_translations = tf.random_uniform((1,), -height_range, height_range) width_translations = tf.random_uniform((1,), -width_range, width_range) translations = tf.concat((height_translations, width_translations), axis=0) return contrib.image().translate(image, translations=translations)
tensorflow/tensor2tensor
tensor2tensor/data_generators/image_utils.py
Python
apache-2.0
14,495
/// <reference path='fourslash.ts' /> // @BaselineFile: bpSpan_interface.baseline // @Filename: bpSpan_interface.ts ////interface I { //// property: string; //// method(): number; //// (a: string): string; //// new (a: string): I; //// [a: number]: number; ////} ////module m { //// interface I1 { //// property: string; //// method(): number; //// (a: string): string; //// new (a: string): I; //// [a: number]: number; //// } //// export interface I2 { //// property: string; //// method(): number; //// (a: string): string; //// new (a: string): I; //// [a: number]: number; //// } ////} verify.baselineCurrentFileBreakpointLocations();
freedot/tstolua
tests/cases/fourslash/breakpointValidationInterface.ts
TypeScript
apache-2.0
738
package main.java; public class SelectionSort9 { public static <T extends Comparable<T>> void sort(final T[] a) { for (int i = 0; i < a.length - 1; i++) { int min = i; for (int j = i + 1; j < a.length; j++) { if (a[j].compareTo(a[min]) < 0) { min = j; } } if (i != min) { final T tmp = a[min]; a[min] = a[i]; a[i] = tmp; } } } }
peteriliev/kata
SelectionSort/src/main/java/SelectionSort9.java
Java
apache-2.0
381
package com.sequenceiq.environment.api.v1.environment.model.response; import java.io.Serializable; import com.sequenceiq.environment.api.doc.environment.EnvironmentModelDescription; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel("EnvironmentAuthenticationV1Response") public class EnvironmentAuthenticationResponse implements Serializable { @ApiModelProperty(EnvironmentModelDescription.PUBLIC_KEY) private String publicKey; @ApiModelProperty(EnvironmentModelDescription.PUBLIC_KEY_ID) private String publicKeyId; @ApiModelProperty(EnvironmentModelDescription.LOGIN_USER_NAME) private String loginUserName; public String getPublicKey() { return publicKey; } public void setPublicKey(String publicKey) { this.publicKey = publicKey; } public String getPublicKeyId() { return publicKeyId; } public void setPublicKeyId(String publicKeyId) { this.publicKeyId = publicKeyId; } public String getLoginUserName() { return loginUserName; } public void setLoginUserName(String loginUserName) { this.loginUserName = loginUserName; } public static Builder builder() { return new Builder(); } @Override public String toString() { return "EnvironmentAuthenticationResponse{" + "publicKey='" + publicKey + '\'' + ", publicKeyId='" + publicKeyId + '\'' + ", loginUserName='" + loginUserName + '\'' + '}'; } public static class Builder { private String publicKey; private String publicKeyId; private String loginUserName; private Builder() { } public Builder withPublicKey(String publicKey) { this.publicKey = publicKey; return this; } public Builder withPublicKeyId(String publicKeyId) { this.publicKeyId = publicKeyId; return this; } public Builder withLoginUserName(String loginUserName) { this.loginUserName = loginUserName; return this; } public EnvironmentAuthenticationResponse build() { EnvironmentAuthenticationResponse response = new EnvironmentAuthenticationResponse(); response.setLoginUserName(loginUserName); response.setPublicKey(publicKey); response.setPublicKeyId(publicKeyId); return response; } } }
hortonworks/cloudbreak
environment-api/src/main/java/com/sequenceiq/environment/api/v1/environment/model/response/EnvironmentAuthenticationResponse.java
Java
apache-2.0
2,539
/* * This file is part of "lunisolar-magma". * * (C) Copyright 2014-2022 Lunisolar (http://lunisolar.eu/). * * 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 eu.lunisolar.magma.func.predicate; import javax.annotation.Nonnull; // NOSONAR import javax.annotation.Nullable; // NOSONAR import javax.annotation.concurrent.NotThreadSafe; // NOSONAR import java.util.Comparator; // NOSONAR import java.util.Objects; // NOSONAR import eu.lunisolar.magma.basics.*; //NOSONAR import eu.lunisolar.magma.basics.builder.*; // NOSONAR import eu.lunisolar.magma.basics.exceptions.*; // NOSONAR import eu.lunisolar.magma.basics.meta.*; // NOSONAR import eu.lunisolar.magma.basics.meta.aType.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR import eu.lunisolar.magma.func.IA; import eu.lunisolar.magma.func.SA; import eu.lunisolar.magma.func.*; // NOSONAR import eu.lunisolar.magma.func.tuple.*; // NOSONAR import java.util.concurrent.*; // NOSONAR import java.util.function.*; // NOSONAR import java.util.*; // NOSONAR import java.lang.reflect.*; // NOSONAR import eu.lunisolar.magma.func.action.*; // NOSONAR import eu.lunisolar.magma.func.consumer.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR import eu.lunisolar.magma.func.function.*; // NOSONAR import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR import eu.lunisolar.magma.func.function.from.*; // NOSONAR import eu.lunisolar.magma.func.function.to.*; // NOSONAR import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR import eu.lunisolar.magma.func.predicate.*; // NOSONAR import eu.lunisolar.magma.func.supplier.*; // NOSONAR /** * Non-throwing functional interface (lambda) LBiObjLongPredicate for Java 8. * * Type: predicate * * Domain (lvl: 3): T1 a1,T2 a2,long a3 * * Co-domain: boolean * */ @FunctionalInterface @SuppressWarnings("UnusedDeclaration") public interface LBiObjLongPredicate<T1, T2> extends MetaPredicate, MetaInterface.NonThrowing, Codomain<aBool>, Domain3<a<T1>, a<T2>, aLong> { // NOSONAR String DESCRIPTION = "LBiObjLongPredicate: boolean test(T1 a1,T2 a2,long a3)"; // boolean test(T1 a1,T2 a2,long a3) ; default boolean test(T1 a1, T2 a2, long a3) { // return nestingTest(a1,a2,a3); try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call test(T1 a1,T2 a2,long a3) */ boolean testX(T1 a1, T2 a2, long a3) throws Throwable; default boolean tupleTest(LBiObjLongTriple<T1, T2> args) { return test(args.first(), args.second(), args.third()); } /** Function call that handles exceptions according to the instructions. */ default boolean handlingTest(T1 a1, T2 a2, long a3, HandlingInstructions<Throwable, RuntimeException> handling) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handler.handleOrNest(e, handling); } } default LBiObjLongPredicate<T1, T2> handling(HandlingInstructions<Throwable, RuntimeException> handling) { return (a1, a2, a3) -> handlingTest(a1, a2, a3, handling); } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage); } } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage, param1); } } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage, param1, param2); } } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage, param1, param2, param3); } } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage); } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage, param1); } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage, param1, param1); } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage, param1, param2, param3); } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWF<RuntimeException> factory) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory); } } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWF<RuntimeException> factory) { return (a1, a2, a3) -> test(a1, a2, a3, factory); } default boolean testThen(T1 a1, T2 a2, long a3, @Nonnull LPredicate<Throwable> handler) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR Handling.handleErrors(e); return handler.test(e); } } default LBiObjLongPredicate<T1, T2> tryingThen(@Nonnull LPredicate<Throwable> handler) { return (a1, a2, a3) -> testThen(a1, a2, a3, handler); } /** Function call that handles exceptions by always nesting checked exceptions and propagating the others as is. */ default boolean nestingTest(T1 a1, T2 a2, long a3) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** Function call that handles exceptions by always propagating them as is, even when they are undeclared checked ones. */ default boolean shovingTest(T1 a1, T2 a2, long a3) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.shoveIt(e); } } static <T1, T2> boolean shovingTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.shovingTest(a1, a2, a3); } static <T1, T2> boolean handlingTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, HandlingInstructions<Throwable, RuntimeException> handling) { // <- Null.nonNullArg(func, "func"); return func.handlingTest(a1, a2, a3, handling); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.nestingTest(a1, a2, a3); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage, param1); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage, param1, param2); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage, param1, param2, param3); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWF<RuntimeException> factory) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory); } static <T1, T2> boolean tryTestThen(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull LPredicate<Throwable> handler) { Null.nonNullArg(func, "func"); return func.testThen(a1, a2, a3, handler); } default boolean failSafeTest(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<T1, T2> failSafe) { try { return test(a1, a2, a3); } catch (Throwable e) { // NOSONAR Handling.handleErrors(e); return failSafe.test(a1, a2, a3); } } static <T1, T2> boolean failSafeTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull LBiObjLongPredicate<T1, T2> failSafe) { Null.nonNullArg(failSafe, "failSafe"); if (func == null) { return failSafe.test(a1, a2, a3); } else { return func.failSafeTest(a1, a2, a3, failSafe); } } static <T1, T2> LBiObjLongPredicate<T1, T2> failSafe(LBiObjLongPredicate<T1, T2> func, @Nonnull LBiObjLongPredicate<T1, T2> failSafe) { Null.nonNullArg(failSafe, "failSafe"); return (a1, a2, a3) -> failSafeTest(a1, a2, a3, func, failSafe); } default boolean doIf(T1 a1, T2 a2, long a3, LAction action) { Null.nonNullArg(action, "action"); if (test(a1, a2, a3)) { action.execute(); return true; } else { return false; } } static <T1, T2> boolean doIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<T1, T2> predicate, @Nonnull LAction action) { Null.nonNullArg(predicate, "predicate"); return predicate.doIf(a1, a2, a3, action); } static <T1, T2> boolean doIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<T1, T2> predicate, @Nonnull LBiObjLongConsumer<? super T1, ? super T2> consumer) { Null.nonNullArg(predicate, "predicate"); return predicate.doIf(a1, a2, a3, consumer); } default boolean doIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongConsumer<? super T1, ? super T2> consumer) { Null.nonNullArg(consumer, "consumer"); if (test(a1, a2, a3)) { consumer.accept(a1, a2, a3); return true; } else { return false; } } /** Just to mirror the method: Ensures the result is not null */ default boolean nonNullTest(T1 a1, T2 a2, long a3) { return test(a1, a2, a3); } /** For convenience, where "test()" makes things more confusing than "applyAsBoolean()". */ default boolean doApplyAsBoolean(T1 a1, T2 a2, long a3) { return test(a1, a2, a3); } /** Returns description of the functional interface. */ @Nonnull default String functionalInterfaceDescription() { return LBiObjLongPredicate.DESCRIPTION; } /** From-To. Intended to be used with non-capturing lambda. */ public static <T1, T2> void fromTo(long min_a3, long max_a3, T1 a1, T2 a2, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); if (min_a3 <= max_a3) { for (long a3 = min_a3; a3 <= max_a3; a3++) { func.test(a1, a2, a3); } } else { for (long a3 = min_a3; a3 >= max_a3; a3--) { func.test(a1, a2, a3); } } } /** From-To. Intended to be used with non-capturing lambda. */ public static <T1, T2> void fromTill(long min_a3, long max_a3, T1 a1, T2 a2, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); if (min_a3 <= max_a3) { for (long a3 = min_a3; a3 < max_a3; a3++) { func.test(a1, a2, a3); } } else { for (long a3 = min_a3; a3 > max_a3; a3--) { func.test(a1, a2, a3); } } } /** From-To. Intended to be used with non-capturing lambda. */ public static <T1, T2> void times(long max_a3, T1 a1, T2 a2, @Nonnull LBiObjLongPredicate<T1, T2> func) { if (max_a3 < 0) return; fromTill(0, max_a3, a1, a2, func); } /** Extract and apply function. */ public static <M, K, V, T2> boolean from(@Nonnull M container, LBiFunction<M, K, V> extractor, K key, T2 a2, long a3, @Nonnull LBiObjLongPredicate<V, T2> function) { Null.nonNullArg(container, "container"); Null.nonNullArg(function, "function"); V value = extractor.apply(container, key); if (value != null) { return function.test(value, a2, a3); } return false; } default LObjLongPredicate<T2> lShrink(@Nonnull LObjLongFunction<T2, T1> left) { Null.nonNullArg(left, "left"); return (a2, a3) -> test(left.apply(a2, a3), a2, a3); } default LObjLongPredicate<T2> lShrink_(T1 a1) { return (a2, a3) -> test(a1, a2, a3); } public static <T2, T1> LObjLongPredicate<T2> lShrunken(@Nonnull LObjLongFunction<T2, T1> left, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(left, "left"); Null.nonNullArg(func, "func"); return func.lShrink(left); } public static <T2, T1> LObjLongPredicate<T2> lShrunken_(T1 a1, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.lShrink_(a1); } default LBiPredicate<T1, T2> rShrink(@Nonnull LToLongBiFunction<T1, T2> right) { Null.nonNullArg(right, "right"); return (a1, a2) -> test(a1, a2, right.applyAsLong(a1, a2)); } default LBiPredicate<T1, T2> rShrink_(long a3) { return (a1, a2) -> test(a1, a2, a3); } public static <T1, T2> LBiPredicate<T1, T2> rShrunken(@Nonnull LToLongBiFunction<T1, T2> right, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(right, "right"); Null.nonNullArg(func, "func"); return func.rShrink(right); } public static <T1, T2> LBiPredicate<T1, T2> rShrunken_(long a3, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.rShrink_(a3); } /** */ public static <T1, T2> LBiObjLongPredicate<T1, T2> uncurry(@Nonnull LFunction<T1, LFunction<T2, LLongPredicate>> func) { Null.nonNullArg(func, "func"); return (T1 a1, T2 a2, long a3) -> func.apply(a1).apply(a2).test(a3); } /** Cast that removes generics. */ default LBiObjLongPredicate untyped() { return this; } /** Cast that replace generics. */ default <V2, V3> LBiObjLongPredicate<V2, V3> cast() { return untyped(); } /** Cast that replace generics. */ public static <V2, V3> LBiObjLongPredicate<V2, V3> cast(LBiObjLongPredicate<?, ?> function) { return (LBiObjLongPredicate) function; } /** Change function to consumer that ignores output. */ default LBiObjLongConsumer<T1, T2> toConsumer() { return this::test; } /** Calls domain consumer before main function. */ default LBiObjLongPredicate<T1, T2> beforeDo(@Nonnull LBiObjLongConsumer<T1, T2> before) { Null.nonNullArg(before, "before"); return (T1 a1, T2 a2, long a3) -> { before.accept(a1, a2, a3); return test(a1, a2, a3); }; } /** Calls codomain consumer after main function. */ default LBiObjLongPredicate<T1, T2> afterDo(@Nonnull LBoolConsumer after) { Null.nonNullArg(after, "after"); return (T1 a1, T2 a2, long a3) -> { final boolean retval = test(a1, a2, a3); after.accept(retval); return retval; }; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (!pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (!pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(msg, a1, a2, a3) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2, param3) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(msg, a1, a2, a3) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2, param3) + ' ' + m); } return a1; } /** Captures arguments but delays the evaluation. */ default LBoolSupplier capture(T1 a1, T2 a2, long a3) { return () -> this.test(a1, a2, a3); } /** Creates function that always returns the same value. */ static <T1, T2> LBiObjLongPredicate<T1, T2> constant(boolean r) { return (a1, a2, a3) -> r; } /** Captures single parameter function into this interface where only 1st parameter will be used. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> test1st(@Nonnull LPredicate<T1> func) { return (a1, a2, a3) -> func.test(a1); } /** Captures single parameter function into this interface where only 2nd parameter will be used. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> test2nd(@Nonnull LPredicate<T2> func) { return (a1, a2, a3) -> func.test(a2); } /** Captures single parameter function into this interface where only 3rd parameter will be used. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> test3rd(@Nonnull LLongPredicate func) { return (a1, a2, a3) -> func.test(a3); } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPred(final @Nonnull LBiObjLongPredicate<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** A completely inconvenient method in case lambda expression and generic arguments are ambiguous for the compiler. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPred(@Nullable Class<T1> c1, @Nullable Class<T2> c2, final @Nonnull LBiObjLongPredicate<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } final class S<T1, T2> implements LBiObjLongPredicate<T1, T2> { private LBiObjLongPredicate<T1, T2> target = null; @Override public boolean testX(T1 a1, T2 a2, long a3) throws Throwable { return target.testX(a1, a2, a3); } } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> recursive(final @Nonnull LFunction<LBiObjLongPredicate<T1, T2>, LBiObjLongPredicate<T1, T2>> selfLambda) { final S<T1, T2> single = new S(); LBiObjLongPredicate<T1, T2> func = selfLambda.apply(single); single.target = func; return func; } public static <T1, T2> M<T1, T2> mementoOf(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> function) { var initialValue = function.test(a1, a2, a3); return initializedMementoOf(initialValue, function); } public static <T1, T2> M<T1, T2> initializedMementoOf(boolean initialValue, LBiObjLongPredicate<T1, T2> function) { return memento(initialValue, initialValue, function, (m, x1, x2) -> x2); } public static <T1, T2> M<T1, T2> deltaOf(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> function, LLogicalBinaryOperator deltaFunction) { var initialValue = function.test(a1, a2, a3); return initializedDeltaOf(initialValue, function, deltaFunction); } public static <T1, T2> M<T1, T2> deltaOf(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> function) { var initialValue = function.test(a1, a2, a3); return initializedDeltaOf(initialValue, function, (x1, x2) -> x1 != x2); } public static <T1, T2> M<T1, T2> initializedDeltaOf(boolean initialValue, LBiObjLongPredicate<T1, T2> function, LLogicalBinaryOperator deltaFunction) { return memento(initialValue, deltaFunction.apply(initialValue, initialValue), function, (m, x1, x2) -> deltaFunction.apply(x1, x2)); } public static <T1, T2> M<T1, T2> memento(boolean initialBaseValue, boolean initialValue, LBiObjLongPredicate<T1, T2> baseFunction, LLogicalTernaryOperator mementoFunction) { return new M(initialBaseValue, initialValue, baseFunction, mementoFunction); } /** * Implementation that allows to create derivative functions (do not confuse it with math concepts). Very short name is intended to be used with parent (LBiObjLongPredicate.M) */ @NotThreadSafe final class M<T1, T2> implements LBiObjLongPredicate<T1, T2> { private final LBiObjLongPredicate<T1, T2> baseFunction; private boolean lastBaseValue; private boolean lastValue; private final LLogicalTernaryOperator mementoFunction; private M(boolean lastBaseValue, boolean lastValue, LBiObjLongPredicate<T1, T2> baseFunction, LLogicalTernaryOperator mementoFunction) { this.baseFunction = baseFunction; this.lastBaseValue = lastBaseValue; this.lastValue = lastValue; this.mementoFunction = mementoFunction; } @Override public boolean testX(T1 a1, T2 a2, long a3) throws Throwable { boolean x1 = lastBaseValue; boolean x2 = lastBaseValue = baseFunction.testX(a1, a2, a3); return lastValue = mementoFunction.apply(lastValue, x1, x2); } public boolean lastValue() { return lastValue; }; public boolean lastBaseValue() { return lastBaseValue; }; } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPredThrowing(final @Nonnull ExF<Throwable> exF) { Null.nonNullArg(exF, "exF"); return (a1, a2, a3) -> { throw exF.produce(); }; } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPredThrowing(final String message, final @Nonnull ExMF<Throwable> exF) { Null.nonNullArg(exF, "exF"); return (a1, a2, a3) -> { throw exF.produce(message); }; } // <editor-fold desc="wrap variants"> /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T1, T2> LBiObjLongPredicate.LObj0Long2Obj1Pred<T1, T2> obj0Long2Obj1Pred(final @Nonnull LBiObjLongPredicate.LObj0Long2Obj1Pred<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T2, T1> LBiObjLongPredicate.LObj1Obj0Long2Pred<T2, T1> obj1Obj0Long2Pred(final @Nonnull LBiObjLongPredicate.LObj1Obj0Long2Pred<T2, T1> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T2, T1> LBiObjLongPredicate.LObj1Long2Obj0Pred<T2, T1> obj1Long2Obj0Pred(final @Nonnull LBiObjLongPredicate.LObj1Long2Obj0Pred<T2, T1> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T1, T2> LBiObjLongPredicate.LLong2Obj0Obj1Pred<T1, T2> long2Obj0Obj1Pred(final @Nonnull LBiObjLongPredicate.LLong2Obj0Obj1Pred<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T2, T1> LBiObjLongPredicate.LLong2Obj1Obj0Pred<T2, T1> long2Obj1Obj0Pred(final @Nonnull LBiObjLongPredicate.LLong2Obj1Obj0Pred<T2, T1> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } // </editor-fold> static <T1, T2> boolean call(T1 a1, T2 a2, long a3, final @Nonnull LBiObjLongPredicate<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda.test(a1, a2, a3); } // <editor-fold desc="wrap"> // </editor-fold> // <editor-fold desc="predicate"> /** * Returns a predicate that represents the logical negation of this predicate. * * @see {@link java.util.function.Predicate#negate} */ @Nonnull default LBiObjLongPredicate<T1, T2> negate() { return (a1, a2, a3) -> !test(a1, a2, a3); } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> not(@Nonnull LBiObjLongPredicate<T1, T2> pred) { Null.nonNullArg(pred, "pred"); return pred.negate(); } /** * Returns a predicate that represents the logical AND of evaluation of this predicate and the argument one. * @see {@link java.util.function.Predicate#and()} */ @Nonnull default LBiObjLongPredicate<T1, T2> and(@Nonnull LBiObjLongPredicate<? super T1, ? super T2> other) { Null.nonNullArg(other, "other"); return (a1, a2, a3) -> test(a1, a2, a3) && other.test(a1, a2, a3); } @Nonnull public static <T1, T2> LBiObjLongPredicate<T1, T2> and(@Nonnull LBiObjLongPredicate<? super T1, ? super T2>... predicates) { Null.nonNullArg(predicates, "predicates"); return (a1, a2, a3) -> { for (LBiObjLongPredicate<? super T1, ? super T2> p : predicates) { if (!p.test(a1, a2, a3)) { return false; } } return true; }; } /** * Returns a predicate that represents the logical OR of evaluation of this predicate and the argument one. * @see {@link java.util.function.Predicate#or} */ @Nonnull default LBiObjLongPredicate<T1, T2> or(@Nonnull LBiObjLongPredicate<? super T1, ? super T2> other) { Null.nonNullArg(other, "other"); return (a1, a2, a3) -> test(a1, a2, a3) || other.test(a1, a2, a3); } @Nonnull public static <T1, T2> LBiObjLongPredicate<T1, T2> or(@Nonnull LBiObjLongPredicate<? super T1, ? super T2>... predicates) { Null.nonNullArg(predicates, "predicates"); return (a1, a2, a3) -> { for (LBiObjLongPredicate<? super T1, ? super T2> p : predicates) { if (p.test(a1, a2, a3)) { return true; } } return false; }; } /** * Returns a predicate that represents the logical XOR of evaluation of this predicate and the argument one. * @see {@link java.util.function.Predicate#or} */ @Nonnull default LBiObjLongPredicate<T1, T2> xor(@Nonnull LBiObjLongPredicate<? super T1, ? super T2> other) { Null.nonNullArg(other, "other"); return (a1, a2, a3) -> test(a1, a2, a3) ^ other.test(a1, a2, a3); } /** * Creates predicate that evaluates if an object is equal with the argument one. * @see {@link java.util.function.Predicate#isEqual() */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> isEqual(T1 v1, T2 v2, long v3) { return (a1, a2, a3) -> (a1 == null ? v1 == null : a1.equals(v1)) && (a2 == null ? v2 == null : a2.equals(v2)) && (a3 == v3); } // </editor-fold> // <editor-fold desc="compose (functional)"> /** Allows to manipulate the domain of the function. */ @Nonnull default <V1, V2> LBiObjLongPredicate<V1, V2> compose(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LLongUnaryOperator before3) { Null.nonNullArg(before1, "before1"); Null.nonNullArg(before2, "before2"); Null.nonNullArg(before3, "before3"); return (v1, v2, v3) -> this.test(before1.apply(v1), before2.apply(v2), before3.applyAsLong(v3)); } public static <V1, V2, T1, T2> LBiObjLongPredicate<V1, V2> composed(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LLongUnaryOperator before3, LBiObjLongPredicate<T1, T2> after) { return after.compose(before1, before2, before3); } /** Allows to manipulate the domain of the function. */ @Nonnull default <V1, V2, V3> LTriPredicate<V1, V2, V3> biObjLongPredCompose(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LToLongFunction<? super V3> before3) { Null.nonNullArg(before1, "before1"); Null.nonNullArg(before2, "before2"); Null.nonNullArg(before3, "before3"); return (v1, v2, v3) -> this.test(before1.apply(v1), before2.apply(v2), before3.applyAsLong(v3)); } public static <V1, V2, V3, T1, T2> LTriPredicate<V1, V2, V3> composed(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LToLongFunction<? super V3> before3, LBiObjLongPredicate<T1, T2> after) { return after.biObjLongPredCompose(before1, before2, before3); } // </editor-fold> // <editor-fold desc="then (functional)"> /** Combines two functions together in a order. */ @Nonnull default <V> LBiObjLongFunction<T1, T2, V> boolToBiObjLongFunc(@Nonnull LBoolFunction<? extends V> after) { Null.nonNullArg(after, "after"); return (a1, a2, a3) -> after.apply(this.test(a1, a2, a3)); } /** Combines two functions together in a order. */ @Nonnull default LBiObjLongPredicate<T1, T2> boolToBiObjLongPred(@Nonnull LLogicalOperator after) { Null.nonNullArg(after, "after"); return (a1, a2, a3) -> after.apply(this.test(a1, a2, a3)); } // </editor-fold> // <editor-fold desc="variant conversions"> // </editor-fold> // <editor-fold desc="interface variants"> /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LObj0Long2Obj1Pred<T1, T2> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call test(T1 a1,T2 a2,long a3) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testObj0Long2Obj1(a1, a3, a2); } // boolean testObj0Long2Obj1(T1 a1,long a3,T2 a2) ; default boolean testObj0Long2Obj1(T1 a1, long a3, T2 a2) { // return nestingTestObj0Long2Obj1(a1,a3,a2); try { return this.testObj0Long2Obj1X(a1, a3, a2); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testObj0Long2Obj1(T1 a1,long a3,T2 a2) */ boolean testObj0Long2Obj1X(T1 a1, long a3, T2 a2) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LObj1Obj0Long2Pred<T2, T1> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testObj0Long2Obj1(T1 a1,long a3,T2 a2) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testObj1Obj0Long2(a2, a1, a3); } // boolean testObj1Obj0Long2(T2 a2,T1 a1,long a3) ; default boolean testObj1Obj0Long2(T2 a2, T1 a1, long a3) { // return nestingTestObj1Obj0Long2(a2,a1,a3); try { return this.testObj1Obj0Long2X(a2, a1, a3); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testObj1Obj0Long2(T2 a2,T1 a1,long a3) */ boolean testObj1Obj0Long2X(T2 a2, T1 a1, long a3) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LObj1Long2Obj0Pred<T2, T1> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testObj1Obj0Long2(T2 a2,T1 a1,long a3) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testObj1Long2Obj0(a2, a3, a1); } // boolean testObj1Long2Obj0(T2 a2,long a3,T1 a1) ; default boolean testObj1Long2Obj0(T2 a2, long a3, T1 a1) { // return nestingTestObj1Long2Obj0(a2,a3,a1); try { return this.testObj1Long2Obj0X(a2, a3, a1); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testObj1Long2Obj0(T2 a2,long a3,T1 a1) */ boolean testObj1Long2Obj0X(T2 a2, long a3, T1 a1) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LLong2Obj0Obj1Pred<T1, T2> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testObj1Long2Obj0(T2 a2,long a3,T1 a1) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testLong2Obj0Obj1(a3, a1, a2); } // boolean testLong2Obj0Obj1(long a3,T1 a1,T2 a2) ; default boolean testLong2Obj0Obj1(long a3, T1 a1, T2 a2) { // return nestingTestLong2Obj0Obj1(a3,a1,a2); try { return this.testLong2Obj0Obj1X(a3, a1, a2); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testLong2Obj0Obj1(long a3,T1 a1,T2 a2) */ boolean testLong2Obj0Obj1X(long a3, T1 a1, T2 a2) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LLong2Obj1Obj0Pred<T2, T1> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testLong2Obj0Obj1(long a3,T1 a1,T2 a2) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testLong2Obj1Obj0(a3, a2, a1); } // boolean testLong2Obj1Obj0(long a3,T2 a2,T1 a1) ; default boolean testLong2Obj1Obj0(long a3, T2 a2, T1 a1) { // return nestingTestLong2Obj1Obj0(a3,a2,a1); try { return this.testLong2Obj1Obj0X(a3, a2, a1); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testLong2Obj1Obj0(long a3,T2 a2,T1 a1) */ boolean testLong2Obj1Obj0X(long a3, T2 a2, T1 a1) throws Throwable; } // </editor-fold> // >>> LBiObjLongPredicate<T1,T2> /** Returns TRUE. */ public static <T1, T2> boolean alwaysTrue(T1 a1, T2 a2, long a3) { return true; } /** Returns FALSE. */ public static <T1, T2> boolean alwaysFalse(T1 a1, T2 a2, long a3) { return false; } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, C3> void filterForEach(IndexedRead<C1, a<T1>> ia1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); size = Integer.min(size, ia2.size(source2)); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); size = Integer.min(size, ia3.size(source3)); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; for (; i < size; i++) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = oiFunc2.apply(source2, i); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, I1, C2, C3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); int size = ia2.size(source2); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); size = Integer.min(size, ia3.size(source3)); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; while (testFunc1.test(iterator1) && i < size) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = oiFunc2.apply(source2, i); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, I2, C3> void filterIterate(IndexedRead<C1, a<T1>> ia1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); size = Integer.min(size, ia3.size(source3)); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; while (i < size && testFunc2.test(iterator2)) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = nextFunc2.apply(iterator2); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, I1, C2, I2, C3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); int size = ia3.size(source3); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; while (testFunc1.test(iterator1) && testFunc2.test(iterator2) && i < size) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = nextFunc2.apply(iterator2); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, C3, I3> void filterIterate(IndexedRead<C1, a<T1>> ia1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); size = Integer.min(size, ia2.size(source2)); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); int i = 0; while (i < size && testFunc3.test(iterator3)) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = oiFunc2.apply(source2, i); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, I1, C2, C3, I3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); int size = ia2.size(source2); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); int i = 0; while (testFunc1.test(iterator1) && i < size && testFunc3.test(iterator3)) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = oiFunc2.apply(source2, i); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, I2, C3, I3> void filterIterate(IndexedRead<C1, a<T1>> ia1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); int i = 0; while (i < size && testFunc2.test(iterator2) && testFunc3.test(iterator3)) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = nextFunc2.apply(iterator2); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method depends highly on the arguments. */ default <C1, I1, C2, I2, C3, I3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); while (testFunc1.test(iterator1) && testFunc2.test(iterator2) && testFunc3.test(iterator3)) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = nextFunc2.apply(iterator2); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); } } }
lunisolar/magma
magma-func/src/main/java/eu/lunisolar/magma/func/predicate/LBiObjLongPredicate.java
Java
apache-2.0
60,660
""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def add_noise(true_R,tau): if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def try_generate_M(I,J,fraction_unknown,attempts): for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown)) ########## if __name__ == "__main__": output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) # Store all matrices in text files numpy.savetxt(open(output_folder+"U.txt",'w'),U) numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()
ThomasBrouwer/BNMTF
data_toy/bnmf/generate_bnmf.py
Python
apache-2.0
3,430
/* Copyright IBM Corp. 2016 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 deliver import ( "fmt" "io" "testing" "time" mockpolicies "github.com/hyperledger/fabric/common/mocks/policies" "github.com/hyperledger/fabric/common/policies" "github.com/hyperledger/fabric/common/tools/configtxgen/provisional" "github.com/hyperledger/fabric/orderer/common/ledger" ramledger "github.com/hyperledger/fabric/orderer/common/ledger/ram" cb "github.com/hyperledger/fabric/protos/common" ab "github.com/hyperledger/fabric/protos/orderer" "github.com/hyperledger/fabric/protos/utils" logging "github.com/op/go-logging" "github.com/stretchr/testify/assert" "google.golang.org/grpc" ) var genesisBlock = cb.NewBlock(0, nil) var systemChainID = "systemChain" const ledgerSize = 10 func init() { logging.SetLevel(logging.DEBUG, "") } type mockD struct { grpc.ServerStream recvChan chan *cb.Envelope sendChan chan *ab.DeliverResponse } func newMockD() *mockD { return &mockD{ recvChan: make(chan *cb.Envelope), sendChan: make(chan *ab.DeliverResponse), } } func (m *mockD) Send(br *ab.DeliverResponse) error { m.sendChan <- br return nil } func (m *mockD) Recv() (*cb.Envelope, error) { msg, ok := <-m.recvChan if !ok { return msg, io.EOF } return msg, nil } type erroneousRecvMockD struct { grpc.ServerStream } func (m *erroneousRecvMockD) Send(br *ab.DeliverResponse) error { return nil } func (m *erroneousRecvMockD) Recv() (*cb.Envelope, error) { // The point here is to simulate an error other than EOF. // We don't bother to create a new custom error type. return nil, io.ErrUnexpectedEOF } type erroneousSendMockD struct { grpc.ServerStream recvVal *cb.Envelope } func (m *erroneousSendMockD) Send(br *ab.DeliverResponse) error { // The point here is to simulate an error other than EOF. // We don't bother to create a new custom error type. return io.ErrUnexpectedEOF } func (m *erroneousSendMockD) Recv() (*cb.Envelope, error) { return m.recvVal, nil } type mockSupportManager struct { chains map[string]*mockSupport } func (mm *mockSupportManager) GetChain(chainID string) (Support, bool) { cs, ok := mm.chains[chainID] return cs, ok } type mockSupport struct { ledger ledger.ReadWriter policyManager *mockpolicies.Manager erroredChan chan struct{} configSeq uint64 } func (mcs *mockSupport) Errored() <-chan struct{} { return mcs.erroredChan } func (mcs *mockSupport) Sequence() uint64 { return mcs.configSeq } func (mcs *mockSupport) PolicyManager() policies.Manager { return mcs.policyManager } func (mcs *mockSupport) Reader() ledger.Reader { return mcs.ledger } func NewRAMLedger() ledger.ReadWriter { rlf := ramledger.New(ledgerSize + 1) rl, _ := rlf.GetOrCreate(provisional.TestChainID) rl.Append(genesisBlock) return rl } func initializeDeliverHandler() Handler { mm := newMockMultichainManager() for i := 1; i < ledgerSize; i++ { l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } return NewHandlerImpl(mm) } func newMockMultichainManager() *mockSupportManager { rl := NewRAMLedger() mm := &mockSupportManager{ chains: make(map[string]*mockSupport), } mm.chains[systemChainID] = &mockSupport{ ledger: rl, policyManager: &mockpolicies.Manager{Policy: &mockpolicies.Policy{}}, erroredChan: make(chan struct{}), } return mm } var seekOldest = &ab.SeekPosition{Type: &ab.SeekPosition_Oldest{Oldest: &ab.SeekOldest{}}} var seekNewest = &ab.SeekPosition{Type: &ab.SeekPosition_Newest{Newest: &ab.SeekNewest{}}} func seekSpecified(number uint64) *ab.SeekPosition { return &ab.SeekPosition{Type: &ab.SeekPosition_Specified{Specified: &ab.SeekSpecified{Number: number}}} } func makeSeek(chainID string, seekInfo *ab.SeekInfo) *cb.Envelope { return &cb.Envelope{ Payload: utils.MarshalOrPanic(&cb.Payload{ Header: &cb.Header{ ChannelHeader: utils.MarshalOrPanic(&cb.ChannelHeader{ ChannelId: chainID, }), SignatureHeader: utils.MarshalOrPanic(&cb.SignatureHeader{}), }, Data: utils.MarshalOrPanic(seekInfo), }), } } func TestWholeChainSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekOldest, Stop: seekNewest, Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) count := uint64(0) for { select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { if deliverReply.GetStatus() != cb.Status_SUCCESS { t.Fatalf("Received an error on the reply channel") } if count != ledgerSize { t.Fatalf("Expected %d blocks but got %d", ledgerSize, count) } return } if deliverReply.GetBlock().Header.Number != count { t.Fatalf("Expected block %d but got block %d", count, deliverReply.GetBlock().Header.Number) } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } count++ } } func TestNewestSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekNewest, Stop: seekNewest, Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { t.Fatalf("Received an error on the reply channel") } if deliverReply.GetBlock().Header.Number != uint64(ledgerSize-1) { t.Fatalf("Expected only the most recent block") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestSpecificSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) specifiedStart := uint64(3) specifiedStop := uint64(7) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(specifiedStart), Stop: seekSpecified(specifiedStop), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) count := uint64(0) for { select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { if deliverReply.GetStatus() != cb.Status_SUCCESS { t.Fatalf("Received an error on the reply channel") } return } if expected := specifiedStart + count; deliverReply.GetBlock().Header.Number != expected { t.Fatalf("Expected block %d but got block %d", expected, deliverReply.GetBlock().Header.Number) } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } count++ } } func TestUnauthorizedSeek(t *testing.T) { mm := newMockMultichainManager() for i := 1; i < ledgerSize; i++ { l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } mm.chains[systemChainID].policyManager.Policy.Err = fmt.Errorf("Fail to evaluate policy") m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(0)), Stop: seekSpecified(uint64(0)), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetStatus() != cb.Status_FORBIDDEN { t.Fatalf("Received wrong error on the reply channel") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestRevokedAuthorizationSeek(t *testing.T) { mm := newMockMultichainManager() for i := 1; i < ledgerSize; i++ { l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(ledgerSize - 1)), Stop: seekSpecified(ledgerSize), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: assert.NotNil(t, deliverReply.GetBlock(), "First should succeed") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } mm.chains[systemChainID].policyManager.Policy.Err = fmt.Errorf("Fail to evaluate policy") mm.chains[systemChainID].configSeq++ l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", ledgerSize+1))}})) select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_FORBIDDEN, deliverReply.GetStatus(), "Second should been forbidden ") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestOutOfBoundSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(3 * ledgerSize)), Stop: seekSpecified(uint64(3 * ledgerSize)), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetStatus() != cb.Status_NOT_FOUND { t.Fatalf("Received wrong error on the reply channel") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestFailFastSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(ledgerSize - 1)), Stop: seekSpecified(ledgerSize), Behavior: ab.SeekInfo_FAIL_IF_NOT_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { t.Fatalf("Expected to receive first block") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } select { case deliverReply := <-m.sendChan: if deliverReply.GetStatus() != cb.Status_NOT_FOUND { t.Fatalf("Expected to receive failure for second block") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestBlockingSeek(t *testing.T) { mm := newMockMultichainManager() for i := 1; i < ledgerSize; i++ { l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(ledgerSize - 1)), Stop: seekSpecified(ledgerSize), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { t.Fatalf("Expected to receive first block") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get first block") } select { case <-m.sendChan: t.Fatalf("Should not have delivered an error or second block") case <-time.After(50 * time.Millisecond): } l := mm.chains[systemChainID].ledger l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", ledgerSize+1))}})) select { case deliverReply := <-m.sendChan: if deliverReply.GetBlock() == nil { t.Fatalf("Expected to receive new block") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get new block") } select { case deliverReply := <-m.sendChan: if deliverReply.GetStatus() != cb.Status_SUCCESS { t.Fatalf("Expected delivery to complete") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestErroredSeek(t *testing.T) { mm := newMockMultichainManager() ms := mm.chains[systemChainID] l := ms.ledger close(ms.erroredChan) for i := 1; i < ledgerSize; i++ { l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(ledgerSize - 1)), Stop: seekSpecified(ledgerSize), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_SERVICE_UNAVAILABLE, deliverReply.GetStatus(), "Mock support errored") case <-time.After(time.Second): t.Fatalf("Timed out waiting for error response") } } func TestErroredBlockingSeek(t *testing.T) { mm := newMockMultichainManager() ms := mm.chains[systemChainID] l := ms.ledger for i := 1; i < ledgerSize; i++ { l.Append(ledger.CreateNextBlock(l, []*cb.Envelope{&cb.Envelope{Payload: []byte(fmt.Sprintf("%d", i))}})) } m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(uint64(ledgerSize - 1)), Stop: seekSpecified(ledgerSize), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: assert.NotNil(t, deliverReply.GetBlock(), "Expected first block") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get first block") } close(ms.erroredChan) select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_SERVICE_UNAVAILABLE, deliverReply.GetStatus(), "Mock support errored") case <-time.After(time.Second): t.Fatalf("Timed out waiting for error response") } } func TestSGracefulShutdown(t *testing.T) { m := newMockD() ds := NewHandlerImpl(nil) close(m.recvChan) assert.NoError(t, ds.Handle(m), "Expected no error for hangup") } func TestReversedSeqSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) specifiedStart := uint64(7) specifiedStop := uint64(3) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekSpecified(specifiedStart), Stop: seekSpecified(specifiedStop), Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: if deliverReply.GetStatus() != cb.Status_BAD_REQUEST { t.Fatalf("Received wrong error on the reply channel") } case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestBadStreamRecv(t *testing.T) { bh := NewHandlerImpl(nil) assert.Error(t, bh.Handle(&erroneousRecvMockD{}), "Should catch unexpected stream error") } func TestBadStreamSend(t *testing.T) { m := &erroneousSendMockD{recvVal: makeSeek(systemChainID, &ab.SeekInfo{Start: seekNewest, Stop: seekNewest, Behavior: ab.SeekInfo_BLOCK_UNTIL_READY})} ds := initializeDeliverHandler() assert.Error(t, ds.Handle(m), "Should catch unexpected stream error") } func TestOldestSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekOldest, Stop: seekOldest, Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: assert.NotEqual(t, nil, deliverReply.GetBlock(), "Received an error on the reply channel") assert.Equal(t, uint64(0), deliverReply.GetBlock().Header.Number, "Expected only the most recent block") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestNoPayloadSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- &cb.Envelope{Payload: []byte("Foo")} select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_BAD_REQUEST, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestNilPayloadHeaderSeek(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- &cb.Envelope{Payload: utils.MarshalOrPanic(&cb.Payload{})} select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_BAD_REQUEST, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestBadChannelHeader(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- &cb.Envelope{Payload: utils.MarshalOrPanic(&cb.Payload{ Header: &cb.Header{ChannelHeader: []byte("Foo")}, })} select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_BAD_REQUEST, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestChainNotFound(t *testing.T) { mm := &mockSupportManager{ chains: make(map[string]*mockSupport), } m := newMockD() defer close(m.recvChan) ds := NewHandlerImpl(mm) go ds.Handle(m) m.recvChan <- makeSeek(systemChainID, &ab.SeekInfo{Start: seekNewest, Stop: seekNewest, Behavior: ab.SeekInfo_BLOCK_UNTIL_READY}) select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_NOT_FOUND, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestBadSeekInfoPayload(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- &cb.Envelope{ Payload: utils.MarshalOrPanic(&cb.Payload{ Header: &cb.Header{ ChannelHeader: utils.MarshalOrPanic(&cb.ChannelHeader{ ChannelId: systemChainID, }), SignatureHeader: utils.MarshalOrPanic(&cb.SignatureHeader{}), }, Data: []byte("Foo"), }), } select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_BAD_REQUEST, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } } func TestMissingSeekPosition(t *testing.T) { m := newMockD() defer close(m.recvChan) ds := initializeDeliverHandler() go ds.Handle(m) m.recvChan <- &cb.Envelope{ Payload: utils.MarshalOrPanic(&cb.Payload{ Header: &cb.Header{ ChannelHeader: utils.MarshalOrPanic(&cb.ChannelHeader{ ChannelId: systemChainID, }), SignatureHeader: utils.MarshalOrPanic(&cb.SignatureHeader{}), }, Data: nil, }), } select { case deliverReply := <-m.sendChan: assert.Equal(t, cb.Status_BAD_REQUEST, deliverReply.GetStatus(), "Received wrong error on the reply channel") case <-time.After(time.Second): t.Fatalf("Timed out waiting to get all blocks") } }
blockc/fabric
orderer/common/deliver/deliver_test.go
GO
apache-2.0
19,021
using Artemis.System; using IHateRectangles.Screens; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace IHateRectangles { public class MenuScreen : Screen { private SpriteBatch _spriteBatch; private SpriteFont _menuFont; private ContentManager _contentManager; public event ScreenFinished OnScreenFinished; public void Initialize() { _contentManager = EntitySystem.BlackBoard.GetEntry<ContentManager>("ContentManager"); _menuFont = _contentManager.Load<SpriteFont>(@"Fonts\Hud"); _spriteBatch = EntitySystem.BlackBoard.GetEntry<SpriteBatch>("SpriteBatch"); } public void Update() { if (Keyboard.GetState().GetPressedKeys().Length > 0) if (OnScreenFinished != null) OnScreenFinished(new GameScreen()); } public void Draw() { var viewport = EntitySystem.BlackBoard.GetEntry<GraphicsDevice>("GraphicsDevice").Viewport; _spriteBatch.Begin(); _spriteBatch.DrawString(_menuFont, "I Hate Rectangles", new Vector2(viewport.Width / 2 - 100, viewport.Height / 2 - 200), Color.White); _spriteBatch.DrawString(_menuFont, "Press any key to continue.", new Vector2(viewport.Width / 2 - 138, viewport.Height / 2 - 100), Color.White); _spriteBatch.End(); } public void Destroy() { } } }
SoulBeaver/i-hate-rectangles
IHateRectangles/IHateRectangles/Screens/MenuScreen.cs
C#
apache-2.0
1,784
package org.easyaccess.nist; import java.io.File; import java.util.HashMap; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.speech.tts.TextToSpeech.OnInitListener; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.Toast; public class HomeScreenActivity extends Activity implements OnInitListener { private static final String TAG = "HomeScreenActivity"; boolean isButtonPressed = false; int gFocusPosition = 1; int gMaxFocusableItem = 2; Context gContext = null; String gTTsOnStart = null; SpeakManager gTTS = null; Button gBtnScan = null, gBtnSkipScan = null; View rootView = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_ballotstart); gContext = this; rootView = findViewById(R.id.alrt_root_view); gBtnScan = (Button) findViewById(R.id.btn_scan); gBtnSkipScan = (Button) findViewById(R.id.btn_skip_scan); gBtnScan.setBackgroundColor(getResources().getColor(R.color.bg_button)); gBtnScan.setTextColor(getResources().getColor(android.R.color.white)); gBtnSkipScan.setBackgroundColor(getResources().getColor(R.color.bg_button)); gBtnSkipScan.setTextColor(getResources().getColor(android.R.color.white)); gBtnScan.isInTouchMode(); File directory = new File(Constants.NIST_VOTING_PROTOTYPE_DIRECTORY); if (!directory.exists()) { directory.mkdir(); } File sampleFile = new File(directory, Constants.NIST_VOTING_PROTOTYPE_FILE_SP); if (!sampleFile.exists()) { StringBuilder builder = Utils.readFile(gContext, this.getResources().openRawResource(R.raw.election_info_sp)); Utils.writeToFile(builder.toString(), directory + File.separator + Constants.NIST_VOTING_PROTOTYPE_FILE_SP, false); } sampleFile = new File(directory, Constants.NIST_VOTING_PROTOTYPE_FILE_EN); if (!sampleFile.exists()) { StringBuilder builder = Utils.readFile(gContext, this.getResources().openRawResource(R.raw.election_info_en)); Utils.writeToFile(builder.toString(), directory + File.separator + Constants.NIST_VOTING_PROTOTYPE_FILE_EN, false); } } private OnClickListener sOnClickListener = new OnClickListener() { Intent intent = null; @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_scan: launchScan(); break; case R.id.btn_skip_scan: skipScan(); break; case R.id.alrt_root_view: speakWord("", null, false); break; } } private void skipScan() { resetPreferences(); intent = new Intent(gContext, ContestActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } private void launchScan() { resetPreferences(); intent = new Intent(gContext, ScannerActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } }; private void resetPreferences() { Constants.SETTING_LANGUAGE = Constants.DEFAULT_LANG_SETTING; Constants.SETTING_TOUCH_PRESENT = Constants.DEFAULT_TOUCH_PRESENT_SETTING; Constants.SETTING_FONT_SIZE = Constants.FONT_SIZE_STD; Constants.SETTING_REVERSE_SCREEN = Constants.DEFAULT_REVERSE_SCREEN_SETTING; Constants.SETTING_TTS_VOICE = Constants.DEFAULT_TTS_VOICE; Constants.SETTING_TTS_SPEED = Constants.TTS_SPEED_STD; Constants.SETTING_SCAN_MODE = Constants.DEFAULT_SCAN_MODE_SETTING; Constants.SETTING_SCAN_MODE_SPEED = Constants.DEFAULT_SCAN_SPEED_SETTING; SharedPreferences preferences = getSharedPreferences( Constants.PREFERENCE_NAME, Context.MODE_PRIVATE); Editor editor = preferences.edit(); editor.clear(); editor.commit(); } private OnTouchListener gOnTouchListener = new OnTouchListener() { /** * on touch down announce the info if it represent text. on touch up * perform the action */ @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition = 0; switch (v.getId()) { case R.id.btn_scan: v.setBackground(getResources().getDrawable( R.drawable.focused)); if (HeadsetListener.isHeadsetConnected) { speakWord(gBtnScan.getText().toString(), null, true); } break; case R.id.btn_skip_scan: v.setBackground(getResources().getDrawable( R.drawable.focused)); if (HeadsetListener.isHeadsetConnected) { speakWord(gBtnSkipScan.getText().toString(), null, true); } break; } } else if (event.getAction() == MotionEvent.ACTION_UP) { switch (v.getId()) { case R.id.btn_scan: v.setBackground(null); // v.performClick(); break; case R.id.btn_skip_scan: v.setBackground(null); // v.performClick(); break; } } return false; } }; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (!isButtonPressed) { int keyPressed = -1; if (keyCode == KeyEvent.KEYCODE_UNKNOWN) { keyPressed = event.getScanCode(); } else { keyPressed = keyCode; } switch (keyPressed) { case KeyEvent.KEYCODE_TAB: if(event.isShiftPressed()){ navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition--; if (gFocusPosition <= 0) { gFocusPosition = gMaxFocusableItem; } navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM); }else{ navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition++; if (gFocusPosition > gMaxFocusableItem) { gFocusPosition = 1; } navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM); } break; case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_BUTTON_1: navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition--; if (gFocusPosition <= 0) { gFocusPosition = gMaxFocusableItem; } navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM); break; case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_BUTTON_2: navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition++; if (gFocusPosition > gMaxFocusableItem) { gFocusPosition = 1; } navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM); break; case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_BUTTON_3: selectCurrentFocusItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); break; } } isButtonPressed = true; return true; } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { isButtonPressed = false; int keyPressed = -1; if (keyCode == KeyEvent.KEYCODE_UNKNOWN) { keyPressed = event.getScanCode(); } else { keyPressed = keyCode; } switch (keyPressed) { case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_BUTTON_3: // selectCurrentFocusItem(gFocusPosition, // Constants.JUMP_FROM_CURRENT_ITEM); break; } return true; } public void selectCurrentFocusItem(int focusPosition, int pressed_released) { switch (pressed_released) { case Constants.REACH_NEW_ITEM: break; case Constants.JUMP_FROM_CURRENT_ITEM: if (gFocusPosition == 1) { gBtnScan.performClick(); } else if (gFocusPosition == 2) { gBtnSkipScan.performClick(); } break; } } public void navigateToOtherItem(int focusPosition, int reach_jump) { View view = getCurrentFocus(); Log.d(TAG, " from navigation method focus position = " + focusPosition + ", current focus = " + view ); // + ", next focus down id = " // + view.getNextFocusDownId() // + ", next focus forward id = " + view.getNextFocusForwardId() // + ", next focus left id = " + view.getNextFocusLeftId() // + ", next focus right id = " + view.getNextFocusRightId() // + ", next focus up id = " + view.getNextFocusUpId()); switch (reach_jump) { case Constants.JUMP_FROM_CURRENT_ITEM: if (focusPosition == 1) { // gBtnScan.setBackground(null); } else if (focusPosition == 2) { // gBtnSkipScan.setBackground(null); } break; case Constants.REACH_NEW_ITEM: if (focusPosition == 1) { gBtnScan.setFocusableInTouchMode(true);// for handling the ez-keypad focus gBtnSkipScan.setFocusableInTouchMode(false);// for handling the ez-keypad focus gBtnScan.requestFocus();// for handling the focus when come out of touch mode // gBtnScan.setBackground(getResources().getDrawable( // R.drawable.focused)); if (HeadsetListener.isHeadsetConnected) { speakWord(gBtnScan.getText().toString() + Constants.COMMA_SPACE + getString(R.string.button), null, true); } } else if (focusPosition == 2) { gBtnScan.setFocusableInTouchMode(false);// for handling the ez-keypad focus gBtnSkipScan.setFocusableInTouchMode(true);// for handling the ez-keypad focus gBtnSkipScan.requestFocus();// for handling the focus when come out of touch mode // gBtnSkipScan.setBackground(getResources().getDrawable( // R.drawable.focused)); if (HeadsetListener.isHeadsetConnected) { speakWord(gBtnSkipScan.getText().toString() + Constants.COMMA_SPACE + getString(R.string.button), null, true); } } break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.d(TAG,"resultCode = " + resultCode); if (requestCode == Constants.TTS_DATA_CHECK_CODE) { if (resultCode == SpeakManager.Engine.CHECK_VOICE_DATA_PASS) { Log.d(TAG,"Setting speak manager"); if (Constants.SETTING_TTS_VOICE == Constants.DEFAULT_TTS_VOICE) { gTTS = new SpeakManager(gContext, this, "com.svox.classic"); } else { gTTS = new SpeakManager(gContext, this, "com.ivona.tts"); } } else { Log.d(TAG,"launching intent for installing tts"); Intent ttsInstallIntent = new Intent(); ttsInstallIntent .setAction(SpeakManager.Engine.ACTION_INSTALL_TTS_DATA); startActivity(ttsInstallIntent); } } } @Override public void onInit(int status) { if (status == SpeakManager.SUCCESS) { if (Constants.SETTING_LANGUAGE == Constants.DEFAULT_LANG_SETTING) { gTTS.setLanguage(Locale.US); } else { gTTS.setLanguage(new Locale("spa", "ESP")); } gTTS.setSpeechRate(Constants.SETTING_TTS_SPEED); speakWord(gTTsOnStart, null, true); } else if (status == SpeakManager.ERROR) { Toast.makeText(gContext, getString(R.string.failed), Toast.LENGTH_SHORT).show(); } } public void speakWord(String word, HashMap<String, String> utteranceId, boolean shouldRepeat) { if (gTTS != null) { gTTS.speak(word, SpeakManager.QUEUE_FLUSH, utteranceId, shouldRepeat); } } @Override protected void onStop() { super.onStop(); if (gTTS != null) { gTTS.stop(); gTTS.shutdown(); } } @Override protected void onStart() { super.onStart(); Intent checkTTSIntent = new Intent(); checkTTSIntent.setAction(SpeakManager.Engine.ACTION_CHECK_TTS_DATA); startActivityForResult(checkTTSIntent, Constants.TTS_DATA_CHECK_CODE); gBtnScan.setText(R.string.scan_barcode); gBtnSkipScan.setText(R.string.skip_barcode); gBtnScan.setTextSize(Constants.SETTING_FONT_SIZE); gBtnSkipScan.setTextSize(Constants.SETTING_FONT_SIZE); gBtnScan.setOnClickListener(sOnClickListener); // gBtnScan.setOnTouchListener(gOnTouchListener); gBtnSkipScan.setOnClickListener(sOnClickListener); // gBtnSkipScan.setOnTouchListener(gOnTouchListener); rootView.setOnClickListener(sOnClickListener); gBtnSkipScan.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus){ // gBtnSkipScan.setFocusableInTouchMode(true); }else{ // gBtnSkipScan.setFocusableInTouchMode(false); } } }); gBtnScan.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus){ // gBtnScan.setFocusableInTouchMode(true); }else{ // gBtnScan.setFocusableInTouchMode(false); } } }); gTTsOnStart = getString(R.string.scan_barcode) + Constants.COMMA_SPACE + getString(R.string.button); // View view = getCurrentFocus(); // Log.d(TAG, "current focus = " + view // + ", next focus down id = " // + view.getNextFocusDownId() // + ", next focus forward id = " + view.getNextFocusForwardId() // + ", next focus left id = " + view.getNextFocusLeftId() // + ", next focus right id = " + view.getNextFocusRightId() // + ", next focus up id = " + view.getNextFocusUpId()); // gBtnScan.setBackgroundResource(R.drawable.focused); gBtnScan.setFocusableInTouchMode(true);// for showing focus initially gBtnScan.requestFocus(); // view = getCurrentFocus(); // Log.d(TAG, "current focus = " + view // + ", next focus down id = " // + view.getNextFocusDownId() // + ", next focus forward id = " + view.getNextFocusForwardId() // + ", next focus left id = " + view.getNextFocusLeftId() // + ", next focus right id = " + view.getNextFocusRightId() // + ", next focus up id = " + view.getNextFocusUpId()); } }
saurabh2590/NIST-Voting-Tablet
src/org/easyaccess/nist/HomeScreenActivity.java
Java
apache-2.0
13,985
// // ÀÌ ÆÄÀÏÀº JAXB(JavaTM Architecture for XML Binding) ÂüÁ¶ ±¸Çö 2.2.8-b130911.1802 ¹öÀüÀ» ÅëÇØ »ý¼ºµÇ¾ú½À´Ï´Ù. // <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>¸¦ ÂüÁ¶ÇϽʽÿÀ. // ÀÌ ÆÄÀÏÀ» ¼öÁ¤ÇÏ¸é ¼Ò½º ½ºÅ°¸¶¸¦ ÀçÄÄÆÄÀÏÇÒ ¶§ ¼öÁ¤ »çÇ×ÀÌ ¼Õ½ÇµË´Ï´Ù. // »ý¼º ³¯Â¥: 2015.07.30 ½Ã°£ 02:38:18 PM KST // package org.gs1.source.tsd; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>TSD_AttributeValuePairListType complex type¿¡ ´ëÇÑ Java Ŭ·¡½ºÀÔ´Ï´Ù. * * <p>´ÙÀ½ ½ºÅ°¸¶ ´ÜÆíÀÌ ÀÌ Å¬·¡½º¿¡ Æ÷ÇԵǴ ÇÊ¿äÇÑ ÄÜÅÙÃ÷¸¦ ÁöÁ¤ÇÕ´Ï´Ù. * * <pre> * &lt;complexType name="TSD_AttributeValuePairListType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="stringAVP" type="{urn:gs1:tsd:tsd_common:xsd:1}TSD_StringAttributeValuePairType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TSD_AttributeValuePairListType", namespace = "urn:gs1:tsd:tsd_common:xsd:1", propOrder = { "stringAVP" }) public class TSDAttributeValuePairListType { @XmlElement(required = true) protected List<TSDStringAttributeValuePairType> stringAVP; /** * Gets the value of the stringAVP property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the stringAVP property. * * <p> * For example, to add a new item, do as follows: * <pre> * getStringAVP().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TSDStringAttributeValuePairType } * * */ public List<TSDStringAttributeValuePairType> getStringAVP() { if (stringAVP == null) { stringAVP = new ArrayList<TSDStringAttributeValuePairType>(); } return this.stringAVP; } }
gs1oliot/gs1source
DataAggregator/src/main/java/org/gs1/source/tsd/TSDAttributeValuePairListType.java
Java
apache-2.0
2,392
/** * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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 jp.co.yahoo.dataplatform.mds.hadoop.hive.io.vector; import java.io.IOException; import org.apache.hadoop.hive.ql.exec.vector.DoubleColumnVector; import jp.co.yahoo.dataplatform.schema.objects.PrimitiveObject; public interface IDecimalPrimitiveSetter{ void set( final PrimitiveObject[] primitiveObjectArray , final DoubleColumnVector columnVector , final int index ) throws IOException; }
yahoojapan/multiple-dimension-spread
src/hive/src/main/java/jp/co/yahoo/dataplatform/mds/hadoop/hive/io/vector/IDecimalPrimitiveSetter.java
Java
apache-2.0
1,217
using System; namespace Benchy.Framework { /// <summary> /// Represents a breakdown of TimeSpan values. /// </summary> public interface IDataBreakout { /// <summary> /// The minimum value of the breakout. /// </summary> TimeSpan RangeMinValue { get; set; } /// <summary> /// The maximum value of the breakout. /// </summary> TimeSpan RangeMaxValue { get; set; } /// <summary> /// The number of items that fit between that breakout. /// </summary> int Occurences { get; set; } /// <summary> /// Represents a way to render it textually. /// </summary> /// <returns>A string representing the Breakout.</returns> string GetText(); } }
cmbrown1598/Benchy
Benchy/IDataBreakout.cs
C#
apache-2.0
818
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.fileTypes.impl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.ExtensionFileNameMatcher; import com.intellij.openapi.fileTypes.FileNameMatcher; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.util.InvalidDataException; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; final class RemovedMappingTracker { private static final Logger LOG = Logger.getInstance(RemovedMappingTracker.class); static final class RemovedMapping { private final FileNameMatcher myFileNameMatcher; private final String myFileTypeName; private final boolean myApproved; private RemovedMapping(@NotNull FileNameMatcher matcher, @NotNull String fileTypeName, boolean approved) { myFileNameMatcher = matcher; myFileTypeName = fileTypeName; myApproved = approved; } @NotNull FileNameMatcher getFileNameMatcher() { return myFileNameMatcher; } @NotNull String getFileTypeName() { return myFileTypeName; } boolean isApproved() { return myApproved; } @Override public String toString() { return "Removed mapping '" + myFileNameMatcher + "' -> " + myFileTypeName; } // must not look at myApproved @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RemovedMapping mapping = (RemovedMapping)o; if (!myFileNameMatcher.equals(mapping.myFileNameMatcher)) return false; return myFileTypeName.equals(mapping.myFileTypeName); } @Override public int hashCode() { int result = myFileNameMatcher.hashCode(); result = 31 * result + myFileTypeName.hashCode(); return result; } } private final MultiMap<FileNameMatcher, RemovedMapping> myRemovedMappings = new MultiMap<>(); @NonNls private static final String ELEMENT_REMOVED_MAPPING = "removed_mapping"; /** Applied for removed mappings approved by user */ @NonNls private static final String ATTRIBUTE_APPROVED = "approved"; @NonNls private static final String ATTRIBUTE_TYPE = "type"; void clear() { myRemovedMappings.clear(); } @NotNull RemovedMapping add(@NotNull FileNameMatcher matcher, @NotNull String fileTypeName, boolean approved) { RemovedMapping mapping = new RemovedMapping(matcher, fileTypeName, approved); List<RemovedMapping> mappings = (List<RemovedMapping>)myRemovedMappings.getModifiable(matcher); boolean found = false; for (int i = 0; i < mappings.size(); i++) { RemovedMapping removedMapping = mappings.get(i); if (removedMapping.getFileTypeName().equals(fileTypeName)) { mappings.set(i, mapping); found = true; break; } } if (!found) { mappings.add(mapping); } return mapping; } void load(@NotNull Element e) { myRemovedMappings.clear(); List<RemovedMapping> removedMappings = readRemovedMappings(e); Set<RemovedMapping> uniques = new LinkedHashSet<>(removedMappings.size()); for (RemovedMapping mapping : removedMappings) { if (!uniques.add(mapping)) { LOG.warn(new InvalidDataException("Duplicate <removed_mapping> tag for " + mapping)); } } for (RemovedMapping mapping : uniques) { myRemovedMappings.putValue(mapping.myFileNameMatcher, mapping); } } @NotNull static List<RemovedMapping> readRemovedMappings(@NotNull Element e) { List<Element> children = e.getChildren(ELEMENT_REMOVED_MAPPING); if (children.isEmpty()) { return Collections.emptyList(); } List<RemovedMapping> result = new ArrayList<>(); for (Element mapping : children) { String ext = mapping.getAttributeValue(AbstractFileType.ATTRIBUTE_EXT); FileNameMatcher matcher = ext == null ? FileTypeManager.parseFromString(mapping.getAttributeValue(AbstractFileType.ATTRIBUTE_PATTERN)) : new ExtensionFileNameMatcher(ext); boolean approved = Boolean.parseBoolean(mapping.getAttributeValue(ATTRIBUTE_APPROVED)); String fileTypeName = mapping.getAttributeValue(ATTRIBUTE_TYPE); if (fileTypeName == null) continue; RemovedMapping removedMapping = new RemovedMapping(matcher, fileTypeName, approved); result.add(removedMapping); } return result; } void save(@NotNull Element element) { List<RemovedMapping> removedMappings = new ArrayList<>(myRemovedMappings.values()); removedMappings.sort(Comparator.comparing((RemovedMapping mapping) -> mapping.getFileNameMatcher().getPresentableString()).thenComparing(RemovedMapping::getFileTypeName)); for (RemovedMapping mapping : removedMappings) { Element content = writeRemovedMapping(mapping.myFileTypeName, mapping.myFileNameMatcher, true, mapping.myApproved); if (content != null) { element.addContent(content); } } } void saveRemovedMappingsForFileType(@NotNull Element map, @NotNull String fileTypeName, @NotNull Collection<? extends FileNameMatcher> associations, boolean specifyTypeName) { for (FileNameMatcher matcher : associations) { Element content = writeRemovedMapping(fileTypeName, matcher, specifyTypeName, isApproved(matcher, fileTypeName)); if (content != null) { map.addContent(content); } } } boolean hasRemovedMapping(@NotNull FileNameMatcher matcher) { return myRemovedMappings.containsKey(matcher); } private boolean isApproved(@NotNull FileNameMatcher matcher, @NotNull String fileTypeName) { RemovedMapping mapping = ContainerUtil.find(myRemovedMappings.get(matcher), m -> m.getFileTypeName().equals(fileTypeName)); return mapping != null && mapping.isApproved(); } @NotNull List<RemovedMapping> getRemovedMappings() { return new ArrayList<>(myRemovedMappings.values()); } @NotNull List<FileNameMatcher> getMappingsForFileType(@NotNull String fileTypeName) { return myRemovedMappings.values().stream() .filter(mapping -> mapping.myFileTypeName.equals(fileTypeName)) .map(mapping -> mapping.myFileNameMatcher) .collect(Collectors.toList()); } @NotNull List<RemovedMapping> removeIf(@NotNull Predicate<? super RemovedMapping> predicate) { List<RemovedMapping> result = new ArrayList<>(); for (Iterator<Map.Entry<FileNameMatcher, Collection<RemovedMapping>>> iterator = myRemovedMappings.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<FileNameMatcher, Collection<RemovedMapping>> entry = iterator.next(); Collection<RemovedMapping> mappings = entry.getValue(); mappings.removeIf(mapping -> { boolean toRemove = predicate.test(mapping); if (toRemove) { result.add(mapping); } return toRemove; }); if (mappings.isEmpty()) { iterator.remove(); } } return result; } void approveUnapprovedMappings() { for (RemovedMapping mapping : new ArrayList<>(myRemovedMappings.values())) { if (!mapping.isApproved()) { myRemovedMappings.remove(mapping.getFileNameMatcher(), mapping); myRemovedMappings.putValue(mapping.getFileNameMatcher(), new RemovedMapping(mapping.getFileNameMatcher(), mapping.getFileTypeName(), true)); } } } private static Element writeRemovedMapping(@NotNull String fileTypeName, @NotNull FileNameMatcher matcher, boolean specifyTypeName, boolean approved) { Element mapping = new Element(ELEMENT_REMOVED_MAPPING); if (!AbstractFileType.writePattern(matcher, mapping)) { return null; } if (approved) { mapping.setAttribute(ATTRIBUTE_APPROVED, "true"); } if (specifyTypeName) { mapping.setAttribute(ATTRIBUTE_TYPE, fileTypeName); } return mapping; } }
mdaniel/intellij-community
platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/RemovedMappingTracker.java
Java
apache-2.0
8,518
# -*- coding: utf-8 -*- # Copyright 2014, 2015 Metaswitch Networks # # 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. """ felix.test.stub_utils ~~~~~~~~~~~~ Test utilities. """ import logging import random from collections import namedtuple CommandOutput = namedtuple('CommandOutput', ['stdout', 'stderr']) # Logger log = logging.getLogger(__name__) # The current time. test_time = 0 def set_time(value): global test_time test_time = value log.debug("Time now set to : %d" % test_time) def get_time(): return test_time def get_mac(): """ Gets a random mac address. """ mac = ("%02x:%02x:%02x:%02x:%02x:%02x" % (random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff))) return mac # Exception raised when tests reach the end. class TestOverException(Exception): pass
nbartos/calico
calico/felix/test/stub_utils.py
Python
apache-2.0
1,545
/******************************************************************************* * Copyright [2016] [Quirino Brizi (quirino.brizi@gmail.com)] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package org.actio.modeler.domain.repository; import java.util.List; import org.actio.commons.message.model.ModelMessage; /** * @author quirino.brizi * */ public interface ModelRepository { ModelMessage add(ModelMessage model); List<ModelMessage> getAllModels(); ModelMessage getModel(String modelKey); }
quirinobrizi/actio
webservices/modeler/src/main/java/org/actio/modeler/domain/repository/ModelRepository.java
Java
apache-2.0
1,108
/* * 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.flink.runtime.scheduler.declarative.allocator; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.jobmaster.SlotInfo; import org.apache.flink.runtime.taskmanager.LocalTaskManagerLocation; import org.apache.flink.runtime.taskmanager.TaskManagerLocation; /** Test {@link SlotInfo} implementation. */ class TestSlotInfo implements SlotInfo { private final AllocationID allocationId = new AllocationID(); @Override public AllocationID getAllocationId() { return allocationId; } @Override public TaskManagerLocation getTaskManagerLocation() { return new LocalTaskManagerLocation(); } @Override public int getPhysicalSlotNumber() { return 0; } @Override public ResourceProfile getResourceProfile() { return ResourceProfile.ANY; } @Override public boolean willBeOccupiedIndefinitely() { return false; } }
kl0u/flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/declarative/allocator/TestSlotInfo.java
Java
apache-2.0
1,853
<?php include("inc_header.php"); ?> <?php include("inc_lang_detect.php"); ?> <!-- Inner Page 4404 Error --> <div class="container"> <div class="inner-error"> <h3><strong>HTTP 404<strong></h3> <?php if (getDefaultLanguage() == "pt-br") { ?> <h3 >Objeto n&atilde;o encontrado!</h3> <p>A URL requisitada n&atilde;o foi encontrada neste servidor.</p> <p>Se o endere&ccedil;o (URL) foi digitado manualmente, pedimos a gentileza de verificar novamente a sintaxe do endere&ccedil;o.</p> <?php } else { ?> <h3 >Object not found!</h3> <p>The requested URL was not found on this server.</p> <p>If you entered the URL manually please check your spelling and try again.</p> <?php } ?> </div> </div> </div> <!-- Inner Page Content End --> <?php include("inc_footer.php"); ?>
soujava/cafe-brasil
404_HTTP_NOT_FOUND.php
PHP
apache-2.0
890
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package beans; import java.io.Serializable; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * * @author Chema */ @Component public class Persona implements Serializable { @Value("#{p.nombre}") private String nombre; @Value("#{p.apellido}") private String apellido; public Persona() { } public Persona(String nombre, String apellido) { this.nombre = nombre; this.apellido = apellido; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } }
xroca/planFormacionJava
spring/Web/AnotacionesWebMaven/src/main/java/beans/Persona.java
Java
apache-2.0
909
import { Component } from '@angular/core'; import {ROUTER_DIRECTIVES, RouteData} from '@angular/router-deprecated'; import {TravelFormComponent} from "./travel-form.component"; import {NavbarComponent} from '../../shared/index'; @Component({ selector: "home", templateUrl: 'app/home/components/home.component.html', styleUrls: ['app/home/components/home.component.css'], directives: [ROUTER_DIRECTIVES, TravelFormComponent, NavbarComponent] }) export class HomeComponent{ signInOnly: boolean; constructor(private _data: RouteData) { //when arriving directly from /login URL this.signInOnly = this._data.get('signInOnly') || true; // set default to false to re-activate the destination form } }
WALK-fr/kuzzle-walk
app/home/components/home.component.ts
TypeScript
apache-2.0
741
/* * 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 delsh.livy; /** * The enumeration types for session kind. */ public enum SessionKind { // Possible values are the following. SPARK("spark"), PYSPARK("pyspark"), SPARKR("sparkr"); private String kind; private SessionKind(String skind) { kind = skind; } public String toString() { return kind; } /** * This class finds enum value that is equivalent to a given string. * @param kind Session kind. * @return Enum value */ public static SessionKind getEnum(String str) { SessionKind[] array = SessionKind.values(); for(SessionKind enumStr : array) { if(str.equals(enumStr.kind.toString())) { return enumStr; } } return null; } }
kojish/hdinsight-spark-livy-client
src/main/java/delsh/livy/SessionKind.java
Java
apache-2.0
1,484
package com.openthinks.libs.utilities.lookup; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import com.openthinks.libs.utilities.Checker; import com.openthinks.libs.utilities.InstanceUtilities; import com.openthinks.libs.utilities.InstanceUtilities.InstanceWrapper; import com.openthinks.libs.utilities.exception.CheckerNoPassException; import com.openthinks.libs.utilities.pools.object.ObjectPool; /** * ClassName: LookupPool <br> * Function: It is used for store shared object instances and find other SPI<br> * Reason: follow the design pattern of fly weight to reduce instantiate new object. <br> * Notice: avoid store or find those object which include its own state and will be changed;<br> * Usage:<br> * * <pre> * <code> * //get gloabl instance of LookupPool * LookupPool lookupPool = LookupPools.gloabl(); * * //get a named instance of LookupPool * lookupPool = LookupPools.get("pool-1"); * * // instance by class directly * LookupInterfaceImpl instanceImpl1 = lookupPool.lookup(LookupInterfaceImpl.class); * * // instance by customized implementation class * LookupInterface instanceImpl2 = lookupPool.lookup(LookupInterface.class,InstanceWrapper.build(LookupInterfaceImpl.class)); * * // lookup shared object already existed * LookupInterface instanceImpl3 = lookupPool.lookup(LookupInterface.class); * assert instanceImpl2==instanceImpl3 ; * * // register a shared object by name * lookupPool.register("beanName1",instanceImpl1); * // lookup shared object by name * LookupInterface instanceImpl4 = lookupPool.lookup("beanName1"); * * assert instanceImpl1==instanceImpl4 ; * * // clear all shared objects and mappings * lookupPool.cleanUp(); * * </code> * </pre> * * date: Sep 8, 2017 3:15:29 PM <br> * * @author dailey.yet@outlook.com * @version 1.0 * @since JDK 1.8 */ public abstract class LookupPool { protected final ObjectPool objectPool; protected final ReadWriteLock lock; public abstract String name(); protected LookupPool() { objectPool = new ObjectPool(); lock = new ReentrantReadWriteLock(); } /** * lookup a object by its type, if not find firstly, try to instance by instanceType and * constructor parameters args * * @param <T> lookup object type * @param type Class lookup key type * @param args Object[] instance constructor parameters * @return T lookup object or null */ public <T> T lookup(Class<T> type, Object... args) { return lookup(type, null, args); } /** * lookup a object by its type, if not find firstly, try to instance by instanceType and * constructor parameters args * * @param <T> lookup object type * @param <E> lookup object type * @param searchType Class lookup key type * @param instancewrapper Class instance type when not lookup the key * @param args Object[] instance constructor parameters * @return T lookup object or null */ public <T, E extends T> T lookup(final Class<T> searchType, InstanceWrapper<E> instancewrapper, Object... args) { T object = null; lock.readLock().lock(); try { object = objectPool.get(searchType); } finally { lock.readLock().unlock(); } if (object == null) { lock.writeLock().lock(); try { object = InstanceUtilities.create(searchType, instancewrapper, args); register(searchType, object); } finally { lock.writeLock().unlock(); } } return object; } /** * look up object by its bean name * * @param <T> lookup object type * @param beanName String lookup object mapping name * @return T lookup object or null */ public <T> T lookup(String beanName) { lock.readLock().lock(); try { return objectPool.get(beanName); } finally { lock.readLock().unlock(); } } /** * lookup a optional object by its type, if not find firstly, try to instance by instanceType and * constructor parameters args * * @param <T> lookup object type * @param type Class lookup key type * @param args Object[] instance constructor parameters * @return Optional of lookup object */ public <T> Optional<T> lookupIf(Class<T> type, Object... args) { return Optional.ofNullable(lookup(type, args)); } /** * lookup a optional object by its type, if not find firstly, try to instance by instanceType and * constructor parameters args * * @param <T> lookup object type * @param <E> lookup object type * @param searchType Class lookup key type * @param instancewrapper Class instance type when not lookup the key * @param args Object[] instance constructor parameters * @return Optional of lookup object */ public <T, E extends T> Optional<T> lookupIf(final Class<T> searchType, InstanceWrapper<E> instancewrapper, Object... args) { return Optional.ofNullable(lookup(searchType, instancewrapper, args)); } /** * look up optional object by its bean name * * @param <T> lookup object type * @param beanName String lookup object mapping name * @return Optional of lookup object */ public <T> Optional<T> lookupIf(String beanName) { return Optional.ofNullable(lookup(beanName)); } /** * * lookupSPI:this will used {@link ServiceLoader} to load SPI which defined in folder * <B>META-INF/services</B>. <br> * It will first to try to load instance from cached {@link ObjectPool}, if not found, then try to * load SPI class and instantiate it.<br> * Notice: only load and instantiate first SPI class in defined file<br> * * @param <T> lookup SPI interface class * @param spiInterface SPI interface or abstract class type * @param args constructor arguments * @return implementation of parameter spiInterface */ public <T> T lookupSPI(Class<T> spiInterface, Object... args) { return lookupFocusSPI(spiInterface, null, args); } /** * * lookupFocusSPI:this will used {@link ServiceLoader} to load SPI which defined in folder * <B>META-INF/services</B>. <br> * It will first to try to load instance from cached {@link ObjectPool}, if not found, then try to * load SPI class and instantiate it.<br> * Notice: only load and instantiate focused SPI class in defined file<br> * * @param <T> lookup SPI interface class * @param spiInterface SPI interface or abstract class type * @param focusClassName focused SPI implementation class aname * @param args constructor arguments * @return implementation of parameter spiInterface * */ public <T> T lookupFocusSPI(Class<T> spiInterface, String focusClassName, Object... args) { T object = null; lock.readLock().lock(); try { object = objectPool.get(spiInterface); } finally { lock.readLock().unlock(); } if (object == null) { lock.writeLock().lock(); try { ServiceLoader<T> serviceLoader = ServiceLoader.load(spiInterface, focusClassName, args); object = serviceLoader.iterator().next(); Checker.require(object).notNull("Cannot found SPI implementation for " + spiInterface); register(spiInterface, object); } finally { lock.writeLock().unlock(); } } return object; } /** * * lookupSPISkipCache:this will used {@link ServiceLoader} to load SPI which defined in folder * <B>META-INF/services</B>. <br> * It will do load SPI skip cache each time, not try to lookup from cache firstly.<br> * Notice: only load and instantiate first SPI class in defined file<br> * * @param <T> lookup SPI interface class * @param spiInterface SPI interface or abstract class type * @param args constructor arguments * @return implementation of parameter spiInterface * @throws CheckerNoPassException when not found implementation SPI */ public <T> T lookupSPISkipCache(Class<T> spiInterface, Object... args) { return lookupFocusSPISkipCache(spiInterface, null, args); } /** * * lookupFocusSPISkipCache:this will used {@link ServiceLoader} to load SPI which defined in * folder <B>META-INF/services</B>. <br> * It will do load SPI skip cache each time, not try to lookup from cache firstly.<br> * Notice: only load and instantiate focused SPI class in defined file<br> * * @param <T> lookup SPI interface class * @param spiInterface SPI interface or abstract class type * @param focusClassName focused SPI implementation class name * @param args constructor arguments * @return implementation of parameter spiInterface * * @throws CheckerNoPassException when not found implementation SPI */ public <T> T lookupFocusSPISkipCache(Class<T> spiInterface, String focusClassName, Object... args) { T object = null; ServiceLoader<T> serviceLoader = ServiceLoader.load(spiInterface, focusClassName, args); object = serviceLoader.iterator().next(); Checker.require(object).notNull("Cannot found SPI implementation for " + spiInterface); return object; } /** * * lookupAllSPI:fina all instance of SPI implementation. <br> * Notice:<BR> * <ul> * <li>all implementation need default constructor.</li> * <li>do not search from cache</li> * </ul> * * @param <T> SPI type * @param spiInterface SPI interface or abstract class type * @return list of all SPI implementation instance */ public <T> List<T> lookupAllSPI(Class<T> spiInterface) { List<T> list = new ArrayList<>(); ServiceLoader<T> serviceLoader = ServiceLoader.load(spiInterface); Iterator<T> iterator = serviceLoader.iterator(); while (iterator.hasNext()) { try { list.add(iterator.next()); } catch (Exception e) { // ignore } } return list; } /** * * register an instance, which key is object.getClass(). <br> * * @param <T> registered object class type * @param object instance which need registered */ public <T> void register(T object) { if (object != null) { lock.writeLock().tryLock(); try { objectPool.put(object.getClass(), object); } finally { lock.writeLock().unlock(); } } } /** * register an instance, which key is given parameter classType * * @param <T> registered object class type * @param classType Class as the key for registered instance * @param object instance which need registered */ public <T> void register(Class<T> classType, T object) { if (object != null) { lock.writeLock().tryLock(); try { objectPool.put(classType, object); } finally { lock.writeLock().unlock(); } } } /** * register object and mapping it to given bean name * * @param <T> register object type * @param beanName String bean name * @param object register object */ public <T> void register(String beanName, T object) { if (object != null) { lock.writeLock().lock(); try { objectPool.put(beanName, object); } finally { lock.writeLock().unlock(); } } } protected void cleanUp() { lock.writeLock().lock(); try { objectPool.cleanUp(); } finally { lock.writeLock().unlock(); } } }
daileyet/openlibs.utilities
src/main/java/com/openthinks/libs/utilities/lookup/LookupPool.java
Java
apache-2.0
11,805
package com.arges.sepan.argmusicplayer.Callbacks; import com.arges.sepan.argmusicplayer.Models.ArgAudio; //Interfaces public interface OnPreparedListener { void onPrepared(ArgAudio audio, int duration); }
mergehez/ArgPlayer
argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Callbacks/OnPreparedListener.java
Java
apache-2.0
211
package io.monocycle.agent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; @Configuration @EnableAutoConfiguration @ComponentScan @EnableAsync @EnableScheduling public class AgentApplication { private static final Logger LOGGER = LoggerFactory.getLogger(AgentApplication.class); public static void main(String[] args) { LOGGER.debug("Starting Monocycle Agent..."); SpringApplication.run(AgentApplication.class, args); } }
monocycle/monocycle-agent
src/main/java/io/monocycle/agent/AgentApplication.java
Java
apache-2.0
847
/* * Copyright 2014 Waratek 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 com.waratek.spiracle.sql.servlet.oracle; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.waratek.spiracle.sql.servlet.util.ParameterNullFix; import com.waratek.spiracle.sql.util.SelectUtil; /** * Servlet implementation class Get_string_no_quote */ @WebServlet({"/Get_string_no_quote", "/MsSql_Get_string_no_quote", "/MySql_Get_string_no_quote"}) public class Get_string_no_quote extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Get_string_no_quote() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { executeRequest(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { executeRequest(request, response); } private void executeRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { ServletContext application = this.getServletConfig().getServletContext(); List<String> queryStringList = new ArrayList<String>(); queryStringList.add("name"); Map<String, String> nullSanitizedMap = ParameterNullFix.sanitizeNull(queryStringList, request); String name = nullSanitizedMap.get("name"); String sql = "SELECT * FROM users WHERE name = " + name; Boolean showErrors = true; Boolean allResults = true; Boolean showOutput = true; SelectUtil.executeQuery(sql, application, request, response, showErrors, allResults, showOutput); } }
waratek/spiracle
src/main/java/com/waratek/spiracle/sql/servlet/oracle/Get_string_no_quote.java
Java
apache-2.0
2,885
module.exports = function(fancyRequire) { fancyRequire('merchant_row'); };
loop-recur/moo-phone
Resources/views/views.js
JavaScript
apache-2.0
77
package fr.xebia.unittestwithdagger; import android.widget.TextView; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import fr.xebia.unittestwithdagger.internal.CustomRobolectricTestRunner; import static junit.framework.Assert.assertEquals; import static org.mockito.BDDMockito.given; /** * Created by florentchampigny on 12/11/2015. */ @RunWith(CustomRobolectricTestRunner.class) @Config(application = MyTestApplication.class, constants = BuildConfig.class, sdk=21) public class UserActivityTest { UserActivity activity; UserStorage userStorage; @Before public void setUp() throws Exception { activity = Robolectric.buildActivity(UserActivity.class).create().get(); userStorage = MyApplication.get().component().userStorage(); } @Test public void displayLoggedUserShoulDisplayFlorent(){ given(userStorage.loadUser()).willReturn(new User("florent")); TextView textView = (TextView)activity.findViewById(R.id.text); activity.displayLoggedUser(); assertEquals("florent", textView.getText().toString()); } }
florent37/UnitTestWithDagger
app/src/test/java/fr/xebia/unittestwithdagger/UserActivityTest.java
Java
apache-2.0
1,254
import { PluginMeta } from '@savantly/sprout-api'; export const validatePluginJson = (pluginJson: any) => { if (!pluginJson.id) { throw new Error('Plugin id is missing in plugin.json'); } if (!pluginJson.info) { throw new Error('Plugin info node is missing in plugin.json'); } if (!pluginJson.info.version) { throw new Error('Plugin info.version is missing in plugin.json'); } const types = ['panel', 'datasource', 'app']; const type = pluginJson.type; if (!types.includes(type)) { throw new Error('Invalid plugin type in plugin.json: ' + type); } if (!pluginJson.id.endsWith('-' + type)) { throw new Error('[plugin.json] id should end with: -' + type); } }; export const getPluginJson = (path: string): PluginMeta => { let pluginJson; try { pluginJson = require(path); } catch (e) { throw new Error('Unable to find: ' + path); } validatePluginJson(pluginJson); return pluginJson as PluginMeta; };
savantly-net/sprout-platform
frontend/tools/sprout-toolkit/src/config/utils/pluginValidation.ts
TypeScript
apache-2.0
970
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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 warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.analytics.data_v1alpha.types import analytics_data_api from .base import AlphaAnalyticsDataTransport, DEFAULT_CLIENT_INFO from .grpc import AlphaAnalyticsDataGrpcTransport class AlphaAnalyticsDataGrpcAsyncIOTransport(AlphaAnalyticsDataTransport): """gRPC AsyncIO backend transport for AlphaAnalyticsData. Google Analytics reporting data service. This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation and call it. It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ _grpc_channel: aio.Channel _stubs: Dict[str, Callable] = {} @classmethod def create_channel( cls, host: str = "analyticsdata.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. quota_project_id (Optional[str]): An optional project to use for billing and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: aio.Channel: A gRPC AsyncIO channel object. """ return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, **kwargs, ) def __init__( self, *, host: str = "analyticsdata.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. channel (Optional[aio.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for the grpc channel. It is ignored if ``channel`` is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, both in PEM format. It is used to configure a mutual TLS channel. It is ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. always_use_jwt_access (Optional[bool]): Whether self signed JWT should be used for service account credentials. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) if client_cert_source: warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: # Ignore credentials if a channel was passed. credentials = False # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None else: if api_mtls_endpoint: host = api_mtls_endpoint # Create SSL credentials with client_cert_source or application # default SSL credentials. if client_cert_source: cert, key = client_cert_source() self._ssl_channel_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) else: self._ssl_channel_credentials = SslCredentials().ssl_credentials else: if client_cert_source_for_mtls and not ssl_channel_credentials: cert, key = client_cert_source_for_mtls() self._ssl_channel_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) # The base transport sets the host, credentials and scopes super().__init__( host=host, credentials=credentials, credentials_file=credentials_file, scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, credentials=self._credentials, credentials_file=credentials_file, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) # Wrap messages. This must be done after self._grpc_channel exists self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: """Create the channel designed to connect to this service. This property caches on the instance; repeated calls return the same channel. """ # Return the channel from cache. return self._grpc_channel @property def run_report( self, ) -> Callable[ [analytics_data_api.RunReportRequest], Awaitable[analytics_data_api.RunReportResponse], ]: r"""Return a callable for the run report method over gRPC. Returns a customized report of your Google Analytics event data. Reports contain statistics derived from data collected by the Google Analytics tracking code. The data returned from the API is as a table with columns for the requested dimensions and metrics. Metrics are individual measurements of user activity on your property, such as active users or event count. Dimensions break down metrics across some common criteria, such as country or event name. Returns: Callable[[~.RunReportRequest], Awaitable[~.RunReportResponse]]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "run_report" not in self._stubs: self._stubs["run_report"] = self.grpc_channel.unary_unary( "/google.analytics.data.v1alpha.AlphaAnalyticsData/RunReport", request_serializer=analytics_data_api.RunReportRequest.serialize, response_deserializer=analytics_data_api.RunReportResponse.deserialize, ) return self._stubs["run_report"] @property def run_pivot_report( self, ) -> Callable[ [analytics_data_api.RunPivotReportRequest], Awaitable[analytics_data_api.RunPivotReportResponse], ]: r"""Return a callable for the run pivot report method over gRPC. Returns a customized pivot report of your Google Analytics event data. Pivot reports are more advanced and expressive formats than regular reports. In a pivot report, dimensions are only visible if they are included in a pivot. Multiple pivots can be specified to further dissect your data. Returns: Callable[[~.RunPivotReportRequest], Awaitable[~.RunPivotReportResponse]]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "run_pivot_report" not in self._stubs: self._stubs["run_pivot_report"] = self.grpc_channel.unary_unary( "/google.analytics.data.v1alpha.AlphaAnalyticsData/RunPivotReport", request_serializer=analytics_data_api.RunPivotReportRequest.serialize, response_deserializer=analytics_data_api.RunPivotReportResponse.deserialize, ) return self._stubs["run_pivot_report"] @property def batch_run_reports( self, ) -> Callable[ [analytics_data_api.BatchRunReportsRequest], Awaitable[analytics_data_api.BatchRunReportsResponse], ]: r"""Return a callable for the batch run reports method over gRPC. Returns multiple reports in a batch. All reports must be for the same Entity. Returns: Callable[[~.BatchRunReportsRequest], Awaitable[~.BatchRunReportsResponse]]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "batch_run_reports" not in self._stubs: self._stubs["batch_run_reports"] = self.grpc_channel.unary_unary( "/google.analytics.data.v1alpha.AlphaAnalyticsData/BatchRunReports", request_serializer=analytics_data_api.BatchRunReportsRequest.serialize, response_deserializer=analytics_data_api.BatchRunReportsResponse.deserialize, ) return self._stubs["batch_run_reports"] @property def batch_run_pivot_reports( self, ) -> Callable[ [analytics_data_api.BatchRunPivotReportsRequest], Awaitable[analytics_data_api.BatchRunPivotReportsResponse], ]: r"""Return a callable for the batch run pivot reports method over gRPC. Returns multiple pivot reports in a batch. All reports must be for the same Entity. Returns: Callable[[~.BatchRunPivotReportsRequest], Awaitable[~.BatchRunPivotReportsResponse]]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "batch_run_pivot_reports" not in self._stubs: self._stubs["batch_run_pivot_reports"] = self.grpc_channel.unary_unary( "/google.analytics.data.v1alpha.AlphaAnalyticsData/BatchRunPivotReports", request_serializer=analytics_data_api.BatchRunPivotReportsRequest.serialize, response_deserializer=analytics_data_api.BatchRunPivotReportsResponse.deserialize, ) return self._stubs["batch_run_pivot_reports"] @property def get_metadata( self, ) -> Callable[ [analytics_data_api.GetMetadataRequest], Awaitable[analytics_data_api.Metadata] ]: r"""Return a callable for the get metadata method over gRPC. Returns metadata for dimensions and metrics available in reporting methods. Used to explore the dimensions and metrics. In this method, a Google Analytics GA4 Property Identifier is specified in the request, and the metadata response includes Custom dimensions and metrics as well as Universal metadata. For example if a custom metric with parameter name ``levels_unlocked`` is registered to a property, the Metadata response will contain ``customEvent:levels_unlocked``. Universal metadata are dimensions and metrics applicable to any property such as ``country`` and ``totalUsers``. Returns: Callable[[~.GetMetadataRequest], Awaitable[~.Metadata]]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_metadata" not in self._stubs: self._stubs["get_metadata"] = self.grpc_channel.unary_unary( "/google.analytics.data.v1alpha.AlphaAnalyticsData/GetMetadata", request_serializer=analytics_data_api.GetMetadataRequest.serialize, response_deserializer=analytics_data_api.Metadata.deserialize, ) return self._stubs["get_metadata"] @property def run_realtime_report( self, ) -> Callable[ [analytics_data_api.RunRealtimeReportRequest], Awaitable[analytics_data_api.RunRealtimeReportResponse], ]: r"""Return a callable for the run realtime report method over gRPC. The Google Analytics Realtime API returns a customized report of realtime event data for your property. These reports show events and usage from the last 30 minutes. Returns: Callable[[~.RunRealtimeReportRequest], Awaitable[~.RunRealtimeReportResponse]]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "run_realtime_report" not in self._stubs: self._stubs["run_realtime_report"] = self.grpc_channel.unary_unary( "/google.analytics.data.v1alpha.AlphaAnalyticsData/RunRealtimeReport", request_serializer=analytics_data_api.RunRealtimeReportRequest.serialize, response_deserializer=analytics_data_api.RunRealtimeReportResponse.deserialize, ) return self._stubs["run_realtime_report"] __all__ = ("AlphaAnalyticsDataGrpcAsyncIOTransport",)
googleapis/python-analytics-data
google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py
Python
apache-2.0
19,474
/** * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved. * * 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.1 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. */ package org.politaktiv.map.model.impl; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.model.CacheModel; import org.politaktiv.map.model.Layer; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Date; /** * The cache model class for representing Layer in entity cache. * * @author Paul Butenko * @see Layer * @generated */ public class LayerCacheModel implements CacheModel<Layer>, Externalizable { @Override public String toString() { StringBundler sb = new StringBundler(11); sb.append("{layerId="); sb.append(layerId); sb.append(", createDate="); sb.append(createDate); sb.append(", label="); sb.append(label); sb.append(", userId="); sb.append(userId); sb.append(", portletInstance="); sb.append(portletInstance); sb.append("}"); return sb.toString(); } @Override public Layer toEntityModel() { LayerImpl layerImpl = new LayerImpl(); layerImpl.setLayerId(layerId); if (createDate == Long.MIN_VALUE) { layerImpl.setCreateDate(null); } else { layerImpl.setCreateDate(new Date(createDate)); } if (label == null) { layerImpl.setLabel(StringPool.BLANK); } else { layerImpl.setLabel(label); } layerImpl.setUserId(userId); if (portletInstance == null) { layerImpl.setPortletInstance(StringPool.BLANK); } else { layerImpl.setPortletInstance(portletInstance); } layerImpl.resetOriginalValues(); return layerImpl; } @Override public void readExternal(ObjectInput objectInput) throws IOException { layerId = objectInput.readLong(); createDate = objectInput.readLong(); label = objectInput.readUTF(); userId = objectInput.readLong(); portletInstance = objectInput.readUTF(); } @Override public void writeExternal(ObjectOutput objectOutput) throws IOException { objectOutput.writeLong(layerId); objectOutput.writeLong(createDate); if (label == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(label); } objectOutput.writeLong(userId); if (portletInstance == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(portletInstance); } } public long layerId; public long createDate; public String label; public long userId; public String portletInstance; }
PolitAktiv/politaktiv-map2-portlet
docroot/WEB-INF/src/org/politaktiv/map/model/impl/LayerCacheModel.java
Java
apache-2.0
3,021
/* Copyright (c) 2016 PaddlePaddle 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 "paddle/fluid/operators/optimizers/rmsprop_op.h" namespace paddle { namespace operators { class RmspropOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext *ctx) const override { PADDLE_ENFORCE_EQ(ctx->HasInput("Param"), true, platform::errors::NotFound( "Input(Param) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasInput("MeanSquare"), true, platform::errors::NotFound( "Input(MeanSquare) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasInput("LearningRate"), true, platform::errors::NotFound( "Input(LearningRate) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ(ctx->HasInput("Grad"), true, platform::errors::NotFound( "Input(Grad) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ(ctx->HasInput("Moment"), true, platform::errors::NotFound( "Input(Moment) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ(ctx->GetInputsVarType("Param").front(), framework::proto::VarType::LOD_TENSOR, platform::errors::InvalidArgument( "The input var's type in RmspropOp should be " "LoDTensor, but the received is %s", ctx->GetInputsVarType("Param").front())); PADDLE_ENFORCE_EQ( ctx->HasOutput("ParamOut"), true, platform::errors::NotFound( "Output(param_out) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("MomentOut"), true, platform::errors::NotFound( "Output(MomentOut) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("MeanSquareOut"), true, platform::errors::NotFound( "Output(MeanSquareOut) of RmspropOp should not be null.")); if (ctx->Attrs().Get<bool>("centered")) { PADDLE_ENFORCE_EQ( ctx->HasOutput("MeanGradOut"), true, platform::errors::NotFound( "Output(MeanGradOut) of RmspropOp should not be null.")); } auto param_dim = ctx->GetInputDim("Param"); PADDLE_ENFORCE_EQ( param_dim, ctx->GetInputDim("Grad"), platform::errors::InvalidArgument( "Param and grad input of RmspropOp should have the same dimension. " "But received Param's dim [%s] and Grad's dim [%s].", param_dim, ctx->GetInputDim("Grad"))); PADDLE_ENFORCE_EQ(param_dim, ctx->GetInputDim("Moment"), platform::errors::InvalidArgument( "Param and Momentum input of RmspropOp " "should have the same dimension. But received " "Param's dim [%s] and Moment [%s]", param_dim, ctx->GetInputDim("Moment"))); PADDLE_ENFORCE_EQ(param_dim, ctx->GetInputDim("MeanSquare"), platform::errors::InvalidArgument( "Param and Momentum input of RmspropOp " "should have the same dimension. But received " "Param's dim [%s] and MeanSquare [%s]", param_dim, ctx->GetInputDim("MeanSquare"))); auto lr_dim = ctx->GetInputDim("LearningRate"); PADDLE_ENFORCE_EQ(phi::product(lr_dim), 1, platform::errors::InvalidArgument( "Learning Rate of RmspropOp should be a scalar. But " "received LearningRate's dim [%s]", phi::product(lr_dim))); ctx->SetOutputDim("ParamOut", param_dim); ctx->SetOutputDim("MomentOut", param_dim); ctx->SetOutputDim("MeanSquareOut", param_dim); if (ctx->Attrs().Get<bool>("centered")) { ctx->SetOutputDim("MeanGradOut", param_dim); } } }; class RmspropOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("Param", "(Tensor, default Tensor<float>) " "Input parameter value that has to be updated."); AddInput("MeanSquare", "(Tensor, default Tensor<float>)" " The mean square value that gets updated."); AddInput("MeanGrad", "(Tensor, default Tensor<float>)" " The moving average of gradient") .AsDispensable(); AddInput("LearningRate", "(Tensor, default Tensor<float>) " "The learning rate should be a tensor of size 1."); AddInput("Grad", "(Tensor, default Tensor<float>) " "Input gradient of the parameter."); AddInput("Moment", "(Tensor, default Tensor<float>) The moment that gets updated."); AddOutput("ParamOut", "(Tensor) Output updated parameter value."); AddOutput("MomentOut", "(Tensor) Output updated moment."); AddOutput("MeanSquareOut", "(Tensor) Output Mean squared updated value."); AddOutput("MeanGradOut", "(Tensor) Output moving average of gradient updated value."); AddAttr<float>("epsilon", "(float, default 1e-10) Constant " "for numerical stability.") .SetDefault(1.0e-10f); AddAttr<float>("decay", "(float, default 0.9) " "Discounting factor for coming gradient.") .SetDefault(0.9f); AddAttr<float>("momentum", "(float, default 0.0) Constant value.") .SetDefault(0.0f); AddAttr<bool>("centered", "(bool, default false) use centered rmsprop.") .SetDefault(false); AddComment(R"DOC( Rmsprop Optimizer. $$ MeanSquareOut = decay * MeanSquare + (1 - decay) * Grad * Grad \\ MomentOut = momentum * Moment + \frac{LearningRate * Grad}{\sqrt{MeanSquareOut + epsilon}} \\ ParamOut = Param - MomentOut $$ if centered is true: mean_grad = decay * mean_square{t-1} + (1-decay) * gradient mean_square = decay * mean_square{t-1} + (1-decay) * gradient ** 2 mom = momentum * mom{t-1} + learning_rate * g_t / sqrt(mean_square - mean_grad**2 + epsilon) param -= mom The original slides that proposed Rmsprop: Slide 29 of http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf) )DOC"); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_WITHOUT_GRADIENT(rmsprop, ops::RmspropOp, ops::RmspropOpMaker); REGISTER_OP_CPU_KERNEL( rmsprop, ops::RmspropOpKernel<paddle::platform::CPUDeviceContext, float>, ops::RmspropOpKernel<paddle::platform::CPUDeviceContext, double>);
PaddlePaddle/Paddle
paddle/fluid/operators/optimizers/rmsprop_op.cc
C++
apache-2.0
7,369
package main import ( "encoding/json" "fmt" "github.com/codegangsta/cli" "github.com/olekukonko/tablewriter" "github.com/zero-os/0-core/base/pm" "gopkg.in/yaml.v2" "os" "sort" "strconv" "strings" ) type containerData struct { Container struct { Arguments struct { Root string `json:"root"` Hostname string `json:"hostname"` Tags []string `json:"tags"` } `json:"arguments"` PID int `json:"pid"` Root string `json:"root"` } `json:"container"` } func containers(t Transport, c *cli.Context) { var tags []string if c.Args().Present() { tags = append(tags, c.Args().First()) tags = append(tags, c.Args().Tail()...) } response, err := t.Run(Command{ Sync: true, Content: pm.Command{ Command: "corex.find", Arguments: pm.MustArguments(M{ "tags": tags, }), }, }) if err != nil { log.Fatal(err) } response.ValidateResultOrExit() var containers map[string]containerData if err := json.Unmarshal([]byte(response.Data), &containers); err != nil { log.Fatal(err) } table := tablewriter.NewWriter(os.Stdout) table.SetBorders(tablewriter.Border{}) table.SetAlignment(tablewriter.ALIGN_LEFT) table.SetHeader([]string{"ID", "FLIST", "HOSTNAME", "TAGS"}) ids := make([]int, 0, len(containers)) for id := range containers { iid, _ := strconv.ParseInt(id, 10, 32) ids = append(ids, int(iid)) } sort.Ints(ids) for _, id := range ids { sid := fmt.Sprintf("%d", id) container := containers[sid] table.Append([]string{ sid, container.Container.Arguments.Root, container.Container.Arguments.Hostname, strings.Join(container.Container.Arguments.Tags, ", "), }) } table.Render() } func containerInspect(t Transport, c *cli.Context) { id := c.Args().First() if id == "" { log.Fatal("missing container id") } response, err := t.Run(Command{ Sync: true, Content: pm.Command{ Command: "corex.list", Arguments: pm.MustArguments(M{}), }, }) if err != nil { log.Fatal(err) } response.ValidateResultOrExit() var containers map[string]interface{} if err := json.Unmarshal([]byte(response.Data), &containers); err != nil { log.Fatal(err) } container, ok := containers[id] if !ok { log.Fatalf("no container with id: %s", id) } data, _ := yaml.Marshal(container) fmt.Println(string(data)) }
g8os/core0
apps/corectl/container.go
GO
apache-2.0
2,323
package org.poormanscastle.studies.compilers.grammar.grammar3_1.astparser.ast; import org.poormanscastle.studies.compilers.utils.grammartools.ast.CodePosition; /** * Created by georg on 15.01.16. */ public class OperatorExpression extends AbstractAstItem implements Expression { private final Expression leftOperand, rightOperand; private final Operator operator; public OperatorExpression(CodePosition codePosition, Expression leftOperand, Operator operator, Expression rightOperand) { super(codePosition); this.leftOperand = leftOperand; this.rightOperand = rightOperand; this.operator = operator; } public Expression getLeftOperand() { return leftOperand; } public Expression getRightOperand() { return rightOperand; } public Operator getOperator() { return operator; } @Override public boolean handleProceedWith(AstItemVisitor visitor) { return visitor.proceedWithOperatorExpression(this); } @Override public void accept(AstItemVisitor visitor) { visitor.visitOperatorExpression(this); if (leftOperand.handleProceedWith(visitor)) { leftOperand.accept(visitor); } if (rightOperand.handleProceedWith(visitor)) { rightOperand.accept(visitor); } visitor.leaveOperatorExpression(this); } }
georgfedermann/compilers
straightline/src/main/java/org/poormanscastle/studies/compilers/grammar/grammar3_1/astparser/ast/OperatorExpression.java
Java
apache-2.0
1,401
using Microsoft.AspNetCore.Http; using System.Collections.Generic; namespace OAuth.AspNet.AuthServer { /// <summary> /// Provides context information used in handling an OAuth resource owner grant. /// </summary> public class OAuthGrantResourceOwnerCredentialsContext : BaseValidatingTicketContext<OAuthAuthorizationServerOptions> { /// <summary> /// Initializes a new instance of the <see cref="OAuthGrantResourceOwnerCredentialsContext"/> class /// </summary> /// <param name="context"></param> /// <param name="options"></param> /// <param name="clientId"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="scope"></param> public OAuthGrantResourceOwnerCredentialsContext(HttpContext context, OAuthAuthorizationServerOptions options, string clientId, string userName, string password, IList<string> scope) : base(context, options, null) { ClientId = clientId; UserName = userName; Password = password; Scope = scope; } /// <summary> /// OAuth client id. /// </summary> public string ClientId { get; private set; } /// <summary> /// Resource owner username. /// </summary> public string UserName { get; private set; } /// <summary> /// Resource owner password. /// </summary> public string Password { get; private set; } /// <summary> /// List of scopes allowed by the resource owner. /// </summary> public IList<string> Scope { get; private set; } } }
XacronDevelopment/oauth-aspnet
src/OAuth.AspNet.AuthServer/OAuth/AspNet/AuthServer/OAuthGrantResourceOwnerCredentialsContext.cs
C#
apache-2.0
1,705
# Generated by Django 2.1.7 on 2019-04-30 13:20 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.AlterField( model_name='publishablemodel', name='id', field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False), ), ]
flavoi/diventi
diventi/core/migrations/0002_auto_20190430_1520.py
Python
apache-2.0
446
package uk.ac.ebi.ddi.extservices.entrez.ncbiresult; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author Yasset Perez-Riverol (ypriverol@gmail.com) * @date 18/05/2015 */ @JsonIgnoreProperties(ignoreUnknown = true) public class NCBITaxResult { @JsonProperty("header") NCBIHeader header; @JsonProperty("esearchresult") NCBIEResult result; public NCBIHeader getHeader() { return header; } public void setHeader(NCBIHeader header) { this.header = header; } public NCBIEResult getResult() { return result; } public void setResult(NCBIEResult result) { this.result = result; } public String[] getNCBITaxonomy() { if (getResult() != null && getResult().getIdList() != null && getResult().getIdList().length == 1) { return getResult().getIdList(); } return null; } }
BD2K-DDI/ddi-annotation
src/main/java/uk/ac/ebi/ddi/extservices/entrez/ncbiresult/NCBITaxResult.java
Java
apache-2.0
974
package peng.zhang.mobilesafe01.servicer; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.util.Log; public class GPSService extends Service { private LocationManager lm; private MyLocationListener listener; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); lm=(LocationManager) getSystemService(LOCATION_SERVICE); /** * List<String> providers=lm.getAllProviders(); for(String pv :providers){ Log.d(TAG, pv); } */ //ΪÄÚÈÝÌṩÕßÉèÖÃÌõ¼þ Criteria criteria=new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); //ÉèÖòÎÊýϸ»¯£º //criteria.setAccuracy(Criteria.ACCURACY_FINE);//ÉèÖÃΪ×î´ó¾«¶È //criteria.setAltitudeRequired(false);//²»ÒªÇ󺣰ÎÐÅÏ¢ //criteria.setBearingRequired(false);//²»ÒªÇó·½Î»ÐÅÏ¢ //criteria.setCostAllowed(true);//ÊÇ·ñÔÊÐí¸¶·Ñ //criteria.setPowerRequirement(Criteria.POWER_LOW);//¶ÔµçÁ¿µÄÒªÇó //ÉèÖÃλÖøüмàÌýÆ÷£¬ÐèÒª´«Èë²ÎÊýΪ¶¨Î»·½Ê½¡¢¸üÐÂʱ¼ä£¨Ò»°ãÒ»·ÖÖÓ£©£¬¸üоàÀ루һ°ã50Ã×£©£¬¼àÌýÆ÷ //ÉèÖûñÈ¡×îºÃµÄλÖÃÌṩÆ÷ listener =new MyLocationListener(); String provider=lm.getBestProvider(criteria, true); lm.requestLocationUpdates(provider,0, 0, listener); Log.d("Location", "Location0"+"Æô¶¯·þÎñ"); } //·þÎñÏú»Ù£¬È¡Ïû×¢²á @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); lm.removeUpdates(listener); listener=null; } class MyLocationListener implements LocationListener{ /** * µ±Î»ÖøıäµÄʱºò»Øµ÷ */ @Override public void onLocationChanged(Location location) { Log.d("Location", "Location1"+"MyLocationListenerÖ´ÐÐÁË"); String longitude = "jj:" + location.getLongitude() + "\n"; String latitude = "w:" + location.getLatitude() + "\n"; String accuracy = "a" + location.getAccuracy() + "\n"; Log.d("Location", "Location1"+longitude); //½«±ê×¼×ø±êת»»Îª»ðÐÇ×ø±ê //ʵÀý»¯ModifyOffsetÐèÒªÊäÈëÒ»¸öÊäÈëÁ÷£¬Õâ¸öÊäÈëÁ÷¼ÈÊǶÁÈ¡Êý¾Ý¿âÁ÷ // InputStream in = null; // try { // in=getResources().getAssets().open("axisoffset.dat"); // ModifyOffset offset=ModifyOffset.getInstance(in); // //½«±ê×¼×ø±êת»»Îª»ðÐÇ×ø±ê // PointDouble double1=offset.s2c(new PointDouble(location.getLongitude(), location.getLatitude())); // //ת»»Íê³É£¬È¡³ö×ø±ê // longitude ="j:" + offset.X+ "\n"; // latitude = "w:" +offset.Y+ "\n"; // } catch (IOException e) { // e.printStackTrace(); // } catch (Exception e) { // e.printStackTrace(); // } //¶ÔµÃµ½µÄ¾­Î³¶È½øÐб£´æ SharedPreferences sp=getSharedPreferences("config", MODE_PRIVATE); Editor editor=sp.edit(); editor.putString("lastlocation", longitude + latitude + accuracy); editor.commit(); } /** * µ±×´Ì¬·¢Éú¸Ä±äµÄʱºò»Øµ÷ ¿ªÆô--¹Ø±Õ £»¹Ø±Õ--¿ªÆô */ @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } /** * ijһ¸öλÖÃÌṩÕß¿ÉÒÔʹÓÃÁË */ @Override public void onProviderEnabled(String provider) { } /** * ijһ¸öλÖÃÌṩÕß²»¿ÉÒÔʹÓÃÁË */ @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } } }
yongyu0102/MobileSafe
src/peng/zhang/mobilesafe01/servicer/GPSService.java
Java
apache-2.0
3,609
package com.ty.activity; import com.ty.app.R; import com.ty.service.AutoUpdateService; import com.ty.util.HttpCallbackListener; import com.ty.util.HttpUtil; import com.ty.util.Utility; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class WeatherActivity extends Activity implements OnClickListener{ private LinearLayout weatherInfoLayout; /** * 用于显示城市名 */ private TextView cityNameText; /** * 用于显示发布时间 */ private TextView publishText; /** * 用于显示天气描述信息 */ private TextView weatherDespText; /** * 用于显示气温1 */ private TextView temp1Text; /** * 用于显示气温2 */ private TextView temp2Text; /** * 用于显示当前日期 */ private TextView currentDateText; /** * 切换城市按钮 */ private Button switchCity; /** * 更新天气按钮 */ private Button refreshWeather; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.weather_layout); // 初始化各控件 weatherInfoLayout = (LinearLayout) findViewById(R.id.tyweather_info_layout); cityNameText = (TextView) findViewById(R.id.tycity_name); publishText = (TextView) findViewById(R.id.typublish_text); weatherDespText = (TextView) findViewById(R.id.tyweather_desp); temp1Text = (TextView) findViewById(R.id.tytemp1); temp2Text = (TextView) findViewById(R.id.tytemp2); currentDateText = (TextView) findViewById(R.id.tycurrent_date); switchCity = (Button) findViewById(R.id.tyswitch_city); refreshWeather = (Button) findViewById(R.id.tyrefresh_weather); String countyCode = getIntent().getStringExtra("county_code"); if (!TextUtils.isEmpty(countyCode)) { // 有县级代号时就去查询天气 publishText.setText("同步中..."); weatherInfoLayout.setVisibility(View.INVISIBLE); cityNameText.setVisibility(View.INVISIBLE); queryWeatherCode(countyCode); } else { // 没有县级代号时就直接显示本地天气 showWeather(); } switchCity.setOnClickListener(this); refreshWeather.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tycity_name: Intent intent = new Intent(this, ChooseAreaActivity.class); intent.putExtra("from_weather_activity", true); startActivity(intent); finish(); break; case R.id.tyrefresh_weather: publishText.setText("同步中..."); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String weatherCode = prefs.getString("weather_code", ""); if (!TextUtils.isEmpty(weatherCode)) { queryWeatherInfo(weatherCode); } break; default: break; } } /** * 查询县级代号所对应的天气代号。 */ private void queryWeatherCode(String countyCode) { String address = "http://www.weather.com.cn/data/list3/city" + countyCode + ".xml"; queryFromServer(address, "countyCode"); } /** * 查询天气代号所对应的天气。 */ private void queryWeatherInfo(String weatherCode) { String address = "http://www.weather.com.cn/data/cityinfo/" + weatherCode + ".html"; queryFromServer(address, "weatherCode"); } /** * 根据传入的地址和类型去向服务器查询天气代号或者天气信息。 */ private void queryFromServer(final String address, final String type) { HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(final String response) { if ("countyCode".equals(type)) { if (!TextUtils.isEmpty(response)) { // 从服务器返回的数据中解析出天气代号 String[] array = response.split("\\|"); if (array != null && array.length == 2) { String weatherCode = array[1]; queryWeatherInfo(weatherCode); } } } else if ("weatherCode".equals(type)) { // 处理服务器返回的天气信息 Utility.handleWeatherResponse(WeatherActivity.this, response); runOnUiThread(new Runnable() { @Override public void run() { showWeather(); } }); } } @Override public void onError(Exception e) { runOnUiThread(new Runnable() { @Override public void run() { publishText.setText("同步失败"); } }); } }); } /** * 从SharedPreferences文件中读取存储的天气信息,并显示到界面上。 */ private void showWeather() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); cityNameText.setText( prefs.getString("city_name", "")); temp1Text.setText(prefs.getString("temp1", "")); temp2Text.setText(prefs.getString("temp2", "")); weatherDespText.setText(prefs.getString("weather_desp", "")); publishText.setText("今天" + prefs.getString("publish_time", "") + "发布"); currentDateText.setText(prefs.getString("current_date", "")); weatherInfoLayout.setVisibility(View.VISIBLE); cityNameText.setVisibility(View.VISIBLE); Intent intent = new Intent(this, AutoUpdateService.class); startService(intent); } }
tanqii/weather
src/com/ty/activity/WeatherActivity.java
Java
apache-2.0
5,476
// Generated from /POI/java/org/apache/poi/hssf/record/DBCellRecord.java #pragma once #include <fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <org/apache/poi/hssf/record/fwd-POI.hpp> #include <org/apache/poi/util/fwd-POI.hpp> #include <org/apache/poi/hssf/record/StandardRecord.hpp> #include <java/lang/Cloneable.hpp> struct default_init_tag; class poi::hssf::record::DBCellRecord final : public StandardRecord , public ::java::lang::Cloneable { public: typedef StandardRecord super; static constexpr int16_t sid { int16_t(215) }; static constexpr int32_t BLOCK_SIZE { int32_t(32) }; private: int32_t field_1_row_offset { }; ::int16_tArray* field_2_cell_offsets { }; protected: void ctor(int32_t rowOffset, ::int16_tArray* cellOffsets); void ctor(RecordInputStream* in); public: ::java::lang::String* toString() override; void serialize(::poi::util::LittleEndianOutput* out) override; public: /* protected */ int32_t getDataSize() override; public: int16_t getSid() override; DBCellRecord* clone() override; // Generated public: /* package */ DBCellRecord(int32_t rowOffset, ::int16_tArray* cellOffsets); public: DBCellRecord(RecordInputStream* in); protected: DBCellRecord(const ::default_init_tag&); public: static ::java::lang::Class *class_(); int32_t serialize(int32_t offset, ::int8_tArray* data); ::int8_tArray* serialize(); private: virtual ::java::lang::Class* getClass0(); friend class DBCellRecord_Builder; };
pebble2015/cpoi
src/org/apache/poi/hssf/record/DBCellRecord.hpp
C++
apache-2.0
1,539
import { Pipe, PipeTransform } from '@angular/core'; import { Project } from 'app/models/project'; @Pipe({ name: 'operatorFilter' }) export class OperatorFilterPipe implements PipeTransform { transform(value: Project[], q: string) { if (!q) { return value; } return value.filter(item => -1 < item.operator.toLowerCase().indexOf(q.toLowerCase())); } }
asanchezr/mem-mmti-public
src/app/operator-filter.pipe.ts
TypeScript
apache-2.0
378
//===--- CGDeclCXX.cpp - Emit LLVM Code for C++ declarations --------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This contains code dealing with code generation of C++ declarations // //===----------------------------------------------------------------------===// #include "CodeGenFunction.h" #include "CGCXXABI.h" #include "CGObjCRuntime.h" #include "CGOpenMPRuntime.h" #include "clang/Basic/CodeGenOptions.h" #include "llvm/ADT/StringExtras.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/MDBuilder.h" #include "llvm/Support/Path.h" using namespace clang; using namespace CodeGen; static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D, ConstantAddress DeclPtr) { assert( (D.hasGlobalStorage() || (D.hasLocalStorage() && CGF.getContext().getLangOpts().OpenCLCPlusPlus)) && "VarDecl must have global or local (in the case of OpenCL) storage!"); assert(!D.getType()->isReferenceType() && "Should not call EmitDeclInit on a reference!"); QualType type = D.getType(); LValue lv = CGF.MakeAddrLValue(DeclPtr, type); const Expr *Init = D.getInit(); switch (CGF.getEvaluationKind(type)) { case TEK_Scalar: { CodeGenModule &CGM = CGF.CGM; if (lv.isObjCStrong()) CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init), DeclPtr, D.getTLSKind()); else if (lv.isObjCWeak()) CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init), DeclPtr); else CGF.EmitScalarInit(Init, &D, lv, false); return; } case TEK_Complex: CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true); return; case TEK_Aggregate: CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed, AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased, AggValueSlot::DoesNotOverlap)); return; } llvm_unreachable("bad evaluation kind"); } /// Emit code to cause the destruction of the given variable with /// static storage duration. static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D, ConstantAddress Addr) { // Honor __attribute__((no_destroy)) and bail instead of attempting // to emit a reference to a possibly nonexistent destructor, which // in turn can cause a crash. This will result in a global constructor // that isn't balanced out by a destructor call as intended by the // attribute. This also checks for -fno-c++-static-destructors and // bails even if the attribute is not present. if (D.isNoDestroy(CGF.getContext())) return; CodeGenModule &CGM = CGF.CGM; // FIXME: __attribute__((cleanup)) ? QualType Type = D.getType(); QualType::DestructionKind DtorKind = Type.isDestructedType(); switch (DtorKind) { case QualType::DK_none: return; case QualType::DK_cxx_destructor: break; case QualType::DK_objc_strong_lifetime: case QualType::DK_objc_weak_lifetime: case QualType::DK_nontrivial_c_struct: // We don't care about releasing objects during process teardown. assert(!D.getTLSKind() && "should have rejected this"); return; } llvm::FunctionCallee Func; llvm::Constant *Argument; // Special-case non-array C++ destructors, if they have the right signature. // Under some ABIs, destructors return this instead of void, and cannot be // passed directly to __cxa_atexit if the target does not allow this // mismatch. const CXXRecordDecl *Record = Type->getAsCXXRecordDecl(); bool CanRegisterDestructor = Record && (!CGM.getCXXABI().HasThisReturn( GlobalDecl(Record->getDestructor(), Dtor_Complete)) || CGM.getCXXABI().canCallMismatchedFunctionType()); // If __cxa_atexit is disabled via a flag, a different helper function is // generated elsewhere which uses atexit instead, and it takes the destructor // directly. bool UsingExternalHelper = !CGM.getCodeGenOpts().CXAAtExit; if (Record && (CanRegisterDestructor || UsingExternalHelper)) { assert(!Record->hasTrivialDestructor()); CXXDestructorDecl *Dtor = Record->getDestructor(); Func = CGM.getAddrAndTypeOfCXXStructor(GlobalDecl(Dtor, Dtor_Complete)); Argument = llvm::ConstantExpr::getBitCast( Addr.getPointer(), CGF.getTypes().ConvertType(Type)->getPointerTo()); // Otherwise, the standard logic requires a helper function. } else { Func = CodeGenFunction(CGM) .generateDestroyHelper(Addr, Type, CGF.getDestroyer(DtorKind), CGF.needsEHCleanup(DtorKind), &D); Argument = llvm::Constant::getNullValue(CGF.Int8PtrTy); } CGM.getCXXABI().registerGlobalDtor(CGF, D, Func, Argument); } /// Emit code to cause the variable at the given address to be considered as /// constant from this point onwards. static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D, llvm::Constant *Addr) { return CGF.EmitInvariantStart( Addr, CGF.getContext().getTypeSizeInChars(D.getType())); } void CodeGenFunction::EmitInvariantStart(llvm::Constant *Addr, CharUnits Size) { // Do not emit the intrinsic if we're not optimizing. if (!CGM.getCodeGenOpts().OptimizationLevel) return; // Grab the llvm.invariant.start intrinsic. llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start; // Overloaded address space type. llvm::Type *ObjectPtr[1] = {Int8PtrTy}; llvm::Function *InvariantStart = CGM.getIntrinsic(InvStartID, ObjectPtr); // Emit a call with the size in bytes of the object. uint64_t Width = Size.getQuantity(); llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(Int64Ty, Width), llvm::ConstantExpr::getBitCast(Addr, Int8PtrTy)}; Builder.CreateCall(InvariantStart, Args); } void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr, bool PerformInit) { const Expr *Init = D.getInit(); QualType T = D.getType(); // The address space of a static local variable (DeclPtr) may be different // from the address space of the "this" argument of the constructor. In that // case, we need an addrspacecast before calling the constructor. // // struct StructWithCtor { // __device__ StructWithCtor() {...} // }; // __device__ void foo() { // __shared__ StructWithCtor s; // ... // } // // For example, in the above CUDA code, the static local variable s has a // "shared" address space qualifier, but the constructor of StructWithCtor // expects "this" in the "generic" address space. unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(T); unsigned ActualAddrSpace = DeclPtr->getType()->getPointerAddressSpace(); if (ActualAddrSpace != ExpectedAddrSpace) { llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(T); llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace); DeclPtr = llvm::ConstantExpr::getAddrSpaceCast(DeclPtr, PTy); } ConstantAddress DeclAddr(DeclPtr, getContext().getDeclAlign(&D)); if (!T->isReferenceType()) { if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd && D.hasAttr<OMPThreadPrivateDeclAttr>()) { (void)CGM.getOpenMPRuntime().emitThreadPrivateVarDefinition( &D, DeclAddr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(), PerformInit, this); } if (PerformInit) EmitDeclInit(*this, D, DeclAddr); if (CGM.isTypeConstant(D.getType(), true)) EmitDeclInvariant(*this, D, DeclPtr); else EmitDeclDestroy(*this, D, DeclAddr); return; } assert(PerformInit && "cannot have constant initializer which needs " "destruction for reference"); RValue RV = EmitReferenceBindingToExpr(Init); EmitStoreOfScalar(RV.getScalarVal(), DeclAddr, false, T); } /// Create a stub function, suitable for being passed to atexit, /// which passes the given address to the given destructor function. llvm::Function *CodeGenFunction::createAtExitStub(const VarDecl &VD, llvm::FunctionCallee dtor, llvm::Constant *addr) { // Get the destructor function type, void(*)(void). llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false); SmallString<256> FnName; { llvm::raw_svector_ostream Out(FnName); CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out); } const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction(); llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction( ty, FnName.str(), FI, VD.getLocation()); CodeGenFunction CGF(CGM); CGF.StartFunction(GlobalDecl(&VD, DynamicInitKind::AtExit), CGM.getContext().VoidTy, fn, FI, FunctionArgList()); llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr); // Make sure the call and the callee agree on calling convention. if (llvm::Function *dtorFn = dyn_cast<llvm::Function>(dtor.getCallee()->stripPointerCasts())) call->setCallingConv(dtorFn->getCallingConv()); CGF.FinishFunction(); return fn; } /// Register a global destructor using the C atexit runtime function. void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD, llvm::FunctionCallee dtor, llvm::Constant *addr) { // Create a function which calls the destructor. llvm::Constant *dtorStub = createAtExitStub(VD, dtor, addr); registerGlobalDtorWithAtExit(dtorStub); } void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtorStub) { // extern "C" int atexit(void (*f)(void)); llvm::FunctionType *atexitTy = llvm::FunctionType::get(IntTy, dtorStub->getType(), false); llvm::FunctionCallee atexit = CGM.CreateRuntimeFunction(atexitTy, "atexit", llvm::AttributeList(), /*Local=*/true); if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit.getCallee())) atexitFn->setDoesNotThrow(); EmitNounwindRuntimeCall(atexit, dtorStub); } void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, bool PerformInit) { // If we've been asked to forbid guard variables, emit an error now. // This diagnostic is hard-coded for Darwin's use case; we can find // better phrasing if someone else needs it. if (CGM.getCodeGenOpts().ForbidGuardVariables) CGM.Error(D.getLocation(), "this initialization requires a guard variable, which " "the kernel does not support"); CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit); } void CodeGenFunction::EmitCXXGuardedInitBranch(llvm::Value *NeedsInit, llvm::BasicBlock *InitBlock, llvm::BasicBlock *NoInitBlock, GuardKind Kind, const VarDecl *D) { assert((Kind == GuardKind::TlsGuard || D) && "no guarded variable"); // A guess at how many times we will enter the initialization of a // variable, depending on the kind of variable. static const uint64_t InitsPerTLSVar = 1024; static const uint64_t InitsPerLocalVar = 1024 * 1024; llvm::MDNode *Weights; if (Kind == GuardKind::VariableGuard && !D->isLocalVarDecl()) { // For non-local variables, don't apply any weighting for now. Due to our // use of COMDATs, we expect there to be at most one initialization of the // variable per DSO, but we have no way to know how many DSOs will try to // initialize the variable. Weights = nullptr; } else { uint64_t NumInits; // FIXME: For the TLS case, collect and use profiling information to // determine a more accurate brach weight. if (Kind == GuardKind::TlsGuard || D->getTLSKind()) NumInits = InitsPerTLSVar; else NumInits = InitsPerLocalVar; // The probability of us entering the initializer is // 1 / (total number of times we attempt to initialize the variable). llvm::MDBuilder MDHelper(CGM.getLLVMContext()); Weights = MDHelper.createBranchWeights(1, NumInits - 1); } Builder.CreateCondBr(NeedsInit, InitBlock, NoInitBlock, Weights); } llvm::Function *CodeGenModule::CreateGlobalInitOrDestructFunction( llvm::FunctionType *FTy, const Twine &Name, const CGFunctionInfo &FI, SourceLocation Loc, bool TLS) { llvm::Function *Fn = llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage, Name, &getModule()); if (!getLangOpts().AppleKext && !TLS) { // Set the section if needed. if (const char *Section = getTarget().getStaticInitSectionSpecifier()) Fn->setSection(Section); } SetInternalFunctionAttributes(GlobalDecl(), Fn, FI); Fn->setCallingConv(getRuntimeCC()); if (!getLangOpts().Exceptions) Fn->setDoesNotThrow(); if (getLangOpts().Sanitize.has(SanitizerKind::Address) && !isInSanitizerBlacklist(SanitizerKind::Address, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::SanitizeAddress); if (getLangOpts().Sanitize.has(SanitizerKind::KernelAddress) && !isInSanitizerBlacklist(SanitizerKind::KernelAddress, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::SanitizeAddress); if (getLangOpts().Sanitize.has(SanitizerKind::HWAddress) && !isInSanitizerBlacklist(SanitizerKind::HWAddress, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress); if (getLangOpts().Sanitize.has(SanitizerKind::KernelHWAddress) && !isInSanitizerBlacklist(SanitizerKind::KernelHWAddress, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress); if (getLangOpts().Sanitize.has(SanitizerKind::Thread) && !isInSanitizerBlacklist(SanitizerKind::Thread, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::SanitizeThread); if (getLangOpts().Sanitize.has(SanitizerKind::Memory) && !isInSanitizerBlacklist(SanitizerKind::Memory, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::SanitizeMemory); if (getLangOpts().Sanitize.has(SanitizerKind::KernelMemory) && !isInSanitizerBlacklist(SanitizerKind::KernelMemory, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::SanitizeMemory); if (getLangOpts().Sanitize.has(SanitizerKind::SafeStack) && !isInSanitizerBlacklist(SanitizerKind::SafeStack, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::SafeStack); if (getLangOpts().Sanitize.has(SanitizerKind::ShadowCallStack) && !isInSanitizerBlacklist(SanitizerKind::ShadowCallStack, Fn, Loc)) Fn->addFnAttr(llvm::Attribute::ShadowCallStack); auto RASignKind = getCodeGenOpts().getSignReturnAddress(); if (RASignKind != CodeGenOptions::SignReturnAddressScope::None) { Fn->addFnAttr("sign-return-address", RASignKind == CodeGenOptions::SignReturnAddressScope::All ? "all" : "non-leaf"); auto RASignKey = getCodeGenOpts().getSignReturnAddressKey(); Fn->addFnAttr("sign-return-address-key", RASignKey == CodeGenOptions::SignReturnAddressKeyValue::AKey ? "a_key" : "b_key"); } if (getCodeGenOpts().BranchTargetEnforcement) Fn->addFnAttr("branch-target-enforcement"); return Fn; } /// Create a global pointer to a function that will initialize a global /// variable. The user has requested that this pointer be emitted in a specific /// section. void CodeGenModule::EmitPointerToInitFunc(const VarDecl *D, llvm::GlobalVariable *GV, llvm::Function *InitFunc, InitSegAttr *ISA) { llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable( TheModule, InitFunc->getType(), /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr"); PtrArray->setSection(ISA->getSection()); addUsedGlobal(PtrArray); // If the GV is already in a comdat group, then we have to join it. if (llvm::Comdat *C = GV->getComdat()) PtrArray->setComdat(C); } void CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D, llvm::GlobalVariable *Addr, bool PerformInit) { // According to E.2.3.1 in CUDA-7.5 Programming guide: __device__, // __constant__ and __shared__ variables defined in namespace scope, // that are of class type, cannot have a non-empty constructor. All // the checks have been done in Sema by now. Whatever initializers // are allowed are empty and we just need to ignore them here. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDASharedAttr>())) return; if (getLangOpts().OpenMP && getOpenMPRuntime().emitDeclareTargetVarDefinition(D, Addr, PerformInit)) return; // Check if we've already initialized this decl. auto I = DelayedCXXInitPosition.find(D); if (I != DelayedCXXInitPosition.end() && I->second == ~0U) return; llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false); SmallString<256> FnName; { llvm::raw_svector_ostream Out(FnName); getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out); } // Create a variable initialization function. llvm::Function *Fn = CreateGlobalInitOrDestructFunction(FTy, FnName.str(), getTypes().arrangeNullaryFunction(), D->getLocation()); auto *ISA = D->getAttr<InitSegAttr>(); CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr, PerformInit); llvm::GlobalVariable *COMDATKey = supportsCOMDAT() && D->isExternallyVisible() ? Addr : nullptr; if (D->getTLSKind()) { // FIXME: Should we support init_priority for thread_local? // FIXME: We only need to register one __cxa_thread_atexit function for the // entire TU. CXXThreadLocalInits.push_back(Fn); CXXThreadLocalInitVars.push_back(D); } else if (PerformInit && ISA) { EmitPointerToInitFunc(D, Addr, Fn, ISA); } else if (auto *IPA = D->getAttr<InitPriorityAttr>()) { OrderGlobalInits Key(IPA->getPriority(), PrioritizedCXXGlobalInits.size()); PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn)); } else if (isTemplateInstantiation(D->getTemplateSpecializationKind()) || getContext().GetGVALinkageForVariable(D) == GVA_DiscardableODR) { // C++ [basic.start.init]p2: // Definitions of explicitly specialized class template static data // members have ordered initialization. Other class template static data // members (i.e., implicitly or explicitly instantiated specializations) // have unordered initialization. // // As a consequence, we can put them into their own llvm.global_ctors entry. // // If the global is externally visible, put the initializer into a COMDAT // group with the global being initialized. On most platforms, this is a // minor startup time optimization. In the MS C++ ABI, there are no guard // variables, so this COMDAT key is required for correctness. AddGlobalCtor(Fn, 65535, COMDATKey); if (getTarget().getCXXABI().isMicrosoft() && COMDATKey) { // In The MS C++, MS add template static data member in the linker // drective. addUsedGlobal(COMDATKey); } } else if (D->hasAttr<SelectAnyAttr>()) { // SelectAny globals will be comdat-folded. Put the initializer into a // COMDAT group associated with the global, so the initializers get folded // too. AddGlobalCtor(Fn, 65535, COMDATKey); } else { I = DelayedCXXInitPosition.find(D); // Re-do lookup in case of re-hash. if (I == DelayedCXXInitPosition.end()) { CXXGlobalInits.push_back(Fn); } else if (I->second != ~0U) { assert(I->second < CXXGlobalInits.size() && CXXGlobalInits[I->second] == nullptr); CXXGlobalInits[I->second] = Fn; } } // Remember that we already emitted the initializer for this global. DelayedCXXInitPosition[D] = ~0U; } void CodeGenModule::EmitCXXThreadLocalInitFunc() { getCXXABI().EmitThreadLocalInitFuncs( *this, CXXThreadLocals, CXXThreadLocalInits, CXXThreadLocalInitVars); CXXThreadLocalInits.clear(); CXXThreadLocalInitVars.clear(); CXXThreadLocals.clear(); } void CodeGenModule::EmitCXXGlobalInitFunc() { while (!CXXGlobalInits.empty() && !CXXGlobalInits.back()) CXXGlobalInits.pop_back(); if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty()) return; llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false); const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction(); // Create our global initialization function. if (!PrioritizedCXXGlobalInits.empty()) { SmallVector<llvm::Function *, 8> LocalCXXGlobalInits; llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(), PrioritizedCXXGlobalInits.end()); // Iterate over "chunks" of ctors with same priority and emit each chunk // into separate function. Note - everything is sorted first by priority, // second - by lex order, so we emit ctor functions in proper order. for (SmallVectorImpl<GlobalInitData >::iterator I = PrioritizedCXXGlobalInits.begin(), E = PrioritizedCXXGlobalInits.end(); I != E; ) { SmallVectorImpl<GlobalInitData >::iterator PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp()); LocalCXXGlobalInits.clear(); unsigned Priority = I->first.priority; // Compute the function suffix from priority. Prepend with zeroes to make // sure the function names are also ordered as priorities. std::string PrioritySuffix = llvm::utostr(Priority); // Priority is always <= 65535 (enforced by sema). PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix; llvm::Function *Fn = CreateGlobalInitOrDestructFunction( FTy, "_GLOBAL__I_" + PrioritySuffix, FI); for (; I < PrioE; ++I) LocalCXXGlobalInits.push_back(I->second); CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits); AddGlobalCtor(Fn, Priority); } PrioritizedCXXGlobalInits.clear(); } // Include the filename in the symbol name. Including "sub_" matches gcc and // makes sure these symbols appear lexicographically behind the symbols with // priority emitted above. SmallString<128> FileName = llvm::sys::path::filename(getModule().getName()); if (FileName.empty()) FileName = "<null>"; for (size_t i = 0; i < FileName.size(); ++i) { // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens // to be the set of C preprocessing numbers. if (!isPreprocessingNumberBody(FileName[i])) FileName[i] = '_'; } llvm::Function *Fn = CreateGlobalInitOrDestructFunction( FTy, llvm::Twine("_GLOBAL__sub_I_", FileName), FI); CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits); AddGlobalCtor(Fn); // In OpenCL global init functions must be converted to kernels in order to // be able to launch them from the host. // FIXME: Some more work might be needed to handle destructors correctly. // Current initialization function makes use of function pointers callbacks. // We can't support function pointers especially between host and device. // However it seems global destruction has little meaning without any // dynamic resource allocation on the device and program scope variables are // destroyed by the runtime when program is released. if (getLangOpts().OpenCL) { GenOpenCLArgMetadata(Fn); Fn->setCallingConv(llvm::CallingConv::SPIR_KERNEL); } CXXGlobalInits.clear(); } void CodeGenModule::EmitCXXGlobalDtorFunc() { if (CXXGlobalDtors.empty()) return; llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false); // Create our global destructor function. const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction(); llvm::Function *Fn = CreateGlobalInitOrDestructFunction(FTy, "_GLOBAL__D_a", FI); CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors); AddGlobalDtor(Fn); } /// Emit the code necessary to initialize the given global variable. void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D, llvm::GlobalVariable *Addr, bool PerformInit) { // Check if we need to emit debug info for variable initializer. if (D->hasAttr<NoDebugAttr>()) DebugInfo = nullptr; // disable debug info indefinitely for this function CurEHLocation = D->getBeginLoc(); StartFunction(GlobalDecl(D, DynamicInitKind::Initializer), getContext().VoidTy, Fn, getTypes().arrangeNullaryFunction(), FunctionArgList(), D->getLocation(), D->getInit()->getExprLoc()); // Use guarded initialization if the global variable is weak. This // occurs for, e.g., instantiated static data members and // definitions explicitly marked weak. // // Also use guarded initialization for a variable with dynamic TLS and // unordered initialization. (If the initialization is ordered, the ABI // layer will guard the whole-TU initialization for us.) if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage() || (D->getTLSKind() == VarDecl::TLS_Dynamic && isTemplateInstantiation(D->getTemplateSpecializationKind()))) { EmitCXXGuardedInit(*D, Addr, PerformInit); } else { EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit); } FinishFunction(); } void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn, ArrayRef<llvm::Function *> Decls, ConstantAddress Guard) { { auto NL = ApplyDebugLocation::CreateEmpty(*this); StartFunction(GlobalDecl(), getContext().VoidTy, Fn, getTypes().arrangeNullaryFunction(), FunctionArgList()); // Emit an artificial location for this function. auto AL = ApplyDebugLocation::CreateArtificial(*this); llvm::BasicBlock *ExitBlock = nullptr; if (Guard.isValid()) { // If we have a guard variable, check whether we've already performed // these initializations. This happens for TLS initialization functions. llvm::Value *GuardVal = Builder.CreateLoad(Guard); llvm::Value *Uninit = Builder.CreateIsNull(GuardVal, "guard.uninitialized"); llvm::BasicBlock *InitBlock = createBasicBlock("init"); ExitBlock = createBasicBlock("exit"); EmitCXXGuardedInitBranch(Uninit, InitBlock, ExitBlock, GuardKind::TlsGuard, nullptr); EmitBlock(InitBlock); // Mark as initialized before initializing anything else. If the // initializers use previously-initialized thread_local vars, that's // probably supposed to be OK, but the standard doesn't say. Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard); // The guard variable can't ever change again. EmitInvariantStart( Guard.getPointer(), CharUnits::fromQuantity( CGM.getDataLayout().getTypeAllocSize(GuardVal->getType()))); } RunCleanupsScope Scope(*this); // When building in Objective-C++ ARC mode, create an autorelease pool // around the global initializers. if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) { llvm::Value *token = EmitObjCAutoreleasePoolPush(); EmitObjCAutoreleasePoolCleanup(token); } for (unsigned i = 0, e = Decls.size(); i != e; ++i) if (Decls[i]) EmitRuntimeCall(Decls[i]); Scope.ForceCleanup(); if (ExitBlock) { Builder.CreateBr(ExitBlock); EmitBlock(ExitBlock); } } FinishFunction(); } void CodeGenFunction::GenerateCXXGlobalDtorsFunc( llvm::Function *Fn, const std::vector<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH, llvm::Constant *>> &DtorsAndObjects) { { auto NL = ApplyDebugLocation::CreateEmpty(*this); StartFunction(GlobalDecl(), getContext().VoidTy, Fn, getTypes().arrangeNullaryFunction(), FunctionArgList()); // Emit an artificial location for this function. auto AL = ApplyDebugLocation::CreateArtificial(*this); // Emit the dtors, in reverse order from construction. for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) { llvm::FunctionType *CalleeTy; llvm::Value *Callee; llvm::Constant *Arg; std::tie(CalleeTy, Callee, Arg) = DtorsAndObjects[e - i - 1]; llvm::CallInst *CI = Builder.CreateCall(CalleeTy, Callee, Arg); // Make sure the call and the callee agree on calling convention. if (llvm::Function *F = dyn_cast<llvm::Function>(Callee)) CI->setCallingConv(F->getCallingConv()); } } FinishFunction(); } /// generateDestroyHelper - Generates a helper function which, when /// invoked, destroys the given object. The address of the object /// should be in global memory. llvm::Function *CodeGenFunction::generateDestroyHelper( Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray, const VarDecl *VD) { FunctionArgList args; ImplicitParamDecl Dst(getContext(), getContext().VoidPtrTy, ImplicitParamDecl::Other); args.push_back(&Dst); const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, args); llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction( FTy, "__cxx_global_array_dtor", FI, VD->getLocation()); CurEHLocation = VD->getBeginLoc(); StartFunction(VD, getContext().VoidTy, fn, FI, args); emitDestroy(addr, type, destroyer, useEHCleanupForArray); FinishFunction(); return fn; }
apple/swift-clang
lib/CodeGen/CGDeclCXX.cpp
C++
apache-2.0
30,989
// Copyright (c) 2018 Uber Technologies, Inc. // // 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 m3ql //go:generate peg -inline -switch src/query/parser/m3ql/grammar.peg import ( "fmt" "io" "math" "os" "sort" "strconv" ) const endSymbol rune = 1114112 /* The rule types inferred from the grammar are below. */ type pegRule uint8 const ( ruleUnknown pegRule = iota ruleGrammar ruleMacroDef rulePipeline ruleExpression ruleFunctionCall ruleArgument ruleKeywordSpecifier ruleNesting ruleSpacing ruleSpace ruleEOL ruleComment ruleCommentStart ruleIdentifier ruleIdentifierStart ruleIdentifierChars ruleOperator ruleOperatorSymbols ruleBoolean ruleTrue ruleFalse ruleNumber ruleIntegralNumber ruleFloatingNumber ruleMinus ruleStringLiteral ruleQuoteChar rulePattern rulePatternChars ruleGlobSymbols ruleSemicolon ruleEquals rulePipe ruleLParenthesis ruleRParenthesis ruleColon ruleEOF ruleAction0 ruleAction1 ruleAction2 ruleAction3 ruleAction4 ruleAction5 ruleAction6 ruleAction7 ruleAction8 ruleAction9 rulePegText ) var rul3s = [...]string{ "Unknown", "Grammar", "MacroDef", "Pipeline", "Expression", "FunctionCall", "Argument", "KeywordSpecifier", "Nesting", "Spacing", "Space", "EOL", "Comment", "CommentStart", "Identifier", "IdentifierStart", "IdentifierChars", "Operator", "OperatorSymbols", "Boolean", "True", "False", "Number", "IntegralNumber", "FloatingNumber", "Minus", "StringLiteral", "QuoteChar", "Pattern", "PatternChars", "GlobSymbols", "Semicolon", "Equals", "Pipe", "LParenthesis", "RParenthesis", "Colon", "EOF", "Action0", "Action1", "Action2", "Action3", "Action4", "Action5", "Action6", "Action7", "Action8", "Action9", "PegText", } type token32 struct { pegRule begin, end uint32 } func (t *token32) String() string { return fmt.Sprintf("\x1B[34m%v\x1B[m %v %v", rul3s[t.pegRule], t.begin, t.end) } type node32 struct { token32 up, next *node32 } func (node *node32) print(w io.Writer, pretty bool, buffer string) { var print func(node *node32, depth int) print = func(node *node32, depth int) { for node != nil { for c := 0; c < depth; c++ { fmt.Printf(" ") } rule := rul3s[node.pegRule] quote := strconv.Quote(string(([]rune(buffer)[node.begin:node.end]))) if !pretty { fmt.Fprintf(w, "%v %v\n", rule, quote) } else { fmt.Fprintf(w, "\x1B[34m%v\x1B[m %v\n", rule, quote) } if node.up != nil { print(node.up, depth+1) } node = node.next } } print(node, 0) } func (node *node32) Print(w io.Writer, buffer string) { node.print(w, false, buffer) } func (node *node32) PrettyPrint(w io.Writer, buffer string) { node.print(w, true, buffer) } type tokens32 struct { tree []token32 } func (t *tokens32) Trim(length uint32) { t.tree = t.tree[:length] } func (t *tokens32) Print() { for _, token := range t.tree { fmt.Println(token.String()) } } func (t *tokens32) AST() *node32 { type element struct { node *node32 down *element } tokens := t.Tokens() var stack *element for _, token := range tokens { if token.begin == token.end { continue } node := &node32{token32: token} for stack != nil && stack.node.begin >= token.begin && stack.node.end <= token.end { stack.node.next = node.up node.up = stack.node stack = stack.down } stack = &element{node: node, down: stack} } if stack != nil { return stack.node } return nil } func (t *tokens32) PrintSyntaxTree(buffer string) { t.AST().Print(os.Stdout, buffer) } func (t *tokens32) WriteSyntaxTree(w io.Writer, buffer string) { t.AST().Print(w, buffer) } func (t *tokens32) PrettyPrintSyntaxTree(buffer string) { t.AST().PrettyPrint(os.Stdout, buffer) } func (t *tokens32) Add(rule pegRule, begin, end, index uint32) { if tree := t.tree; int(index) >= len(tree) { expanded := make([]token32, 2*len(tree)) copy(expanded, tree) t.tree = expanded } t.tree[index] = token32{ pegRule: rule, begin: begin, end: end, } } func (t *tokens32) Tokens() []token32 { return t.tree } type m3ql struct { scriptBuilder Buffer string buffer []rune rules [49]func() bool parse func(rule ...int) error reset func() Pretty bool tokens32 } func (p *m3ql) Parse(rule ...int) error { return p.parse(rule...) } func (p *m3ql) Reset() { p.reset() } type textPosition struct { line, symbol int } type textPositionMap map[int]textPosition func translatePositions(buffer []rune, positions []int) textPositionMap { length, translations, j, line, symbol := len(positions), make(textPositionMap, len(positions)), 0, 1, 0 sort.Ints(positions) search: for i, c := range buffer { if c == '\n' { line, symbol = line+1, 0 } else { symbol++ } if i == positions[j] { translations[positions[j]] = textPosition{line, symbol} for j++; j < length; j++ { if i != positions[j] { continue search } } break search } } return translations } type parseError struct { p *m3ql max token32 } func (e *parseError) Error() string { tokens, error := []token32{e.max}, "\n" positions, p := make([]int, 2*len(tokens)), 0 for _, token := range tokens { positions[p], p = int(token.begin), p+1 positions[p], p = int(token.end), p+1 } translations := translatePositions(e.p.buffer, positions) format := "parse error near %v (line %v symbol %v - line %v symbol %v):\n%v\n" if e.p.Pretty { format = "parse error near \x1B[34m%v\x1B[m (line %v symbol %v - line %v symbol %v):\n%v\n" } for _, token := range tokens { begin, end := int(token.begin), int(token.end) error += fmt.Sprintf(format, rul3s[token.pegRule], translations[begin].line, translations[begin].symbol, translations[end].line, translations[end].symbol, strconv.Quote(string(e.p.buffer[begin:end]))) } return error } func (p *m3ql) PrintSyntaxTree() { if p.Pretty { p.tokens32.PrettyPrintSyntaxTree(p.Buffer) } else { p.tokens32.PrintSyntaxTree(p.Buffer) } } func (p *m3ql) WriteSyntaxTree(w io.Writer) { p.tokens32.WriteSyntaxTree(w, p.Buffer) } func (p *m3ql) Execute() { buffer, _buffer, text, begin, end := p.Buffer, p.buffer, "", 0, 0 for _, token := range p.Tokens() { switch token.pegRule { case rulePegText: begin, end = int(token.begin), int(token.end) text = string(_buffer[begin:end]) case ruleAction0: p.newMacro(text) case ruleAction1: p.newPipeline() case ruleAction2: p.endPipeline() case ruleAction3: p.newExpression(text) case ruleAction4: p.endExpression() case ruleAction5: p.newBooleanArgument(text) case ruleAction6: p.newNumericArgument(text) case ruleAction7: p.newPatternArgument(text) case ruleAction8: p.newStringLiteralArgument(text) case ruleAction9: p.newKeywordArgument(text) } } _, _, _, _, _ = buffer, _buffer, text, begin, end } func (p *m3ql) Init() { var ( max token32 position, tokenIndex uint32 buffer []rune ) p.reset = func() { max = token32{} position, tokenIndex = 0, 0 p.buffer = []rune(p.Buffer) if len(p.buffer) == 0 || p.buffer[len(p.buffer)-1] != endSymbol { p.buffer = append(p.buffer, endSymbol) } buffer = p.buffer } p.reset() _rules := p.rules tree := tokens32{tree: make([]token32, math.MaxInt16)} p.parse = func(rule ...int) error { r := 1 if len(rule) > 0 { r = rule[0] } matches := p.rules[r]() p.tokens32 = tree if matches { p.Trim(tokenIndex) return nil } return &parseError{p, max} } add := func(rule pegRule, begin uint32) { tree.Add(rule, begin, position, tokenIndex) tokenIndex++ if begin != position && position > max.end { max = token32{rule, begin, position} } } matchDot := func() bool { if buffer[position] != endSymbol { position++ return true } return false } /*matchChar := func(c byte) bool { if buffer[position] == c { position++ return true } return false }*/ /*matchRange := func(lower byte, upper byte) bool { if c := buffer[position]; c >= lower && c <= upper { position++ return true } return false }*/ _rules = [...]func() bool{ nil, /* 0 Grammar <- <(Spacing (MacroDef Semicolon)* Pipeline EOF)> */ func() bool { position0, tokenIndex0 := position, tokenIndex { position1 := position if !_rules[ruleSpacing]() { goto l0 } l2: { position3, tokenIndex3 := position, tokenIndex { position4 := position if !_rules[ruleIdentifier]() { goto l3 } { add(ruleAction0, position) } { position6 := position if buffer[position] != rune('=') { goto l3 } position++ if !_rules[ruleSpacing]() { goto l3 } add(ruleEquals, position6) } if !_rules[rulePipeline]() { goto l3 } add(ruleMacroDef, position4) } { position7 := position if buffer[position] != rune(';') { goto l3 } position++ if !_rules[ruleSpacing]() { goto l3 } add(ruleSemicolon, position7) } goto l2 l3: position, tokenIndex = position3, tokenIndex3 } if !_rules[rulePipeline]() { goto l0 } { position8 := position { position9, tokenIndex9 := position, tokenIndex if !matchDot() { goto l9 } goto l0 l9: position, tokenIndex = position9, tokenIndex9 } add(ruleEOF, position8) } add(ruleGrammar, position1) } return true l0: position, tokenIndex = position0, tokenIndex0 return false }, /* 1 MacroDef <- <(Identifier Action0 Equals Pipeline)> */ nil, /* 2 Pipeline <- <(Action1 Expression (Pipe Expression)* Action2)> */ func() bool { position11, tokenIndex11 := position, tokenIndex { position12 := position { add(ruleAction1, position) } if !_rules[ruleExpression]() { goto l11 } l14: { position15, tokenIndex15 := position, tokenIndex { position16 := position if buffer[position] != rune('|') { goto l15 } position++ if !_rules[ruleSpacing]() { goto l15 } add(rulePipe, position16) } if !_rules[ruleExpression]() { goto l15 } goto l14 l15: position, tokenIndex = position15, tokenIndex15 } { add(ruleAction2, position) } add(rulePipeline, position12) } return true l11: position, tokenIndex = position11, tokenIndex11 return false }, /* 3 Expression <- <(FunctionCall / Nesting)> */ func() bool { position18, tokenIndex18 := position, tokenIndex { position19 := position { position20, tokenIndex20 := position, tokenIndex { position22 := position { position23, tokenIndex23 := position, tokenIndex if !_rules[ruleIdentifier]() { goto l24 } goto l23 l24: position, tokenIndex = position23, tokenIndex23 { position25 := position { position26 := position { position27 := position { position28, tokenIndex28 := position, tokenIndex if buffer[position] != rune('<') { goto l29 } position++ if buffer[position] != rune('=') { goto l29 } position++ goto l28 l29: position, tokenIndex = position28, tokenIndex28 if buffer[position] != rune('>') { goto l30 } position++ if buffer[position] != rune('=') { goto l30 } position++ goto l28 l30: position, tokenIndex = position28, tokenIndex28 { switch buffer[position] { case '>': if buffer[position] != rune('>') { goto l21 } position++ break case '!': if buffer[position] != rune('!') { goto l21 } position++ if buffer[position] != rune('=') { goto l21 } position++ break case '=': if buffer[position] != rune('=') { goto l21 } position++ if buffer[position] != rune('=') { goto l21 } position++ break default: if buffer[position] != rune('<') { goto l21 } position++ break } } } l28: add(ruleOperatorSymbols, position27) } add(rulePegText, position26) } if !_rules[ruleSpacing]() { goto l21 } add(ruleOperator, position25) } } l23: { add(ruleAction3, position) } l33: { position34, tokenIndex34 := position, tokenIndex { position35 := position { position36, tokenIndex36 := position, tokenIndex { position38 := position if !_rules[ruleIdentifier]() { goto l36 } { add(ruleAction9, position) } { position40 := position if buffer[position] != rune(':') { goto l36 } position++ if !_rules[ruleSpacing]() { goto l36 } add(ruleColon, position40) } add(ruleKeywordSpecifier, position38) } goto l37 l36: position, tokenIndex = position36, tokenIndex36 } l37: { position41, tokenIndex41 := position, tokenIndex { position43 := position { position44 := position { position45, tokenIndex45 := position, tokenIndex { position47 := position { position48, tokenIndex48 := position, tokenIndex if buffer[position] != rune('t') { goto l49 } position++ goto l48 l49: position, tokenIndex = position48, tokenIndex48 if buffer[position] != rune('T') { goto l46 } position++ } l48: { position50, tokenIndex50 := position, tokenIndex if buffer[position] != rune('r') { goto l51 } position++ goto l50 l51: position, tokenIndex = position50, tokenIndex50 if buffer[position] != rune('R') { goto l46 } position++ } l50: { position52, tokenIndex52 := position, tokenIndex if buffer[position] != rune('u') { goto l53 } position++ goto l52 l53: position, tokenIndex = position52, tokenIndex52 if buffer[position] != rune('U') { goto l46 } position++ } l52: { position54, tokenIndex54 := position, tokenIndex if buffer[position] != rune('e') { goto l55 } position++ goto l54 l55: position, tokenIndex = position54, tokenIndex54 if buffer[position] != rune('E') { goto l46 } position++ } l54: add(ruleTrue, position47) } goto l45 l46: position, tokenIndex = position45, tokenIndex45 { position56 := position { position57, tokenIndex57 := position, tokenIndex if buffer[position] != rune('f') { goto l58 } position++ goto l57 l58: position, tokenIndex = position57, tokenIndex57 if buffer[position] != rune('F') { goto l42 } position++ } l57: { position59, tokenIndex59 := position, tokenIndex if buffer[position] != rune('a') { goto l60 } position++ goto l59 l60: position, tokenIndex = position59, tokenIndex59 if buffer[position] != rune('A') { goto l42 } position++ } l59: { position61, tokenIndex61 := position, tokenIndex if buffer[position] != rune('l') { goto l62 } position++ goto l61 l62: position, tokenIndex = position61, tokenIndex61 if buffer[position] != rune('L') { goto l42 } position++ } l61: { position63, tokenIndex63 := position, tokenIndex if buffer[position] != rune('s') { goto l64 } position++ goto l63 l64: position, tokenIndex = position63, tokenIndex63 if buffer[position] != rune('S') { goto l42 } position++ } l63: { position65, tokenIndex65 := position, tokenIndex if buffer[position] != rune('e') { goto l66 } position++ goto l65 l66: position, tokenIndex = position65, tokenIndex65 if buffer[position] != rune('E') { goto l42 } position++ } l65: add(ruleFalse, position56) } } l45: add(rulePegText, position44) } { position67, tokenIndex67 := position, tokenIndex if !_rules[rulePatternChars]() { goto l67 } goto l42 l67: position, tokenIndex = position67, tokenIndex67 } if !_rules[ruleSpacing]() { goto l42 } add(ruleBoolean, position43) } { add(ruleAction5, position) } goto l41 l42: position, tokenIndex = position41, tokenIndex41 { position70 := position { position71 := position { position72, tokenIndex72 := position, tokenIndex { position74 := position if buffer[position] != rune('-') { goto l72 } position++ add(ruleMinus, position74) } goto l73 l72: position, tokenIndex = position72, tokenIndex72 } l73: { position75, tokenIndex75 := position, tokenIndex { position77 := position { position78, tokenIndex78 := position, tokenIndex if !_rules[ruleIntegralNumber]() { goto l78 } goto l79 l78: position, tokenIndex = position78, tokenIndex78 } l79: if buffer[position] != rune('.') { goto l76 } position++ if !_rules[ruleIntegralNumber]() { goto l76 } add(ruleFloatingNumber, position77) } goto l75 l76: position, tokenIndex = position75, tokenIndex75 if !_rules[ruleIntegralNumber]() { goto l69 } } l75: add(rulePegText, position71) } { position80, tokenIndex80 := position, tokenIndex if !_rules[rulePatternChars]() { goto l80 } goto l69 l80: position, tokenIndex = position80, tokenIndex80 } if !_rules[ruleSpacing]() { goto l69 } add(ruleNumber, position70) } { add(ruleAction6, position) } goto l41 l69: position, tokenIndex = position41, tokenIndex41 { switch buffer[position] { case '(': if !_rules[ruleNesting]() { goto l34 } break case '"': { position83 := position if !_rules[ruleQuoteChar]() { goto l34 } { position84 := position l85: { position86, tokenIndex86 := position, tokenIndex { position87, tokenIndex87 := position, tokenIndex if buffer[position] != rune('"') { goto l87 } position++ goto l86 l87: position, tokenIndex = position87, tokenIndex87 } if !matchDot() { goto l86 } goto l85 l86: position, tokenIndex = position86, tokenIndex86 } add(rulePegText, position84) } if !_rules[ruleQuoteChar]() { goto l34 } if !_rules[ruleSpacing]() { goto l34 } add(ruleStringLiteral, position83) } { add(ruleAction8, position) } break default: { position89 := position { position90 := position if !_rules[rulePatternChars]() { goto l34 } l91: { position92, tokenIndex92 := position, tokenIndex if !_rules[rulePatternChars]() { goto l92 } goto l91 l92: position, tokenIndex = position92, tokenIndex92 } add(rulePegText, position90) } if !_rules[ruleSpacing]() { goto l34 } add(rulePattern, position89) } { add(ruleAction7, position) } break } } } l41: add(ruleArgument, position35) } goto l33 l34: position, tokenIndex = position34, tokenIndex34 } { add(ruleAction4, position) } add(ruleFunctionCall, position22) } goto l20 l21: position, tokenIndex = position20, tokenIndex20 if !_rules[ruleNesting]() { goto l18 } } l20: add(ruleExpression, position19) } return true l18: position, tokenIndex = position18, tokenIndex18 return false }, /* 4 FunctionCall <- <((Identifier / Operator) Action3 Argument* Action4)> */ nil, /* 5 Argument <- <(KeywordSpecifier? ((Boolean Action5) / (Number Action6) / ((&('(') Nesting) | (&('"') (StringLiteral Action8)) | (&('$' | '*' | ',' | '-' | '.' | '/' | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '?' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z' | '[' | '\\' | ']' | '^' | '_' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z' | '{' | '}') (Pattern Action7)))))> */ nil, /* 6 KeywordSpecifier <- <(Identifier Action9 Colon)> */ nil, /* 7 Nesting <- <(LParenthesis Pipeline RParenthesis)> */ func() bool { position98, tokenIndex98 := position, tokenIndex { position99 := position { position100 := position if buffer[position] != rune('(') { goto l98 } position++ if !_rules[ruleSpacing]() { goto l98 } add(ruleLParenthesis, position100) } if !_rules[rulePipeline]() { goto l98 } { position101 := position if buffer[position] != rune(')') { goto l98 } position++ if !_rules[ruleSpacing]() { goto l98 } add(ruleRParenthesis, position101) } add(ruleNesting, position99) } return true l98: position, tokenIndex = position98, tokenIndex98 return false }, /* 8 Spacing <- <((&('#') Comment) | (&('\n' | '\r') EOL) | (&('\t' | ' ') Space))*> */ func() bool { { position103 := position l104: { position105, tokenIndex105 := position, tokenIndex { switch buffer[position] { case '#': { position107 := position { position108 := position if buffer[position] != rune('#') { goto l105 } position++ add(ruleCommentStart, position108) } l109: { position110, tokenIndex110 := position, tokenIndex { position111, tokenIndex111 := position, tokenIndex if !_rules[ruleEOL]() { goto l111 } goto l110 l111: position, tokenIndex = position111, tokenIndex111 } if !matchDot() { goto l110 } goto l109 l110: position, tokenIndex = position110, tokenIndex110 } add(ruleComment, position107) } break case '\n', '\r': if !_rules[ruleEOL]() { goto l105 } break default: { position112 := position { position113, tokenIndex113 := position, tokenIndex if buffer[position] != rune(' ') { goto l114 } position++ goto l113 l114: position, tokenIndex = position113, tokenIndex113 if buffer[position] != rune('\t') { goto l105 } position++ } l113: add(ruleSpace, position112) } break } } goto l104 l105: position, tokenIndex = position105, tokenIndex105 } add(ruleSpacing, position103) } return true }, /* 9 Space <- <(' ' / '\t')> */ nil, /* 10 EOL <- <(('\r' '\n') / '\n' / '\r')> */ func() bool { position116, tokenIndex116 := position, tokenIndex { position117 := position { position118, tokenIndex118 := position, tokenIndex if buffer[position] != rune('\r') { goto l119 } position++ if buffer[position] != rune('\n') { goto l119 } position++ goto l118 l119: position, tokenIndex = position118, tokenIndex118 if buffer[position] != rune('\n') { goto l120 } position++ goto l118 l120: position, tokenIndex = position118, tokenIndex118 if buffer[position] != rune('\r') { goto l116 } position++ } l118: add(ruleEOL, position117) } return true l116: position, tokenIndex = position116, tokenIndex116 return false }, /* 11 Comment <- <(CommentStart (!EOL .)*)> */ nil, /* 12 CommentStart <- <'#'> */ nil, /* 13 Identifier <- <(<(IdentifierStart IdentifierChars*)> Spacing)> */ func() bool { position123, tokenIndex123 := position, tokenIndex { position124 := position { position125 := position if !_rules[ruleIdentifierStart]() { goto l123 } l126: { position127, tokenIndex127 := position, tokenIndex if !_rules[ruleIdentifierChars]() { goto l127 } goto l126 l127: position, tokenIndex = position127, tokenIndex127 } add(rulePegText, position125) } if !_rules[ruleSpacing]() { goto l123 } add(ruleIdentifier, position124) } return true l123: position, tokenIndex = position123, tokenIndex123 return false }, /* 14 IdentifierStart <- <((&('_') '_') | (&('A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z') [A-Z]) | (&('a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z') [a-z]))> */ func() bool { position128, tokenIndex128 := position, tokenIndex { position129 := position { switch buffer[position] { case '_': if buffer[position] != rune('_') { goto l128 } position++ break case 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z': if c := buffer[position]; c < rune('A') || c > rune('Z') { goto l128 } position++ break default: if c := buffer[position]; c < rune('a') || c > rune('z') { goto l128 } position++ break } } add(ruleIdentifierStart, position129) } return true l128: position, tokenIndex = position128, tokenIndex128 return false }, /* 15 IdentifierChars <- <((&('\\') '\\') | (&('/') '/') | (&('-') '-') | (&('.') '.') | (&('0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9') [0-9]) | (&('A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z' | '_' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z') IdentifierStart))> */ func() bool { position131, tokenIndex131 := position, tokenIndex { position132 := position { switch buffer[position] { case '\\': if buffer[position] != rune('\\') { goto l131 } position++ break case '/': if buffer[position] != rune('/') { goto l131 } position++ break case '-': if buffer[position] != rune('-') { goto l131 } position++ break case '.': if buffer[position] != rune('.') { goto l131 } position++ break case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': if c := buffer[position]; c < rune('0') || c > rune('9') { goto l131 } position++ break default: if !_rules[ruleIdentifierStart]() { goto l131 } break } } add(ruleIdentifierChars, position132) } return true l131: position, tokenIndex = position131, tokenIndex131 return false }, /* 16 Operator <- <(<OperatorSymbols> Spacing)> */ nil, /* 17 OperatorSymbols <- <(('<' '=') / ('>' '=') / ((&('>') '>') | (&('!') ('!' '=')) | (&('=') ('=' '=')) | (&('<') '<')))> */ nil, /* 18 Boolean <- <(<(True / False)> !PatternChars Spacing)> */ nil, /* 19 True <- <(('t' / 'T') ('r' / 'R') ('u' / 'U') ('e' / 'E'))> */ nil, /* 20 False <- <(('f' / 'F') ('a' / 'A') ('l' / 'L') ('s' / 'S') ('e' / 'E'))> */ nil, /* 21 Number <- <(<(Minus? (FloatingNumber / IntegralNumber))> !PatternChars Spacing)> */ nil, /* 22 IntegralNumber <- <[0-9]+> */ func() bool { position140, tokenIndex140 := position, tokenIndex { position141 := position if c := buffer[position]; c < rune('0') || c > rune('9') { goto l140 } position++ l142: { position143, tokenIndex143 := position, tokenIndex if c := buffer[position]; c < rune('0') || c > rune('9') { goto l143 } position++ goto l142 l143: position, tokenIndex = position143, tokenIndex143 } add(ruleIntegralNumber, position141) } return true l140: position, tokenIndex = position140, tokenIndex140 return false }, /* 23 FloatingNumber <- <(IntegralNumber? '.' IntegralNumber)> */ nil, /* 24 Minus <- <'-'> */ nil, /* 25 StringLiteral <- <(QuoteChar <(!'"' .)*> QuoteChar Spacing)> */ nil, /* 26 QuoteChar <- <'"'> */ func() bool { position147, tokenIndex147 := position, tokenIndex { position148 := position if buffer[position] != rune('"') { goto l147 } position++ add(ruleQuoteChar, position148) } return true l147: position, tokenIndex = position147, tokenIndex147 return false }, /* 27 Pattern <- <(<PatternChars+> Spacing)> */ nil, /* 28 PatternChars <- <(IdentifierChars / GlobSymbols)> */ func() bool { position150, tokenIndex150 := position, tokenIndex { position151 := position { position152, tokenIndex152 := position, tokenIndex if !_rules[ruleIdentifierChars]() { goto l153 } goto l152 l153: position, tokenIndex = position152, tokenIndex152 { position154 := position { switch buffer[position] { case '$': if buffer[position] != rune('$') { goto l150 } position++ break case '^': if buffer[position] != rune('^') { goto l150 } position++ break case ',': if buffer[position] != rune(',') { goto l150 } position++ break case '?': if buffer[position] != rune('?') { goto l150 } position++ break case '*': if buffer[position] != rune('*') { goto l150 } position++ break case ']': if buffer[position] != rune(']') { goto l150 } position++ break case '[': if buffer[position] != rune('[') { goto l150 } position++ break case '}': if buffer[position] != rune('}') { goto l150 } position++ break default: if buffer[position] != rune('{') { goto l150 } position++ break } } add(ruleGlobSymbols, position154) } } l152: add(rulePatternChars, position151) } return true l150: position, tokenIndex = position150, tokenIndex150 return false }, /* 29 GlobSymbols <- <((&('$') '$') | (&('^') '^') | (&(',') ',') | (&('?') '?') | (&('*') '*') | (&(']') ']') | (&('[') '[') | (&('}') '}') | (&('{') '{'))> */ nil, /* 30 Semicolon <- <(';' Spacing)> */ nil, /* 31 Equals <- <('=' Spacing)> */ nil, /* 32 Pipe <- <('|' Spacing)> */ nil, /* 33 LParenthesis <- <('(' Spacing)> */ nil, /* 34 RParenthesis <- <(')' Spacing)> */ nil, /* 35 Colon <- <(':' Spacing)> */ nil, /* 36 EOF <- <!.> */ nil, /* 38 Action0 <- <{ p.newMacro(text) }> */ nil, /* 39 Action1 <- <{ p.newPipeline() }> */ nil, /* 40 Action2 <- <{ p.endPipeline() }> */ nil, /* 41 Action3 <- <{ p.newExpression(text) }> */ nil, /* 42 Action4 <- <{ p.endExpression() }> */ nil, /* 43 Action5 <- <{ p.newBooleanArgument(text) }> */ nil, /* 44 Action6 <- <{ p.newNumericArgument(text) }> */ nil, /* 45 Action7 <- <{ p.newPatternArgument(text) }> */ nil, /* 46 Action8 <- <{ p.newStringLiteralArgument(text) }> */ nil, /* 47 Action9 <- <{ p.newKeywordArgument(text) }> */ nil, nil, } p.rules = _rules }
m3db/m3db
src/query/parser/m3ql/grammar.peg.go
GO
apache-2.0
37,003
<?php /** * The Campaigns endpoint. This is a campaign of type SMS. * * @link https://github.com/PortaText/docs/wiki/REST-API#api_campaigns Campaigns endpoint. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache 2.0 * @author Marcelo Gornstein <marcelog@portatext.com> * @copyright 2015 PortaText */ namespace PortaText\Command\Api; use PortaText\Command\Base; /** * The Campaigns endpoint. This is a campaign of type SMS. */ class SmsCampaign extends Campaigns { /** * Specifies source sms service. * * @param string $serviceId SMS Service ID. * * @return PortaText\Command\ICommand */ public function fromService($serviceId) { return $this->setArgument("service_id", $serviceId); } /** * Sets the template id to use. * * @param integer $templateId Use the given template as the message body. * @param array $variables Variables to use in template. * * @return PortaText\Command\ICommand */ public function useTemplate($templateId, array $variables = array()) { $this->setSetting("template_id", $templateId); return $this->setSetting("variables", $variables); } /** * Sets the message text. * * @param string $text Message text. * * @return PortaText\Command\ICommand */ public function text($text) { return $this->setSetting("text", $text); } /** * Standard constructor. * */ public function __construct() { parent::__construct(); $this->setArgument("type", "sms"); } }
PortaText/php-sdk
src/PortaText/Command/Api/SmsCampaign.php
PHP
apache-2.0
1,615
/** Copyright 2017 Andrea "Stock" Stocchero Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * Contains the {@link org.pepstock.charba.client.annotation.AnnotationPlugin#ID} plugin elements interfaces to use in the callbacks and events. * * @author Andrea "Stock" Stocchero * */ package org.pepstock.charba.client.annotation.elements;
pepstock-org/Charba
src/org/pepstock/charba/client/annotation/elements/package-info.java
Java
apache-2.0
881
# # Copyright (C) 2010-2016 dtk contributors # # This file is part of the dtk 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. # module DTK::Client; class Operation::Service::TaskStatus::StreamMode class Element class TaskStart < self def self.get(task_status_handle, opts = {}) opts_get = { :start_index => 0, :end_index => 0 }.merge(opts) get_task_status_elements(task_status_handle, :task_start, opts_get) end def render return if @ignore_stage_level_info msg = "start '#{field?(:display_name) || 'Workflow'}'" render_line msg, :bracket => true, :started_at => field?(:started_at) render_empty_lines 2 end end end end; end
dtk/dtk-client
lib/client/operation/service/task_status/stream_mode/element/task_start.rb
Ruby
apache-2.0
1,243
/* Copyright 2016, 2020 Nationale-Nederlanden, 2020-2021 WeAreFrank! 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 nl.nn.adapterframework.pipes; import java.io.ByteArrayOutputStream; import java.io.IOException; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.Adapter; import nl.nn.adapterframework.core.PipeLineSession; import nl.nn.adapterframework.core.PipeRunException; import nl.nn.adapterframework.core.PipeRunResult; import nl.nn.adapterframework.doc.IbisDoc; import nl.nn.adapterframework.http.RestListenerUtils; import nl.nn.adapterframework.soap.WsdlGenerator; import nl.nn.adapterframework.stream.Message; import nl.nn.adapterframework.util.StreamUtil; /** * Generate WSDL of parent or specified adapter. * * @author Jaco de Groot */ public class WsdlGeneratorPipe extends FixedForwardPipe { private String from = "parent"; @Override public void configure() throws ConfigurationException { super.configure(); if (!"parent".equals(getFrom()) && !"input".equals(getFrom())) { throw new ConfigurationException("from should either be parent or input"); } } @Override public PipeRunResult doPipe(Message message, PipeLineSession session) throws PipeRunException { String result = null; Adapter adapter; try { if ("input".equals(getFrom())) { String adapterName = message.asString(); adapter = getAdapter().getConfiguration().getIbisManager().getRegisteredAdapter(adapterName); if (adapter == null) { throw new PipeRunException(this, "Could not find adapter: " + adapterName); } } else { adapter = getPipeLine().getAdapter(); } } catch (IOException e) { throw new PipeRunException(this, "Could not determine adapter name", e); } try { String generationInfo = "at " + RestListenerUtils.retrieveRequestURL(session); WsdlGenerator wsdl = new WsdlGenerator(adapter.getPipeLine(), generationInfo); wsdl.init(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); wsdl.wsdl(outputStream, null); result = outputStream.toString(StreamUtil.DEFAULT_INPUT_STREAM_ENCODING); } catch (Exception e) { throw new PipeRunException(this, "Could not generate WSDL for adapter [" + adapter.getName() + "]", e); } return new PipeRunResult(getSuccessForward(), result); } public String getFrom() { return from; } @IbisDoc({"either parent (adapter of pipeline which contains this pipe) or input (name of adapter specified by input of pipe)", "parent"}) public void setFrom(String from) { this.from = from; } }
ibissource/iaf
core/src/main/java/nl/nn/adapterframework/pipes/WsdlGeneratorPipe.java
Java
apache-2.0
3,096
/* * #%L * Diana UI Core * %% * Copyright (C) 2014 Diana UI * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.dianaui.universal.core.client.ui.html; import com.dianaui.universal.core.client.ui.base.AbstractTextWidget; import com.dianaui.universal.core.client.ui.constants.ElementTags; import com.google.gwt.dom.client.Document; /** * Simple {@code <strong>} tag to emphasize words * * @author Joshua Godi */ public class Strong extends AbstractTextWidget { public Strong() { super(Document.get().createElement(ElementTags.STRONG)); } public Strong(final String text) { this(); setHTML(text); } }
dianaui/dianaui-universal
core/src/main/java/com/dianaui/universal/core/client/ui/html/Strong.java
Java
apache-2.0
1,186
/* * #%L * Diana UI Core * %% * Copyright (C) 2014 Diana UI * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.dianaui.universal.core.client.ui.constants; import com.dianaui.universal.core.client.ui.base.helper.EnumHelper; import com.google.gwt.dom.client.Style; /** * Only relevant to horizontal forms * * @author Xiaodong Sun */ public enum FormGroupSize implements Size, Style.HasCssName { LARGE("form-group-lg"), DEFAULT(""), SMALL("form-group-sm"),; private final String cssClass; private FormGroupSize(final String cssClass) { this.cssClass = cssClass; } @Override public String getCssName() { return cssClass; } public static FormGroupSize fromStyleName(final String styleName) { return EnumHelper.fromStyleName(styleName, FormGroupSize.class, DEFAULT); } }
dianaui/dianaui-universal
core/src/main/java/com/dianaui/universal/core/client/ui/constants/FormGroupSize.java
Java
apache-2.0
1,385
# frozen_string_literal: true require 'github_request' class GithubPostReceiveHook SUBSCRIBE_NAME = "web" def initialize(repository, oauth_token) @repository = repository @oauth_token = oauth_token @root_url = "#{repository.base_api_url}/hooks" @hook_url = "#{repository.base_api_url}/hooks/#{repository.github_post_receive_hook_id}" @receive_url = Rails.application.routes.url_helpers.pull_request_build_url @interested_events = @repository.interested_github_events @subscribe_args = {:name => "web", :config => {:url => @receive_url}, :events => @interested_events, :active => true} end def subscribe! if @repository.github_post_receive_hook_id update_repository_hook! else synchronize_or_create! end end private def update_repository_hook! begin GithubRequest.patch(@hook_url, @subscribe_args, @oauth_token) rescue GithubRequest::ResponseError => e if e.response.class == Net::HTTPNotFound create_hook else raise e end end end def synchronize_or_create! begin response_body = GithubRequest.get(@root_url, @oauth_token) existing_hooks = JSON.parse(response_body) existing_subscription = existing_hooks.detect do |hook| hook["active"] && hook["events"] == @interested_events && hook["config"]["url"] == @receive_url end if existing_subscription @repository.update_attributes(:github_post_receive_hook_id => existing_subscription["id"]) return response_body end rescue GithubRequest::ResponseError Rails.logger.info("Failed to get hooks for #{@root_url}") end create_hook end def create_hook GithubRequest.post(@root_url, @subscribe_args, @oauth_token) end end
square/kochiku
lib/github_post_receive_hook.rb
Ruby
apache-2.0
1,783
# frozen_string_literal: true # rubocop:disable Layout/LineLength # == Schema Information # # Table name: form_items # # id :uuid not null, primary key # all_levels_required :boolean default(FALSE), not null # ancestry :text # ancestry_depth :integer not null # default :string # disabled :boolean default(FALSE), not null # display_if :string default("always"), not null # group_hint_translations :jsonb # group_item_name_translations :jsonb # group_name_translations :jsonb # hidden :boolean default(FALSE), not null # one_screen :boolean # rank :integer not null # read_only :boolean # repeatable :boolean # required :boolean default(FALSE), not null # type :string(255) not null # created_at :datetime not null # updated_at :datetime not null # form_id :uuid not null # form_old_id :integer # mission_id :uuid # old_id :integer # question_id :uuid # question_old_id :integer # # Indexes # # index_form_items_on_ancestry (ancestry) # index_form_items_on_form_id (form_id) # index_form_items_on_form_id_and_question_id (form_id,question_id) UNIQUE # index_form_items_on_mission_id (mission_id) # index_form_items_on_question_id (question_id) # # Foreign Keys # # form_items_form_id_fkey (form_id => forms.id) ON DELETE => restrict ON UPDATE => restrict # form_items_mission_id_fkey (mission_id => missions.id) ON DELETE => restrict ON UPDATE => restrict # form_items_question_id_fkey (question_id => questions.id) ON DELETE => restrict ON UPDATE => restrict # # rubocop:enable Layout/LineLength require "rails_helper" describe Questioning do it "mission should get copied from question on creation" do f = create(:form, question_types: %w[integer], mission: get_mission) expect(f.questionings[0].mission).to eq(get_mission) end describe "normalization" do # Run valid? to trigger normalization let(:q_attrs) { {} } let(:question) { create(:question, q_attrs) } let(:qing) { build(:questioning, submitted.merge(question: question)).tap(&:valid?) } subject { submitted.keys.index_with { |k| qing.send(k) }.to_h } describe "hidden/disabled/required/read_only" do context do let(:submitted) { {hidden: true, disabled: false, required: true, read_only: false} } it { is_expected.to eq(hidden: true, disabled: false, required: false, read_only: false) } end context do let(:submitted) { {hidden: false, disabled: true, required: true, read_only: false} } it { is_expected.to eq(hidden: false, disabled: true, required: true, read_only: false) } end context do let(:submitted) { {hidden: true, disabled: true, required: false, read_only: false} } it { is_expected.to eq(hidden: true, disabled: true, required: false, read_only: false) } end context do let(:submitted) { {hidden: false, disabled: false, required: true, read_only: false} } it { is_expected.to eq(hidden: false, disabled: false, required: true, read_only: false) } end context do let(:submitted) { {hidden: false, disabled: false, required: true, read_only: true} } it { is_expected.to eq(hidden: false, disabled: false, required: false, read_only: true) } end context do let(:submitted) { {hidden: false, disabled: false, required: false, read_only: true} } it { is_expected.to eq(hidden: false, disabled: false, required: false, read_only: true) } end end describe "preload_last_saved and default" do context do let(:submitted) { {preload_last_saved: false, default: "foo"} } it { is_expected.to eq(preload_last_saved: false, default: "foo") } end context do let(:submitted) { {preload_last_saved: true, default: "foo"} } it { is_expected.to eq(preload_last_saved: true, default: nil) } end end describe "question metadata and hidden/disabled/required" do context do let(:q_attrs) { {qtype_name: "datetime", metadata_type: "formstart"} } let(:submitted) { {required: true, hidden: false, disabled: false} } it { is_expected.to eq(required: false, hidden: true, disabled: false) } end context do let(:q_attrs) { {qtype_name: "datetime", metadata_type: "formstart"} } let(:submitted) { {required: "", hidden: true, disabled: true} } it { is_expected.to eq(required: false, hidden: true, disabled: true) } end context do let(:q_attrs) { {qtype_name: "datetime", metadata_type: ""} } let(:submitted) { {required: true, disabled: false} } it { is_expected.to eq(required: true, disabled: false) } end end describe "question metadata and condition" do let(:condition) { build(:condition) } context "not adding a metadata_type" do let(:q_attrs) { {qtype_name: "datetime", metadata_type: nil} } let(:submitted) { {display_conditions: [condition]} } it "should not destroy existing conditions" do is_expected.to eq(display_conditions: [condition]) end end context "add a metadata_type with an existing condition" do let(:q_attrs) { {qtype_name: "datetime", metadata_type: "formstart"} } let(:submitted) { {display_conditions: [condition]} } it "should destroy existing conditions" do is_expected.to eq(display_conditions: []) expect(condition).to be_destroyed end end context "add a metadata_type with no existing conditions" do let(:q_attrs) { {qtype_name: "datetime", metadata_type: "formstart"} } let(:submitted) { {display_conditions: []} } it "should not change the display conditions" do is_expected.to eq(display_conditions: []) end end end describe "all_levels_required" do let(:question) { form.c[0].question } context "multilevel, required question" do let(:form) { create(:form, question_types: %w[multilevel_select_one]) } let(:submitted) { {all_levels_required: true, required: true} } it "should leave all_levels_required alone" do is_expected.to eq(all_levels_required: true, required: true) end end context "multilevel, non-required question" do let(:form) { create(:form, question_types: %w[multilevel_select_one]) } let(:submitted) { {all_levels_required: true, required: false} } it "should reset all_levels_required" do is_expected.to eq(all_levels_required: false, required: false) end end context "non-multilevel question" do let(:form) { create(:form, question_types: %w[select_one]) } let(:submitted) { {all_levels_required: true, required: true} } it "should reset all_levels_required" do is_expected.to eq(all_levels_required: false, required: true) end end context "non-select question" do let(:form) { create(:form, question_types: %w[integer]) } let(:submitted) { {all_levels_required: true, required: true} } it "should reset all_levels_required" do is_expected.to eq(all_levels_required: false, required: true) end end end end describe "validation" do let(:questioning) { build(:questioning, default: "Item: calc($Foo + 4) ") } # Detailed testing of this validator is in own file. describe "DynamicPatternValidator" do it "is hooked up properly" do expect(questioning).to be_invalid expect(questioning.errors[:default].join).to match(/must surround/) end end it "should fail properly when there is no qtype" do questioning.qtype_name = nil expect { questioning.save }.not_to raise_error end end end
thecartercenter/elmo
spec/models/questioning_spec.rb
Ruby
apache-2.0
8,424
/* * 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 fixture.simple; import java.util.List; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.Named; import org.apache.isis.applib.annotation.Prototype; import org.apache.isis.applib.fixturescripts.FixtureResult; import org.apache.isis.applib.fixturescripts.FixtureScript; import org.apache.isis.applib.fixturescripts.FixtureScripts; import org.apache.isis.applib.fixturescripts.SimpleFixtureScript; /** * Enables fixtures to be installed from the application. */ @Named("Prototyping") @DomainService(menuOrder = "20") public class SimpleObjectsFixturesService extends FixtureScripts { public SimpleObjectsFixturesService() { super("fixture.simple"); } //@Override // compatibility with core 1.5.0 public FixtureScript default0RunFixtureScript() { return findFixtureScriptFor(SimpleFixtureScript.class); } /** * Raising visibility to <tt>public</tt> so that choices are available for first param * of {@link #runFixtureScript(FixtureScript, String)}. */ @Override public List<FixtureScript> choices0RunFixtureScript() { return super.choices0RunFixtureScript(); } // ////////////////////////////////////// @Prototype @MemberOrder(sequence="20") public Object installFixturesAndReturnFirst() { final List<FixtureResult> run = findFixtureScriptFor(SimpleObjectsFixture.class).run(null); return run.get(0).getObject(); } @Prototype @MemberOrder(sequence="20") public Object instalarFixturesAlumnos() { final List<FixtureResult> run = findFixtureScriptFor(AlumnosFixture.class).run(null); return run.get(0).getObject(); } @Prototype @MemberOrder(sequence="20") public Object instalarFixturesCursos() { final List<FixtureResult> run = findFixtureScriptFor(CursosFixture.class).run(null); return run.get(0).getObject(); } }
leanddrot/isis-asistencia
fixture/src/main/java/fixture/simple/SimpleObjectsFixturesService.java
Java
apache-2.0
2,843
/* * Copyright (C) 2008 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.phonemetra.turbo.launcher; import com.phonemetra.turbo.launcher.R; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.Region; import android.graphics.Region.Op; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.TypedValue; import android.view.MotionEvent; import android.widget.TextView; public class BubbleTextView extends TextView { static final float SHADOW_LARGE_RADIUS = 4.0f; static final float SHADOW_SMALL_RADIUS = 1.75f; static final float SHADOW_Y_OFFSET = 2.0f; static final int SHADOW_LARGE_COLOUR = 0xDD000000; static final int SHADOW_SMALL_COLOUR = 0xCC000000; static final float PADDING_H = 8.0f; static final float PADDING_V = 3.0f; private int mPrevAlpha = -1; private HolographicOutlineHelper mOutlineHelper; private final Canvas mTempCanvas = new Canvas(); private final Rect mTempRect = new Rect(); private boolean mDidInvalidateForPressedState; private Bitmap mPressedOrFocusedBackground; private int mFocusedOutlineColor; private int mFocusedGlowColor; private int mPressedOutlineColor; private int mPressedGlowColor; private int mTextColor; private boolean mShadowsEnabled = true; private boolean mIsTextVisible; private boolean mBackgroundSizeChanged; private Drawable mBackground; private boolean mStayPressed; private CheckLongPressHelper mLongPressHelper; public BubbleTextView(Context context) { super(context); init(); } public BubbleTextView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public BubbleTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public void onFinishInflate() { super.onFinishInflate(); LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); setTextSize(TypedValue.COMPLEX_UNIT_PX, grid.iconTextSizePx); setTextColor(getResources().getColor(R.color.workspace_icon_text_color)); } private void init() { mLongPressHelper = new CheckLongPressHelper(this); mBackground = getBackground(); mOutlineHelper = HolographicOutlineHelper.obtain(getContext()); final Resources res = getContext().getResources(); mFocusedOutlineColor = mFocusedGlowColor = mPressedOutlineColor = mPressedGlowColor = res.getColor(R.color.outline_color); setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR); } public void applyFromShortcutInfo(ShortcutInfo info, IconCache iconCache) { LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); Bitmap b = info.getIcon(iconCache); setCompoundDrawables(null, Utilities.createIconDrawable(b), null, null); setCompoundDrawablePadding(grid.iconDrawablePaddingPx); setText(info.title); setTag(info); } @Override protected boolean setFrame(int left, int top, int right, int bottom) { if (getLeft() != left || getRight() != right || getTop() != top || getBottom() != bottom) { mBackgroundSizeChanged = true; } return super.setFrame(left, top, right, bottom); } @Override protected boolean verifyDrawable(Drawable who) { return who == mBackground || super.verifyDrawable(who); } @Override public void setTag(Object tag) { if (tag != null) { LauncherModel.checkItemInfo((ItemInfo) tag); } super.setTag(tag); } @Override protected void drawableStateChanged() { if (isPressed()) { // In this case, we have already created the pressed outline on ACTION_DOWN, // so we just need to do an invalidate to trigger draw if (!mDidInvalidateForPressedState) { setCellLayoutPressedOrFocusedIcon(); } } else { // Otherwise, either clear the pressed/focused background, or create a background // for the focused state final boolean backgroundEmptyBefore = mPressedOrFocusedBackground == null; if (!mStayPressed) { mPressedOrFocusedBackground = null; } if (isFocused()) { if (getLayout() == null) { // In some cases, we get focus before we have been layed out. Set the // background to null so that it will get created when the view is drawn. mPressedOrFocusedBackground = null; } else { mPressedOrFocusedBackground = createGlowingOutline( mTempCanvas, mFocusedGlowColor, mFocusedOutlineColor); } mStayPressed = false; setCellLayoutPressedOrFocusedIcon(); } final boolean backgroundEmptyNow = mPressedOrFocusedBackground == null; if (!backgroundEmptyBefore && backgroundEmptyNow) { setCellLayoutPressedOrFocusedIcon(); } } Drawable d = mBackground; if (d != null && d.isStateful()) { d.setState(getDrawableState()); } super.drawableStateChanged(); } /** * Draw this BubbleTextView into the given Canvas. * * @param destCanvas the canvas to draw on * @param padding the horizontal and vertical padding to use when drawing */ private void drawWithPadding(Canvas destCanvas, int padding) { final Rect clipRect = mTempRect; getDrawingRect(clipRect); // adjust the clip rect so that we don't include the text label clipRect.bottom = getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V + getLayout().getLineTop(0); // Draw the View into the bitmap. // The translate of scrollX and scrollY is necessary when drawing TextViews, because // they set scrollX and scrollY to large values to achieve centered text destCanvas.save(); destCanvas.scale(getScaleX(), getScaleY(), (getWidth() + padding) / 2, (getHeight() + padding) / 2); destCanvas.translate(-getScrollX() + padding / 2, -getScrollY() + padding / 2); destCanvas.clipRect(clipRect, Op.REPLACE); draw(destCanvas); destCanvas.restore(); } public void setGlowColor(int color) { mFocusedOutlineColor = mFocusedGlowColor = mPressedOutlineColor = mPressedGlowColor = color; } /** * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. * Responsibility for the bitmap is transferred to the caller. */ private Bitmap createGlowingOutline(Canvas canvas, int outlineColor, int glowColor) { final int padding = mOutlineHelper.mMaxOuterBlurRadius; final Bitmap b = Bitmap.createBitmap( getWidth() + padding, getHeight() + padding, Bitmap.Config.ARGB_8888); canvas.setBitmap(b); drawWithPadding(canvas, padding); mOutlineHelper.applyExtraThickExpensiveOutlineWithBlur(b, canvas, glowColor, outlineColor); canvas.setBitmap(null); return b; } @Override public boolean onTouchEvent(MotionEvent event) { // Call the superclass onTouchEvent first, because sometimes it changes the state to // isPressed() on an ACTION_UP boolean result = super.onTouchEvent(event); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // So that the pressed outline is visible immediately when isPressed() is true, // we pre-create it on ACTION_DOWN (it takes a small but perceptible amount of time // to create it) if (mPressedOrFocusedBackground == null) { mPressedOrFocusedBackground = createGlowingOutline( mTempCanvas, mPressedGlowColor, mPressedOutlineColor); } // Invalidate so the pressed state is visible, or set a flag so we know that we // have to call invalidate as soon as the state is "pressed" if (isPressed()) { mDidInvalidateForPressedState = true; setCellLayoutPressedOrFocusedIcon(); } else { mDidInvalidateForPressedState = false; } mLongPressHelper.postCheckForLongPress(); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: // If we've touched down and up on an item, and it's still not "pressed", then // destroy the pressed outline if (!isPressed()) { mPressedOrFocusedBackground = null; } mLongPressHelper.cancelLongPress(); break; } return result; } void setStayPressed(boolean stayPressed) { mStayPressed = stayPressed; if (!stayPressed) { mPressedOrFocusedBackground = null; } setCellLayoutPressedOrFocusedIcon(); } void setCellLayoutPressedOrFocusedIcon() { if (getParent() instanceof ShortcutAndWidgetContainer) { ShortcutAndWidgetContainer parent = (ShortcutAndWidgetContainer) getParent(); if (parent != null) { CellLayout layout = (CellLayout) parent.getParent(); layout.setPressedOrFocusedIcon((mPressedOrFocusedBackground != null) ? this : null); } } } void clearPressedOrFocusedBackground() { mPressedOrFocusedBackground = null; setCellLayoutPressedOrFocusedIcon(); } Bitmap getPressedOrFocusedBackground() { return mPressedOrFocusedBackground; } int getPressedOrFocusedBackgroundPadding() { return mOutlineHelper.mMaxOuterBlurRadius / 2; } @Override public void draw(Canvas canvas) { if (!mShadowsEnabled) { super.draw(canvas); return; } final Drawable background = mBackground; if (background != null) { final int scrollX = getScrollX(); final int scrollY = getScrollY(); if (mBackgroundSizeChanged) { background.setBounds(0, 0, getRight() - getLeft(), getBottom() - getTop()); mBackgroundSizeChanged = false; } if ((scrollX | scrollY) == 0) { background.draw(canvas); } else { canvas.translate(scrollX, scrollY); background.draw(canvas); canvas.translate(-scrollX, -scrollY); } } // If text is transparent, don't draw any shadow if (getCurrentTextColor() == getResources().getColor(android.R.color.transparent)) { getPaint().clearShadowLayer(); super.draw(canvas); return; } // We enhance the shadow by drawing the shadow twice getPaint().setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR); super.draw(canvas); canvas.save(Canvas.CLIP_SAVE_FLAG); canvas.clipRect(getScrollX(), getScrollY() + getExtendedPaddingTop(), getScrollX() + getWidth(), getScrollY() + getHeight(), Region.Op.INTERSECT); getPaint().setShadowLayer(SHADOW_SMALL_RADIUS, 0.0f, 0.0f, SHADOW_SMALL_COLOUR); super.draw(canvas); canvas.restore(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (mBackground != null) mBackground.setCallback(this); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mBackground != null) mBackground.setCallback(null); } @Override public void setTextColor(int color) { mTextColor = color; super.setTextColor(color); } public void setShadowsEnabled(boolean enabled) { mShadowsEnabled = enabled; getPaint().clearShadowLayer(); invalidate(); } public void setTextVisibility(boolean visible) { Resources res = getResources(); if (visible) { super.setTextColor(mTextColor); } else { super.setTextColor(res.getColor(android.R.color.transparent)); } mIsTextVisible = visible; } public boolean isTextVisible() { return mIsTextVisible; } @Override protected boolean onSetAlpha(int alpha) { if (mPrevAlpha != alpha) { mPrevAlpha = alpha; super.onSetAlpha(alpha); } return true; } @Override public void cancelLongPress() { super.cancelLongPress(); mLongPressHelper.cancelLongPress(); } }
Phonemetra/TurboLauncher
app/src/main/java/com/phonemetra/turbo/launcher/BubbleTextView.java
Java
apache-2.0
13,912
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.frauddetector.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.frauddetector.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * DeleteEventsByEventTypeRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DeleteEventsByEventTypeRequestProtocolMarshaller implements Marshaller<Request<DeleteEventsByEventTypeRequest>, DeleteEventsByEventTypeRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("AWSHawksNestServiceFacade.DeleteEventsByEventType").serviceName("AmazonFraudDetector").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public DeleteEventsByEventTypeRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<DeleteEventsByEventTypeRequest> marshall(DeleteEventsByEventTypeRequest deleteEventsByEventTypeRequest) { if (deleteEventsByEventTypeRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<DeleteEventsByEventTypeRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller( SDK_OPERATION_BINDING, deleteEventsByEventTypeRequest); protocolMarshaller.startMarshalling(); DeleteEventsByEventTypeRequestMarshaller.getInstance().marshall(deleteEventsByEventTypeRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-frauddetector/src/main/java/com/amazonaws/services/frauddetector/model/transform/DeleteEventsByEventTypeRequestProtocolMarshaller.java
Java
apache-2.0
2,836
/* * 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.jackrabbit.oak.sling; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import javax.jcr.Repository; import org.apache.jackrabbit.oak.api.ContentRepository; import org.apache.jackrabbit.oak.spi.security.SecurityProvider; import org.apache.sling.jcr.api.SlingRepository; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; public class Activator implements BundleActivator, ServiceTrackerCustomizer { private BundleContext context; private ScheduledExecutorService executor; private SecurityProvider securityProvider; private ServiceTracker tracker; private final Map<ServiceReference, ServiceRegistration> jcrRepositories = new HashMap<ServiceReference, ServiceRegistration>(); private final Map<ServiceReference, ServiceRegistration> slingRepositories = new HashMap<ServiceReference, ServiceRegistration>(); //-----------------------------------------------------< BundleActivator >-- @Override public void start(BundleContext bundleContext) throws Exception { context = bundleContext; executor = Executors.newScheduledThreadPool(1); securityProvider = null; // TODO tracker = new ServiceTracker( context, ContentRepository.class.getName(), this); tracker.open(); } @Override public void stop(BundleContext bundleContext) throws Exception { tracker.close(); executor.shutdown(); } //--------------------------------------------< ServiceTrackerCustomizer >-- @Override public Object addingService(ServiceReference reference) { Object service = context.getService(reference); if (service instanceof ContentRepository) { SlingRepository repository = new SlingRepositoryImpl( (ContentRepository) service, executor, securityProvider); jcrRepositories.put(reference, context.registerService( Repository.class.getName(), repository, new Properties())); slingRepositories.put(reference, context.registerService( SlingRepository.class.getName(), repository, new Properties())); return service; } else { context.ungetService(reference); return null; } } @Override public void modifiedService(ServiceReference reference, Object service) { } @Override public void removedService(ServiceReference reference, Object service) { slingRepositories.get(reference).unregister(); jcrRepositories.get(reference).unregister(); context.ungetService(reference); } }
tteofili/jackrabbit-oak
oak-sling/src/main/java/org/apache/jackrabbit/oak/sling/Activator.java
Java
apache-2.0
3,841
/* * Copyright 1999-2101 Alibaba Group. * * 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.alibaba.fastjson.parser; /** * @author wenshao[szujobs@hotmail.com] */ public class JSONToken { // public final static int ERROR = 1; // public final static int LITERAL_INT = 2; // public final static int LITERAL_FLOAT = 3; // public final static int LITERAL_STRING = 4; // public final static int LITERAL_ISO8601_DATE = 5; public final static int TRUE = 6; // public final static int FALSE = 7; // public final static int NULL = 8; // public final static int NEW = 9; // public final static int LPAREN = 10; // ("("), // public final static int RPAREN = 11; // (")"), // public final static int LBRACE = 12; // ("{"), // public final static int RBRACE = 13; // ("}"), // public final static int LBRACKET = 14; // ("["), // public final static int RBRACKET = 15; // ("]"), // public final static int COMMA = 16; // (","), // public final static int COLON = 17; // (":"), // public final static int IDENTIFIER = 18; // public final static int FIELD_NAME = 19; public final static int EOF = 20; public final static int SET = 21; public final static int TREE_SET = 22; public final static int UNDEFINED = 23; // undefined public static String name(int value) { switch (value) { case ERROR: return "error"; case LITERAL_INT: return "int"; case LITERAL_FLOAT: return "float"; case LITERAL_STRING: return "string"; case LITERAL_ISO8601_DATE: return "iso8601"; case TRUE: return "true"; case FALSE: return "false"; case NULL: return "null"; case NEW: return "new"; case LPAREN: return "("; case RPAREN: return ")"; case LBRACE: return "{"; case RBRACE: return "}"; case LBRACKET: return "["; case RBRACKET: return "]"; case COMMA: return ","; case COLON: return ":"; case IDENTIFIER: return "ident"; case FIELD_NAME: return "fieldName"; case EOF: return "EOF"; case SET: return "Set"; case TREE_SET: return "TreeSet"; case UNDEFINED: return "undefined"; default: return "Unkown"; } } }
xiepengchong/FactoryZxing
src/com/alibaba/fastjson/parser/JSONToken.java
Java
apache-2.0
3,656
package com.github.obourgain.elasticsearch.http.response.parser; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.elasticsearch.common.xcontent.XContentParser; import com.github.obourgain.elasticsearch.http.response.entity.Indices; import com.github.obourgain.elasticsearch.http.response.entity.ShardFailure; import com.github.obourgain.elasticsearch.http.response.entity.Shards; import lombok.Getter; @Getter public class IndicesParser { private static List<ShardFailure> failures; public static Indices parse(XContentParser parser) { Map<String, Shards> result = new HashMap<>(); try { XContentParser.Token token; String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { failures = ShardFailure.parse(parser); } else if (token == XContentParser.Token.START_OBJECT) { Shards shards = new Shards().parse(parser); result.put(currentFieldName, shards); } } return Indices.fromMap(result); } catch (IOException e) { throw new RuntimeException("Unable to parse source", e); } } }
obourgain/elasticsearch-http
src/main/java/com/github/obourgain/elasticsearch/http/response/parser/IndicesParser.java
Java
apache-2.0
1,496
/* * Copyright 2012 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 com.github.carlomicieli.nerdmovies.controllers; import com.github.carlomicieli.nerdmovies.services.MovieService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * @author Carlo Micieli */ @Controller @RequestMapping("/") public class HomeController { private MovieService movieService; @Autowired public HomeController(MovieService movieService) { this.movieService = movieService; } @RequestMapping(value = {"/", "/home"}, method = RequestMethod.GET) public String index(Model model) { model.addAttribute("movies", movieService.getRecentMovies(10)); return "home/index"; } @RequestMapping(value = "/about", method = RequestMethod.GET) public String about() { return "home/about"; } @RequestMapping(value = "/default", method = RequestMethod.GET) public String defaultPage() { return "home/index"; } }
CarloMicieli/spring-mvc-movies
src/main/java/com/github/carlomicieli/nerdmovies/controllers/HomeController.java
Java
apache-2.0
1,759
package com.camillepradel.movierecommender.utils; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; public class CsvToMySql { static final String pathToCsvFiles = "D:\\MovieRecommender\\src\\main\\java\\com\\camillepradel\\movierecommender\\utils\\"; static final String usersCsvFile = pathToCsvFiles + "users.csv"; static final String moviesCsvFile = pathToCsvFiles + "movies.csv"; static final String genresCsvFile = pathToCsvFiles + "genres.csv"; static final String movGenreCsvFile = pathToCsvFiles + "mov_genre.csv"; static final String ratingsCsvFile = pathToCsvFiles + "ratings.csv"; static final String friendsCsvFile = pathToCsvFiles + "friends.csv"; static final String cvsSplitBy = ","; private static void commitUsers(Connection connection) throws SQLException { System.out.println(usersCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS users (\n" + " id int(11) NOT NULL AUTO_INCREMENT,\n" + " age int(11) NOT NULL,\n" + " sex varchar(1) NOT NULL,\n" + " occupation varchar(60) NOT NULL,\n" + " zip varchar(6) NOT NULL,\n" + " PRIMARY KEY (`id`)\n" + ");"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(usersCsvFile))) { String insertQuery = "INSERT INTO users (id, age, sex, occupation, zip) VALUES (?, ?, ?, ?, ?)"; PreparedStatement insertUsers = null; try { connection.setAutoCommit(false); insertUsers = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); insertUsers.setInt(1, Integer.parseInt(values[0])); insertUsers.setInt(2, Integer.parseInt(values[1])); insertUsers.setString(3, values[2]); insertUsers.setString(4, values[3]); insertUsers.setString(5, values[4]); insertUsers.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertUsers != null) { insertUsers.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } private static void commitMovies(Connection connection) throws SQLException { // movies.csv System.out.println(moviesCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS movies (\n" + " id int(11) NOT NULL AUTO_INCREMENT,\n" + " title varchar(200) NOT NULL,\n" + " date date NOT NULL,\n" + " PRIMARY KEY (`id`)\n" + ");"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(moviesCsvFile))) { String insertQuery = "INSERT INTO movies (id, title, date) VALUES (?, ?, ?)"; PreparedStatement insertMovies = null; try { connection.setAutoCommit(false); insertMovies = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); int movieId = Integer.parseInt(values[0]); String title = String.join(",", Arrays.copyOfRange(values, 1, values.length - 1)); Date date = new Date(Long.parseLong(values[values.length - 1]) * 1000); insertMovies.setInt(1, movieId); insertMovies.setString(2, title); insertMovies.setDate(3, date); insertMovies.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertMovies != null) { insertMovies.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } private static void commitGenres(Connection connection) throws SQLException { // genres.csv System.out.println(genresCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS genres (\n" + " name varchar(60) NOT NULL,\n" + " id int(11) NOT NULL AUTO_INCREMENT,\n" + " PRIMARY KEY (`id`)\n" + ");"); // necessary to make mySQL accept 0 as a valid id value for genre unknown statement.execute("SET SESSION sql_mode='NO_AUTO_VALUE_ON_ZERO';"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(genresCsvFile))) { String insertQuery = "INSERT INTO genres (name, id) VALUES (?, ?)"; PreparedStatement insertGenres = null; try { connection.setAutoCommit(false); insertGenres = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); String name = values[0]; int genreId = Integer.parseInt(values[1]); insertGenres.setString(1, name); insertGenres.setInt(2, genreId); insertGenres.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertGenres != null) { insertGenres.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } private static void commitMovieGenre(Connection connection) throws SQLException { // mov_genre.csv System.out.println(movGenreCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS movie_genre (\n" + " movie_id int(11) NOT NULL,\n" + " genre_id int(11) NOT NULL,\n" + " KEY movie_id (movie_id),\n" + " KEY genre_id (genre_id)\n" + ");"); statement.executeUpdate("ALTER TABLE movie_genre\n" + " ADD CONSTRAINT movie_genre_to_movie FOREIGN KEY (movie_id) REFERENCES movies(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); statement.executeUpdate("ALTER TABLE movie_genre\n" + " ADD CONSTRAINT movie_genre_to_genre FOREIGN KEY (genre_id) REFERENCES genres(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(movGenreCsvFile))) { String insertQuery = "INSERT INTO movie_genre (movie_id, genre_id) VALUES (?, ?)"; PreparedStatement insertMovieGenre = null; try { connection.setAutoCommit(false); insertMovieGenre = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); int movieId = Integer.parseInt(values[0]); int genreId = Integer.parseInt(values[1]); insertMovieGenre.setInt(1, movieId); insertMovieGenre.setInt(2, genreId); insertMovieGenre.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertMovieGenre != null) { insertMovieGenre.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } private static void commitRatings(Connection connection) throws SQLException { // ratings.csv System.out.println(ratingsCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS ratings (\n" + " user_id int(11) NOT NULL,\n" + " movie_id int(11) NOT NULL,\n" + " rating int(11) NOT NULL,\n" + " date date NOT NULL,\n" + " KEY user_id (user_id),\n" + " KEY movie_id (movie_id)\n" + ");"); statement.executeUpdate("ALTER TABLE ratings\n" + " ADD CONSTRAINT ratings_to_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); statement.executeUpdate("ALTER TABLE ratings\n" + " ADD CONSTRAINT ratings_to_movie FOREIGN KEY (movie_id) REFERENCES movies(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); statement.executeUpdate("ALTER TABLE ratings\n" + " ADD UNIQUE unique_index(user_id, movie_id);\n"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(ratingsCsvFile))) { String insertQuery = "INSERT INTO ratings (user_id, movie_id, rating, date) VALUES (?, ?, ?, ?)"; PreparedStatement insertRatings = null; try { connection.setAutoCommit(false); insertRatings = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); int userId = Integer.parseInt(values[0]); int movieId = Integer.parseInt(values[1]); int ratingValue = Integer.parseInt(values[2]); Date date = new Date(Long.parseLong(values[3]) * 1000); insertRatings.setInt(1, userId); insertRatings.setInt(2, movieId); insertRatings.setInt(3, ratingValue); insertRatings.setDate(4, date); insertRatings.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertRatings != null) { insertRatings.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } private static void commitFriends(Connection connection) throws SQLException { // friends.csv System.out.println(friendsCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS friends (\n" + " user1_id int(11) NOT NULL,\n" + " user2_id int(11) NOT NULL,\n" + " KEY user1_id (user1_id),\n" + " KEY user2_id (user2_id)\n" + ");"); statement.executeUpdate("ALTER TABLE friends\n" + " ADD CONSTRAINT friends_to_user1 FOREIGN KEY (user1_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); statement.executeUpdate("ALTER TABLE friends\n" + " ADD CONSTRAINT friends_to_user2 FOREIGN KEY (user2_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(friendsCsvFile))) { String insertQuery = "INSERT INTO friends (user1_id, user2_id) VALUES (?, ?)"; PreparedStatement insertFriends = null; try { connection.setAutoCommit(false); insertFriends = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); int user1Id = Integer.parseInt(values[0]); int user2Id = Integer.parseInt(values[1]); insertFriends.setInt(1, user1Id); insertFriends.setInt(2, user2Id); insertFriends.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertFriends != null) { insertFriends.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { // load JDBC driver try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } // db connection info String url = "jdbc:mysql://localhost:3306" + "?zeroDateTimeBehavior=convertToNull&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; String login = "admin"; String password = "Q86PhnJRiEa7"; Connection connection = null; try { connection = DriverManager.getConnection(url, login, password); Statement statement = connection.createStatement(); // create database statement.executeUpdate("DROP DATABASE IF EXISTS movie_recommender;"); statement.executeUpdate("CREATE DATABASE movie_recommender;"); statement.executeUpdate("USE movie_recommender;"); commitUsers(connection); commitMovies(connection); commitGenres(connection); commitMovieGenre(connection); commitRatings(connection); commitFriends(connection); } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException ignore) { // exception occured while closing connexion -> nothing else can be done } } } System.out.println("done"); } }
Camille31/MovieRecommender
src/main/java/com/camillepradel/movierecommender/utils/CsvToMySql.java
Java
apache-2.0
17,630
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.cache.query.internal; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.geode.annotations.internal.MakeNotStatic; import org.apache.geode.cache.EntryDestroyedException; import org.apache.geode.cache.Region; import org.apache.geode.cache.query.AmbiguousNameException; import org.apache.geode.cache.query.FunctionDomainException; import org.apache.geode.cache.query.NameResolutionException; import org.apache.geode.cache.query.QueryInvocationTargetException; import org.apache.geode.cache.query.QueryService; import org.apache.geode.cache.query.TypeMismatchException; import org.apache.geode.internal.InternalDataSerializer; import org.apache.geode.internal.cache.PartitionedRegion; import org.apache.geode.pdx.PdxInstance; import org.apache.geode.pdx.PdxSerializationException; import org.apache.geode.pdx.internal.InternalPdxInstance; import org.apache.geode.pdx.internal.PdxString; /** * Class Description * * @version $Revision: 1.1 $ */ public class CompiledOperation extends AbstractCompiledValue { private final CompiledValue receiver; // may be null if implicit to scope private final String methodName; private final List args; @MakeNotStatic private static final ConcurrentMap cache = new ConcurrentHashMap(); // receiver is an ID or PATH that contains the operation name public CompiledOperation(CompiledValue receiver, String methodName, List args) { this.receiver = receiver; this.methodName = methodName; this.args = args; } @Override public List getChildren() { List list = new ArrayList(); if (this.receiver != null) { list.add(this.receiver); } list.addAll(this.args); return list; } public String getMethodName() { return this.methodName; } public List getArguments() { return this.args; } @Override public int getType() { return METHOD_INV; } public CompiledValue getReceiver(ExecutionContext cxt) { // receiver may be cached in execution context if (this.receiver == null && cxt != null) { return (CompiledValue) cxt.cacheGet(this); } return this.receiver; } @Override public boolean hasIdentifierAtLeafNode() { if (this.receiver.getType() == Identifier) { return true; } else { return this.receiver.hasIdentifierAtLeafNode(); } } @Override public CompiledValue getReceiver() { return this.getReceiver(null); } @Override public Object evaluate(ExecutionContext context) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException { CompiledValue rcvr = getReceiver(context); Object result; Object evalRcvr; if (rcvr == null) { // must be intended as implicit iterator operation // see if it's an implicit operation name RuntimeIterator rcvrItr = context.resolveImplicitOperationName(this.methodName, this.args.size(), true); evalRcvr = rcvrItr.evaluate(context); /* * // evaluate on current iteration of collection if (rcvrItr != null) { result = * eval0(rcvrItr.evaluate(context), rcvrItr.getElementType().resolveClass(), context); } * * // function call: no functions implemented except keywords in the grammar throw new * TypeMismatchException("Could not resolve method named 'xyz'") */ } else { // if not null, then explicit receiver evalRcvr = rcvr.evaluate(context); } // short circuit null immediately if (evalRcvr == null) { return QueryService.UNDEFINED; } if (context.isCqQueryContext() && evalRcvr instanceof Region.Entry) { Region.Entry re = (Region.Entry) evalRcvr; if (re.isDestroyed()) { return QueryService.UNDEFINED; } try { evalRcvr = re.getValue(); } catch (EntryDestroyedException ede) { // Even though isDestory() check is made, the entry could // throw EntryDestroyedException if the value becomes null. return QueryService.UNDEFINED; } } // check if the receiver is the iterator, in which // case we resolve the method on the constraint rather // than the runtime type of the receiver Class resolveClass = null; // commented out because we currently always resolve the method // on the runtime types // CompiledValue rcvrVal = rcvrPath.getReceiver(); // if (rcvrVal.getType() == ID) // { // CompiledValue resolvedID = context.resolve(((CompiledID)rcvrVal).getId()); // if (resolvedID.getType() == ITERATOR) // { // resolveClass = ((RuntimeIterator)resolvedID).getBaseCollection().getConstraint(); // } // } // if (resolveClass == null) if (evalRcvr instanceof PdxInstance) { String className = ((PdxInstance) evalRcvr).getClassName(); try { resolveClass = InternalDataSerializer.getCachedClass(className); } catch (ClassNotFoundException cnfe) { throw new QueryInvocationTargetException(cnfe); } } else if (evalRcvr instanceof PdxString) { resolveClass = String.class; } else { resolveClass = evalRcvr.getClass(); } result = eval0(evalRcvr, resolveClass, context); // } // check for PR substitution // check for BucketRegion substitution PartitionedRegion pr = context.getPartitionedRegion(); if (pr != null && (result instanceof Region)) { if (pr.getFullPath().equals(((Region) result).getFullPath())) { result = context.getBucketRegion(); } } return result; } @Override public Set computeDependencies(ExecutionContext context) throws TypeMismatchException, AmbiguousNameException, NameResolutionException { List args = this.args; Iterator i = args.iterator(); while (i.hasNext()) { context.addDependencies(this, ((CompiledValue) i.next()).computeDependencies(context)); } CompiledValue rcvr = getReceiver(context); if (rcvr == null) // implicit iterator operation { // see if it's an implicit operation name RuntimeIterator rcvrItr = context.resolveImplicitOperationName(this.methodName, this.args.size(), true); if (rcvrItr == null) { // no receiver resolved // function call: no functions implemented except keywords in the grammar throw new TypeMismatchException( String.format("Could not resolve method named ' %s '", this.methodName)); } // cache the receiver so we don't have to resolve it again context.cachePut(this, rcvrItr); return context.addDependency(this, rcvrItr); } // receiver is explicit return context.addDependencies(this, rcvr.computeDependencies(context)); } @edu.umd.cs.findbugs.annotations.SuppressWarnings( value = "RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED", justification = "Does not matter if the methodDispatch that isn't stored in the map is used") private Object eval0(Object receiver, Class resolutionType, ExecutionContext context) throws TypeMismatchException, FunctionDomainException, NameResolutionException, QueryInvocationTargetException { if (receiver == null || receiver == QueryService.UNDEFINED) return QueryService.UNDEFINED; List args = new ArrayList(); List argTypes = new ArrayList(); Iterator i = this.args.iterator(); while (i.hasNext()) { CompiledValue arg = (CompiledValue) i.next(); Object o = arg.evaluate(context); // undefined arg produces undefines method result if (o == QueryService.UNDEFINED) return QueryService.UNDEFINED; args.add(o); // pass in null for the type if the runtime value is null if (o == null) argTypes.add(null); // commented out because we currently always use the runtime type for args // else if (arg.getType() == Identifier) // { // CompiledValue resolved = context.resolve(((CompiledID)arg).getId()); // if (resolved != null && resolved.getType() == ITERATOR) // argTypes.add(((RuntimeIterator)resolved).getBaseCollection().getConstraint()); // else // argTypes.add(o.getClass()); // } else argTypes.add(o.getClass()); // otherwise use the runtime type } // see if in cache MethodDispatch methodDispatch; List key = Arrays.asList(new Object[] {resolutionType, this.methodName, argTypes}); methodDispatch = (MethodDispatch) CompiledOperation.cache.get(key); if (methodDispatch == null) { try { methodDispatch = new MethodDispatch(context.getCache().getQueryService().getMethodInvocationAuthorizer(), resolutionType, this.methodName, argTypes); } catch (NameResolutionException nre) { if (!org.apache.geode.cache.query.Struct.class.isAssignableFrom(resolutionType) && (DefaultQueryService.QUERY_HETEROGENEOUS_OBJECTS || DefaultQueryService.TEST_QUERY_HETEROGENEOUS_OBJECTS)) { return QueryService.UNDEFINED; } else { throw nre; } } // cache CompiledOperation.cache.putIfAbsent(key, methodDispatch); } if (receiver instanceof InternalPdxInstance) { try { receiver = ((InternalPdxInstance) receiver).getCachedObject(); } catch (PdxSerializationException ex) { throw new QueryInvocationTargetException(ex); } } else if (receiver instanceof PdxString) { receiver = ((PdxString) receiver).toString(); } return methodDispatch.invoke(receiver, args); } // Asif :Function for generating from clause @Override public void generateCanonicalizedExpression(StringBuilder clauseBuffer, ExecutionContext context) throws AmbiguousNameException, TypeMismatchException, NameResolutionException { // Asif: if the method name starts with getABC & argument list is empty // then canonicalize it to aBC int len; if (this.methodName.startsWith("get") && (len = this.methodName.length()) > 3 && (this.args == null || this.args.isEmpty())) { clauseBuffer.insert(0, len > 4 ? this.methodName.substring(4) : ""); clauseBuffer.insert(0, Character.toLowerCase(this.methodName.charAt(3))); } else if (this.args == null || this.args.isEmpty()) { clauseBuffer.insert(0, "()").insert(0, this.methodName); } else { // The method contains arguments which need to be canonicalized clauseBuffer.insert(0, ')'); CompiledValue cv = null; for (int j = this.args.size(); j > 0;) { cv = (CompiledValue) this.args.get(--j); cv.generateCanonicalizedExpression(clauseBuffer, context); clauseBuffer.insert(0, ','); } clauseBuffer.deleteCharAt(0).insert(0, '(').insert(0, this.methodName); } clauseBuffer.insert(0, '.'); CompiledValue rcvr = this.receiver; if (rcvr == null) { // must be intended as implicit iterator operation // see if it's an implicit operation name. The receiver will now be RuntimeIterator rcvr = context.resolveImplicitOperationName(this.methodName, this.args.size(), true); } rcvr.generateCanonicalizedExpression(clauseBuffer, context); } }
PurelyApplied/geode
geode-core/src/main/java/org/apache/geode/cache/query/internal/CompiledOperation.java
Java
apache-2.0
12,213
package com.turlir.abakgists.allgists.view.listing; import androidx.recyclerview.widget.RecyclerView; import android.view.View; abstract class ModelViewHolder<T> extends RecyclerView.ViewHolder { ModelViewHolder(View itemView) { super(itemView); } abstract void bind(T model); }
iljaosintsev/Apress-Gists
app/src/main/java/com/turlir/abakgists/allgists/view/listing/ModelViewHolder.java
Java
apache-2.0
305
package com.zuoqing.demo.entity; /** * http 请求返回的最外层对象 */ public class Result<T> { private Integer code; private String msg; private T data; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
zuoqing135du/SpringBoot
src/main/java/com/zuoqing/demo/entity/Result.java
Java
apache-2.0
569
/* * 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 libthrift091; public interface TEnum { public int getValue(); }
XiaoMi/galaxy-sdk-java
galaxy-thrift-api/src/main/java/libthrift091/TEnum.java
Java
apache-2.0
880
/* * Copyright (c) 2013 EMBL - European Bioinformatics Institute * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ var lodeNamespacePrefixes = { rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', rdfs: 'http://www.w3.org/2000/01/rdf-schema#', owl: 'http://www.w3.org/2002/07/owl#', dc: 'http://purl.org/dc/elements/1.1/', dcterms: 'http://purl.org/dc/terms/', obo: 'http://purl.obolibrary.org/obo/', efo: 'http://www.ebi.ac.uk/efo/', 'biosd-terms': 'http://rdf.ebi.ac.uk/terms/biosd/', pav: 'http://purl.org/pav/2.0/', prov: 'http://www.w3.org/ns/prov#', foaf: 'http://xmlns.com/foaf/0.1/', sio: 'http://semanticscience.org/resource/', atlas: 'http://rdf.ebi.ac.uk/terms/atlas/', oac: 'http://www.openannotation.org/ns/' };
EBIBioSamples/lodestar
web-ui/src/main/webapp/scripts/namespaces.js
JavaScript
apache-2.0
1,394
/* * Copyright to 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.rioproject.tools.cli; import java.io.BufferedReader; import java.io.PrintStream; /** * Define plugin interface for CLI option handlers. An OptionHandler is * responsible for providing a option, or activity, that will be used through * the CLI. * * @author Dennis Reedy */ public interface OptionHandler { /** * Process the option. * * @param input Parameters for the option, may be null * @param br An optional BufferdReader, used if the option requires input. * if this is null, the option handler may create a BufferedReader to * handle the input * @param out The PrintStream to use if the option prints results or * choices for the user. Must not be null * * @return The result of the action. */ String process(String input, BufferedReader br, PrintStream out); /** * Get the usage of the command * * @return Command usage */ String getUsage(); }
dreedyman/Rio
rio-tools/rio-cli/src/main/java/org/rioproject/tools/cli/OptionHandler.java
Java
apache-2.0
1,583
package com.cognitionis.nlp_files; import java.io.*; import java.util.regex.*; /** * * @author Héctor Llorens * @since 2011 */ public class TreebankFile extends NLPFile { public TreebankFile(String filename) { super(filename); } @Override public Boolean isWellFormatted() { int par_level = 0; try { if (super.getFile()==null) { throw new Exception("No file loaded in NLPFile object"); } BufferedReader reader = new BufferedReader(new FileReader(this.f)); try { String line = null; int linen = 0; Pattern p = Pattern.compile("[\\(\\)]"); while ((line = reader.readLine()) != null) { linen++; //System.getProperty("line.separator") if (line.matches("\\s*[^\\(\\s].*")) { throw new Exception("Treebank format error: line " + linen + " not begining with \\s*("); } Matcher m = p.matcher(line); while (m.find()) { if (m.group().equals("(")) { par_level++; } else { par_level--; if (par_level < 0) { throw new Exception("Treebank format error: par_level lower than 0"); } } } //System.out.println(linen+": "+line+" - parlevel="+ par_level); } } finally { reader.close(); } if (par_level != 0) { throw new Exception("Treebank format error: positive unbalancement, par_level=" + par_level); } } catch (Exception e) { System.err.println("Errors found ("+this.getClass().getSimpleName()+"):\n\t" + e.toString() + "\n"); if(System.getProperty("DEBUG")!=null && System.getProperty("DEBUG").equalsIgnoreCase("true")){e.printStackTrace(System.err);} return false; } return true; } public String toPlain(String filename){ // one token, one space, one token, one space... (end of sentence -> \n) return this.getFile().toString(); } }
hllorens/cognitionis-nlp-libraries
nlp-files/src/main/java/com/cognitionis/nlp_files/TreebankFile.java
Java
apache-2.0
2,385
package com.kashukov.convert; /** * Convert short to any primitive data type */ public class Short { /** * Convert short to boolean * * @param input short * @return boolean */ public static boolean shortToBoolean(short input) { return input != 0; } /** * Convert short to byte * * @param input short * @return byte */ public static byte shortToByte(short input) { return (byte) input; } /** * Convert short to byte[] * * @param input short * @return byte[] */ public static byte[] shortToByteArray(short input) { return new byte[]{ (byte) (input >>> 8), (byte) input}; } /** * Convert short to char * * @param input short * @return char */ public static char shortToChar(short input) { return (char) input; } /** * Convert short to double * * @param input short * @return double */ public static double shortToDouble(short input) { return (double) input; } /** * Convert short to float * * @param input short * @return float */ public static float shortToFloat(short input) { return (float) input; } /** * Convert short to int * * @param input short * @return int */ public static int shortToInt(short input) { return (int) input; } /** * Convert short to long * * @param input short * @return long */ public static long shortToLong(short input) { return (long) input; } /** * Convert short to String * * @param input short * @return String */ public static java.lang.String shortToString(short input) { return java.lang.Short.toString(input); } }
kashukov/convert
src/main/java/com/kashukov/convert/Short.java
Java
apache-2.0
1,895
<?php /** * PluginOp2CommunityEventMember form. * * @package opMTViewerPlugin * @subpackage form * @author Kimura Youichi <kim.upsilon@gmail.com> */ abstract class PluginOp2CommunityEventMemberForm extends BaseOp2CommunityEventMemberForm { }
upsilon/opMTViewerPlugin
lib/form/doctrine/PluginOp2CommunityEventMemberForm.class.php
PHP
apache-2.0
256
package be.dnsbelgium.rdap.sample.parser; import be.dnsbelgium.rdap.sample.dto.Contact; import be.dnsbelgium.rdap.sample.dto.DnsSecKey; import be.dnsbelgium.rdap.sample.dto.SimpleContact; public enum WhoisKeyBlock { MAIN(), DOMAIN(), REGISTRAR(), REGISTRANT(), ADMIN(Contact.class), TECH(Contact.class), DNSSEC(), DNSSECKEY(DnsSecKey.class, true), HOST(), SIMPLE_ADMIN(SimpleContact.class), SIMPLE_TECH(SimpleContact.class); private Class repeatClass = null; private boolean hasIndexSuffix = false; WhoisKeyBlock() { } WhoisKeyBlock(Class repeatClass) { this.repeatClass = repeatClass; } WhoisKeyBlock(Class repeatClass, boolean hasIndexSuffix) { this.repeatClass = repeatClass; this.hasIndexSuffix = hasIndexSuffix; } public Class getRepeatClass() { return repeatClass; } public boolean hasIndexSuffix() { return hasIndexSuffix; } public boolean isRepeatable() { return repeatClass != null; } }
DNSBelgium/rdap-server-sample-gtld
src/main/java/be/dnsbelgium/rdap/sample/parser/WhoisKeyBlock.java
Java
apache-2.0
981
package com.github.hadoop.maven.plugin; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; /** * Writes jars. * * */ public class JarWriter { /** * Given a root directory, this writes the contents of the same as a jar file. * The path to files inside the jar are relative paths, relative to the root * directory specified. * * @param jarRootDir * Root Directory that serves as an input to writing the jars. * @param os * OutputStream to which the jar is to be packed * @throws FileNotFoundException * @throws IOException */ public void packToJar(File jarRootDir, OutputStream os) throws FileNotFoundException, IOException { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); JarOutputStream target = new JarOutputStream(os, manifest); for (File nestedFile : jarRootDir.listFiles()) add(jarRootDir.getPath().replace("\\", "/"), nestedFile, target); target.close(); } private void add(String prefix, File source, JarOutputStream target) throws IOException { BufferedInputStream in = null; try { if (source.isDirectory()) { String name = source.getPath().replace("\\", "/"); if (!name.isEmpty()) { if (!name.endsWith("/")) name += "/"; JarEntry entry = new JarEntry(name.substring(prefix.length() + 1)); entry.setTime(source.lastModified()); target.putNextEntry(entry); target.closeEntry(); } for (File nestedFile : source.listFiles()) add(prefix, nestedFile, target); return; } String jarentryName = source.getPath().replace("\\", "/").substring( prefix.length() + 1); JarEntry entry = new JarEntry(jarentryName); entry.setTime(source.lastModified()); target.putNextEntry(entry); in = new BufferedInputStream(new FileInputStream(source)); byte[] buffer = new byte[1024]; while (true) { int count = in.read(buffer); if (count == -1) break; target.write(buffer, 0, count); } target.closeEntry(); } finally { if (in != null) in.close(); } } }
akkumar/maven-hadoop
src/main/java/com/github/hadoop/maven/plugin/JarWriter.java
Java
apache-2.0
2,529
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.transfer.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum HomeDirectoryType { PATH("PATH"), LOGICAL("LOGICAL"); private String value; private HomeDirectoryType(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return HomeDirectoryType corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static HomeDirectoryType fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (HomeDirectoryType enumEntry : HomeDirectoryType.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
aws/aws-sdk-java
aws-java-sdk-transfer/src/main/java/com/amazonaws/services/transfer/model/HomeDirectoryType.java
Java
apache-2.0
1,790
package com.ilad.teamwork; import org.openqa.selenium.WebElement; import io.appium.java_client.android.AndroidDriver; public class TabsMenu extends AbstractTeamWork { public TabsMenu(AndroidDriver<WebElement> driver) { super(driver); } public AllProjectsPage goToProjects() { driver.findElementByXPath("//android.widget.TextView[@text='Projects']").click(); return new AllProjectsPage(driver); } }
Solomon1732/infinity-labs-repository
TeamWorkAndroid/src/main/java/com/ilad/teamwork/TabsMenu.java
Java
apache-2.0
414
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # You may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. require 'spec_helper' RSpec.describe OneviewSDK::API2200::C7000::VolumeTemplate do include_context 'shared context' it 'inherits from OneviewSDK::API2000::C7000::VolumeTemplate' do expect(described_class).to be < OneviewSDK::API2000::C7000::VolumeTemplate end end
HewlettPackard/oneview-sdk-ruby
spec/unit/resource/api2200/c7000/volume_template_spec.rb
Ruby
apache-2.0
876
// Copyright 2021 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.api.ads.admanager.jaxws.v202111; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * * Gets an {@link ActivityGroupPage} of {@link ActivityGroup} objects that satisfy the given * {@link Statement#query}. The following fields are supported for filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link ActivityGroup#id}</td> * </tr> * <tr> * <td>{@code name}</td> * <td>{@link ActivityGroup#name}</td> * </tr> * <tr> * <td>{@code impressionsLookback}</td> * <td>{@link ActivityGroup#impressionsLookback}</td> * </tr> * <tr> * <td>{@code clicksLookback}</td> * <td>{@link ActivityGroup#clicksLookback}</td> * </tr> * <tr> * <td>{@code status}</td> * <td>{@link ActivityGroup#status}</td> * </tr> * </table> * * @param filterStatement a statement used to filter a set of activity groups * @return the activity groups that match the given filter * * * <p>Java class for getActivityGroupsByStatement element declaration. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;element name="getActivityGroupsByStatement"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="filterStatement" type="{https://www.google.com/apis/ads/publisher/v202111}Statement" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "filterStatement" }) @XmlRootElement(name = "getActivityGroupsByStatement") public class ActivityGroupServiceInterfacegetActivityGroupsByStatement { protected Statement filterStatement; /** * Gets the value of the filterStatement property. * * @return * possible object is * {@link Statement } * */ public Statement getFilterStatement() { return filterStatement; } /** * Sets the value of the filterStatement property. * * @param value * allowed object is * {@link Statement } * */ public void setFilterStatement(Statement value) { this.filterStatement = value; } }
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202111/ActivityGroupServiceInterfacegetActivityGroupsByStatement.java
Java
apache-2.0
3,560
package vnetpeering import ( "context" "fmt" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-11-01/network" "github.com/giantswarm/microerror" "github.com/giantswarm/operatorkit/v4/pkg/controller/context/reconciliationcanceledcontext" "github.com/giantswarm/to" "github.com/giantswarm/azure-operator/v5/service/controller/key" ) const ( ProvisioningStateDeleting = "Deleting" ) // This resource manages the VNet peering between the control plane and tenant cluster. func (r *Resource) EnsureCreated(ctx context.Context, obj interface{}) error { cr, err := key.ToCustomResource(obj) if err != nil { return microerror.Mask(err) } var tcVnet network.VirtualNetwork { r.logger.LogCtx(ctx, "level", "debug", "message", fmt.Sprintf("Checking if TC virtual network %#q exists in resource group %#q", key.VnetName(cr), key.ResourceGroupName(cr))) virtualNetworksClient, err := r.clientFactory.GetVirtualNetworksClient(ctx, cr.ObjectMeta) if err != nil { return microerror.Mask(err) } tcVnet, err = virtualNetworksClient.Get(ctx, key.ResourceGroupName(cr), key.VnetName(cr), "") if IsNotFound(err) { r.logger.LogCtx(ctx, "level", "debug", "message", "TC Virtual network does not exist in resource group") reconciliationcanceledcontext.SetCanceled(ctx) r.logger.LogCtx(ctx, "level", "debug", "message", "canceling reconciliation") return nil } else if err != nil { return microerror.Mask(err) } r.logger.LogCtx(ctx, "level", "debug", "message", "TC Virtual network exists in resource group") } var cpVnet network.VirtualNetwork { r.logger.LogCtx(ctx, "level", "debug", "message", fmt.Sprintf("Checking if CP virtual network %#q exists in resource group %#q", r.mcVirtualNetworkName, r.mcResourceGroup)) cpVnet, err = r.cpAzureClientSet.VirtualNetworkClient.Get(ctx, r.mcResourceGroup, r.mcVirtualNetworkName, "") if IsNotFound(err) { r.logger.LogCtx(ctx, "level", "debug", "message", "CP Virtual network does not exist in resource group") reconciliationcanceledcontext.SetCanceled(ctx) r.logger.LogCtx(ctx, "level", "debug", "message", "canceling reconciliation") return nil } else if err != nil { return microerror.Mask(err) } r.logger.LogCtx(ctx, "level", "debug", "message", "CP Virtual network exists") } { r.logger.LogCtx(ctx, "level", "debug", "message", fmt.Sprintf("Ensuring vnet peering %#q exists on the tenant cluster vnet %#q in resource group %#q", r.mcVirtualNetworkName, key.VnetName(cr), key.ResourceGroupName(cr))) vnetPeeringsClient, err := r.clientFactory.GetVnetPeeringsClient(ctx, cr.ObjectMeta) if err != nil { return microerror.Mask(err) } tcPeering := r.getTCVnetPeering(*cpVnet.ID) _, err = vnetPeeringsClient.CreateOrUpdate(ctx, key.ResourceGroupName(cr), key.VnetName(cr), r.mcVirtualNetworkName, tcPeering) if err != nil { return microerror.Mask(err) } } { r.logger.LogCtx(ctx, "level", "debug", "message", fmt.Sprintf("Ensuring vnet peering %#q exists on the control plane vnet %#q in resource group %#q", key.ResourceGroupName(cr), r.mcVirtualNetworkName, r.mcResourceGroup)) cpPeering := r.getCPVnetPeering(*tcVnet.ID) _, err = r.cpAzureClientSet.VnetPeeringClient.CreateOrUpdate(ctx, r.mcResourceGroup, r.mcVirtualNetworkName, key.ResourceGroupName(cr), cpPeering) if err != nil { return microerror.Mask(err) } } return nil } func (r *Resource) getCPVnetPeering(vnetId string) network.VirtualNetworkPeering { peering := network.VirtualNetworkPeering{ VirtualNetworkPeeringPropertiesFormat: &network.VirtualNetworkPeeringPropertiesFormat{ AllowVirtualNetworkAccess: to.BoolP(true), AllowForwardedTraffic: to.BoolP(false), AllowGatewayTransit: to.BoolP(false), UseRemoteGateways: to.BoolP(false), RemoteVirtualNetwork: &network.SubResource{ ID: &vnetId, }, }, } return peering } func (r *Resource) getTCVnetPeering(vnetId string) network.VirtualNetworkPeering { peering := network.VirtualNetworkPeering{ VirtualNetworkPeeringPropertiesFormat: &network.VirtualNetworkPeeringPropertiesFormat{ AllowVirtualNetworkAccess: to.BoolP(true), AllowForwardedTraffic: to.BoolP(false), AllowGatewayTransit: to.BoolP(false), UseRemoteGateways: to.BoolP(false), RemoteVirtualNetwork: &network.SubResource{ ID: &vnetId, }, }, } return peering }
giantswarm/azure-operator
service/controller/azureconfig/handler/vnetpeering/create.go
GO
apache-2.0
4,401
package org.ovirt.engine.ui.uicommonweb.models.vms; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.ovirt.engine.core.common.businessentities.DiskImage; import org.ovirt.engine.core.common.businessentities.DiskImageBase; import org.ovirt.engine.core.common.businessentities.StorageType; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VolumeFormat; import org.ovirt.engine.core.common.businessentities.VolumeType; import org.ovirt.engine.core.common.businessentities.storage_domain_static; import org.ovirt.engine.core.common.businessentities.storage_domains; import org.ovirt.engine.core.common.businessentities.storage_pool; import org.ovirt.engine.core.compat.Event; import org.ovirt.engine.core.compat.EventArgs; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.IEventListener; import org.ovirt.engine.core.compat.NGuid; import org.ovirt.engine.core.compat.ObservableCollection; import org.ovirt.engine.core.compat.PropertyChangedEventArgs; import org.ovirt.engine.core.compat.StringFormat; import org.ovirt.engine.core.compat.StringHelper; import org.ovirt.engine.ui.frontend.AsyncQuery; import org.ovirt.engine.ui.frontend.INewAsyncCallback; import org.ovirt.engine.ui.uicommonweb.Linq; import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider; import org.ovirt.engine.ui.uicommonweb.models.EntityModel; import org.ovirt.engine.ui.uicommonweb.models.ListModel; import org.ovirt.engine.ui.uicommonweb.models.ListWithDetailsModel; import org.ovirt.engine.ui.uicommonweb.validation.IValidation; import org.ovirt.engine.ui.uicommonweb.validation.NotEmptyValidation; @SuppressWarnings("unused") public class ImportVmModel extends ListWithDetailsModel { boolean sameSelectedDestinationStorage = false; ArrayList<storage_domains> uniqueDestStorages; ArrayList<storage_domains> allDestStorages; storage_domains selectedDestinationStorage; HashMap<Guid, ArrayList<Guid>> templateGuidUniqueStorageDomainDic; HashMap<Guid, ArrayList<Guid>> templateGuidAllStorageDomainDic; HashMap<Guid, ArrayList<DiskImage>> templateGuidDiskImagesDic; VmImportDiskListModel importDiskListModel; ArrayList<storage_domains> allStorageDomains; int uniqueDomains; Guid templateGuid; private storage_domain_static privateSourceStorage; public storage_domain_static getSourceStorage() { return privateSourceStorage; } public void setSourceStorage(storage_domain_static value) { privateSourceStorage = value; } private storage_pool privateStoragePool; public storage_pool getStoragePool() { return privateStoragePool; } public void setStoragePool(storage_pool value) { privateStoragePool = value; } private ListModel privateDestinationStorage; public ListModel getDestinationStorage() { return privateDestinationStorage; } private void setDestinationStorage(ListModel value) { privateDestinationStorage = value; } private ListModel privateAllDestinationStorage; public ListModel getAllDestinationStorage() { return privateAllDestinationStorage; } private void setAllDestinationStorage(ListModel value) { privateAllDestinationStorage = value; } private ListModel privateCluster; public ListModel getCluster() { return privateCluster; } private void setCluster(ListModel value) { privateCluster = value; } private ListModel privateSystemDiskFormat; public ListModel getSystemDiskFormat() { return privateSystemDiskFormat; } private void setSystemDiskFormat(ListModel value) { privateSystemDiskFormat = value; } private ListModel privateDataDiskFormat; public ListModel getDataDiskFormat() { return privateDataDiskFormat; } private void setDataDiskFormat(ListModel value) { privateDataDiskFormat = value; } private EntityModel collapseSnapshots; public EntityModel getCollapseSnapshots() { return collapseSnapshots; } public void setCollapseSnapshots(EntityModel value) { this.collapseSnapshots = value; } private boolean isMissingStorages; public boolean getIsMissingStorages() { return isMissingStorages; } public void setIsMissingStorages(boolean value) { if (isMissingStorages != value) { isMissingStorages = value; OnPropertyChanged(new PropertyChangedEventArgs("IsMissingStorages")); } } private String nameAndDescription; private AsyncQuery onCollapseSnapshotsChangedFinish; public String getNameAndDescription() { return nameAndDescription; } public void setNameAndDescription(String value) { if (!StringHelper.stringsEqual(nameAndDescription, value)) { nameAndDescription = value; OnPropertyChanged(new PropertyChangedEventArgs("NameAndDescription")); } } private java.util.List<VM> problematicItems; public java.util.List<VM> getProblematicItems() { return problematicItems; } public void setProblematicItems(java.util.List<VM> value) { if (problematicItems != value) { problematicItems = value; OnPropertyChanged(new PropertyChangedEventArgs("ProblematicItems")); } } private EntityModel privateIsSingleDestStorage; public EntityModel getIsSingleDestStorage() { return privateIsSingleDestStorage; } public void setIsSingleDestStorage(EntityModel value) { privateIsSingleDestStorage = value; } private ListModel privateStorageDoamins; public ListModel getStorageDoamins() { return privateStorageDoamins; } private void setStorageDoamins(ListModel value) { privateStorageDoamins = value; } private HashMap<Guid, HashMap<Guid, Guid>> privateDiskStorageMap; public HashMap<Guid, HashMap<Guid, Guid>> getDiskStorageMap() { return privateDiskStorageMap; } public void setDiskStorageMap(HashMap<Guid, HashMap<Guid, Guid>> value) { privateDiskStorageMap = value; } @Override public void setSelectedItem(Object value) { super.setSelectedItem(value); OnEntityChanged(); } public ImportVmModel() { setProblematicItems(new ArrayList<VM>()); setCollapseSnapshots(new EntityModel()); getCollapseSnapshots().setEntity(false); getCollapseSnapshots().getPropertyChangedEvent().addListener( new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { OnCollapseSnapshotsChanged(); } }); setDestinationStorage(new ListModel()); getDestinationStorage().getSelectedItemChangedEvent().addListener( new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { DestinationStorage_SelectedItemChanged(); } }); setCluster(new ListModel()); setSystemDiskFormat(new ListModel()); setDataDiskFormat(new ListModel()); setDiskStorageMap(new HashMap<Guid, HashMap<Guid, Guid>>()); setIsSingleDestStorage(new EntityModel()); getIsSingleDestStorage().setEntity(true); setAllDestinationStorage(new ListModel()); } public void OnCollapseSnapshotsChanged(AsyncQuery _asyncQuery) { this.onCollapseSnapshotsChangedFinish = _asyncQuery; OnCollapseSnapshotsChanged(); } public void initStorageDomains() { templateGuidUniqueStorageDomainDic = new java.util.HashMap<Guid, ArrayList<Guid>>(); templateGuidAllStorageDomainDic = new java.util.HashMap<Guid, ArrayList<Guid>>(); templateGuidDiskImagesDic = new java.util.HashMap<Guid, ArrayList<DiskImage>>(); uniqueDomains = 0; for (Object item : getItems()) { VM vm = (VM) item; templateGuid = vm.getvmt_guid(); if (templateGuid.equals(NGuid.Empty)) { uniqueDomains++; templateGuidUniqueStorageDomainDic.put(templateGuid, null); templateGuidAllStorageDomainDic.put(templateGuid, null); } else { AsyncDataProvider.GetTemplateDiskList(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { ImportVmModel importVmModel = (ImportVmModel) target; ArrayList<DiskImage> disks = (ArrayList<DiskImage>) returnValue; ArrayList<ArrayList<Guid>> allSourceStorages = new ArrayList<ArrayList<Guid>>(); for (DiskImage disk : disks) { allSourceStorages.add(disk.getstorage_ids()); } ArrayList<Guid> intersectStorageDomains = Linq.Intersection(allSourceStorages); ArrayList<Guid> unionStorageDomains = Linq.Union(allSourceStorages); uniqueDomains++; templateGuidUniqueStorageDomainDic.put(importVmModel.templateGuid, intersectStorageDomains); templateGuidAllStorageDomainDic.put(importVmModel.templateGuid, unionStorageDomains); templateGuidDiskImagesDic.put(importVmModel.templateGuid, disks); importVmModel.postInitStorageDomains(); } }), templateGuid); } } postInitStorageDomains(); } protected void postInitStorageDomains() { if (templateGuidUniqueStorageDomainDic.size() != uniqueDomains) { return; } AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.Model = this; _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model, Object returnValue) { allStorageDomains = (ArrayList<storage_domains>) returnValue; OnCollapseSnapshotsChanged(); initDiskStorageMap(); } }; AsyncDataProvider.GetDataDomainsListByDomain(_asyncQuery, this.getSourceStorage().getId()); } private void initDiskStorageMap() { for (Object item : getItems()) { VM vm = (VM) item; for (DiskImage disk : vm.getDiskMap().values()) { if (NGuid.Empty.equals(vm.getvmt_guid())) { Guid storageId = !allDestStorages.isEmpty() ? allDestStorages.get(0).getId() : new Guid(); addToDiskStorageMap(vm.getId(), disk, storageId); } else { ArrayList<Guid> storageIds = templateGuidUniqueStorageDomainDic.get(vm.getvmt_guid()); Guid storageId = storageIds != null ? templateGuidUniqueStorageDomainDic.get(vm.getvmt_guid()).get(0) : new Guid(); addToDiskStorageMap(vm.getId(), disk, storageId); } } } } public void OnCollapseSnapshotsChanged() { if (this.getItems() == null || allStorageDomains == null) { return; } selectedDestinationStorage = null; sameSelectedDestinationStorage = false; uniqueDestStorages = new ArrayList<storage_domains>(); allDestStorages = new ArrayList<storage_domains>(); setIsMissingStorages(false); if (getDestinationStorage().getSelectedItem() != null) { selectedDestinationStorage = (storage_domains) getDestinationStorage().getSelectedItem(); } for (storage_domains domain : allStorageDomains) { boolean addStorage = false; if (Linq.IsDataActiveStorageDomain(domain)) { allDestStorages.add(domain); if (((Boolean) getCollapseSnapshots().getEntity()).equals(true)) { addStorage = true; } else { for (Map.Entry<Guid, ArrayList<Guid>> keyValuePair : templateGuidUniqueStorageDomainDic.entrySet()) { if (NGuid.Empty.equals(keyValuePair.getKey())) { addStorage = true; } else { addStorage = false; for (Guid storageDomainId : keyValuePair.getValue()) { if (storageDomainId.equals(domain.getId())) { addStorage = true; break; } } } if (addStorage == false) { break; } } } } else { for (Map.Entry<Guid, ArrayList<Guid>> keyValuePair : templateGuidAllStorageDomainDic.entrySet()) { if (!NGuid.Empty.equals(keyValuePair.getKey())) { for (Guid storageDomainId : keyValuePair.getValue()) { if (storageDomainId.equals(domain.getId())) { setIsMissingStorages(true); break; } } } } } if (addStorage) { uniqueDestStorages.add(domain); if (sameSelectedDestinationStorage == false && domain.equals(selectedDestinationStorage)) { sameSelectedDestinationStorage = true; selectedDestinationStorage = domain; } } } getAllDestinationStorage().setItems(allDestStorages); getDestinationStorage().setItems(uniqueDestStorages); if (sameSelectedDestinationStorage) { getDestinationStorage().setSelectedItem(selectedDestinationStorage); } else { getDestinationStorage().setSelectedItem(Linq.FirstOrDefault(uniqueDestStorages)); } if (getDetailModels() != null && getActiveDetailModel() instanceof VmImportDiskListModel) { VmImportDiskListModel detailModel = (VmImportDiskListModel) getActiveDetailModel(); detailModel .setCollapseSnapshots((Boolean) getCollapseSnapshots() .getEntity()); } if (onCollapseSnapshotsChangedFinish != null) { onCollapseSnapshotsChangedFinish.asyncCallback.OnSuccess( onCollapseSnapshotsChangedFinish.getModel(), null); onCollapseSnapshotsChangedFinish = null; } } @Override protected void ActiveDetailModelChanged() { super.ActiveDetailModelChanged(); OnCollapseSnapshotsChanged(); } @Override protected void InitDetailModels() { super.InitDetailModels(); importDiskListModel = new VmImportDiskListModel(); ObservableCollection<EntityModel> list = new ObservableCollection<EntityModel>(); list.add(new VmGeneralModel()); list.add(new VmImportInterfaceListModel()); list.add(importDiskListModel); list.add(new VmAppListModel()); setDetailModels(list); } public boolean Validate() { getDestinationStorage().ValidateSelectedItem( new IValidation[] { new NotEmptyValidation() }); getCluster().ValidateSelectedItem( new IValidation[] { new NotEmptyValidation() }); return getDestinationStorage().getIsValid() && getCluster().getIsValid(); } @Override protected void OnSelectedItemChanged() { super.OnSelectedItemChanged(); if (getSelectedItem() != null) { VM vm = (VM) getSelectedItem(); setNameAndDescription(StringFormat.format("%1$s%2$s", vm.getvm_name(), !StringHelper.isNullOrEmpty(vm.getvm_description()) ? " [" + vm.getvm_description() + "]" : "")); } else { setNameAndDescription(""); } } public void setItems(Iterable value) { super.setItems(value); for (Object vm : getItems()) { getDiskStorageMap().put(((VM) vm).getId(), new HashMap<Guid, Guid>()); } initStorageDomains(); } @Override protected String getListName() { return "ImportVmModel"; } public void setSelectedVMsCount(int size) { importDiskListModel.setSelectedVMsCount(((List) getItems()).size()); } storage_domains currStorageDomain = null; private void DestinationStorage_SelectedItemChanged() { storage_domains selectedStorageDomain = (storage_domains) getDestinationStorage().getSelectedItem(); List destinationStorageDomains = ((List) getDestinationStorage().getItems()); if (selectedStorageDomain == null && !destinationStorageDomains.isEmpty()) { selectedStorageDomain = (storage_domains) destinationStorageDomains.get(0); } if (currStorageDomain == null || selectedStorageDomain == null || !currStorageDomain.getQueryableId().equals(selectedStorageDomain.getQueryableId())) { currStorageDomain = selectedStorageDomain; UpdateImportWarnings(); } } public void DestinationStorage_SelectedItemChanged(DiskImage disk, String storageDomainName) { VM item = (VM) getSelectedItem(); addToDiskStorageMap(item.getId(), disk, getStorageDomainByName(storageDomainName).getId()); } public void addToDiskStorageMap(Guid vmId, DiskImage disk, Guid storageId) { HashMap<Guid, Guid> vmDiskStorageMap = getDiskStorageMap().get(vmId); vmDiskStorageMap.put(disk.getId(), storageId); } private storage_domains getStorageDomainByName(String storageDomainName) { storage_domains storage = null; for (Object storageDomain : getDestinationStorage().getItems()) { storage = (storage_domains) storageDomain; if (storageDomainName.equals(storage.getstorage_name())) { break; } } return storage; } @Override protected void ItemsChanged() { super.ItemsChanged(); UpdateImportWarnings(); } public VmImportDiskListModel getImportDiskListModel() { return importDiskListModel; } private void UpdateImportWarnings() { // Clear problematic state. getProblematicItems().clear(); if (getItems() == null) { return; } storage_domains destinationStorage = (storage_domains) getDestinationStorage() .getSelectedItem(); for (Object item : getItems()) { VM vm = (VM) item; if (vm.getDiskMap() != null) { for (java.util.Map.Entry<String, DiskImage> pair : vm .getDiskMap().entrySet()) { DiskImage disk = pair.getValue(); if (disk.getvolume_type() == VolumeType.Sparse && disk.getvolume_format() == VolumeFormat.RAW && destinationStorage != null && (destinationStorage.getstorage_type() == StorageType.ISCSI || destinationStorage .getstorage_type() == StorageType.FCP)) { getProblematicItems().add(vm); } } } } // Decide what to do with the CollapseSnapshots option. if (problematicItems.size() > 0) { if (problematicItems.size() == Linq.Count(getItems())) { // All items are problematic. getCollapseSnapshots().setIsChangable(false); getCollapseSnapshots().setEntity(true); getCollapseSnapshots() .setMessage( "Note that all snapshots will be collapsed due to different storage types"); } else { // Some items are problematic. getCollapseSnapshots() .setMessage( "Use a separate import operation for the marked VMs or\nApply \"Collapse Snapshots\" for all VMs"); } } else { // No problematic items. getCollapseSnapshots().setIsChangable(true); getCollapseSnapshots().setMessage(null); } } public void VolumeType_SelectedItemChanged(DiskImage disk, VolumeType tempVolumeType) { for (Object item : getItems()) { VM vm = (VM) item; java.util.HashMap<String, DiskImageBase> diskDictionary = new java.util.HashMap<String, DiskImageBase>(); for (java.util.Map.Entry<String, DiskImage> a : vm.getDiskMap() .entrySet()) { if (a.getValue().getQueryableId().equals(disk.getQueryableId())) { a.getValue().setvolume_type(tempVolumeType); break; } } } } public ArrayList<String> getAvailableStorageDomainsByDiskId(Guid diskId) { ArrayList<String> storageDomains = null; ArrayList<Guid> storageDomainsIds = getImportDiskListModel().getAvailableStorageDomainsByDiskId(diskId); if (storageDomainsIds != null) { storageDomains = new ArrayList<String>(); for (Guid storageId : storageDomainsIds) { if (Linq.IsActiveStorageDomain(getStorageById(storageId))) { storageDomains.add(getStorageNameById(storageId)); } } } if (storageDomains != null) { Collections.sort(storageDomains); } return storageDomains; } public String getStorageNameById(NGuid storageId) { String storageName = ""; for (Object storageDomain : getAllDestinationStorage().getItems()) { storage_domains storage = (storage_domains) storageDomain; if (storage.getId().equals(storageId)) { storageName = storage.getstorage_name(); } } return storageName; } public storage_domains getStorageById(Guid storageId) { for (storage_domains storage : allDestStorages) { if (storage.getId().equals(storageId)) { return storage; } } return null; } }
Dhandapani/gluster-ovirt
frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/vms/ImportVmModel.java
Java
apache-2.0
23,592
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Ais.Internal.Dcm.ModernUIV2")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Ais.Internal.Dcm.ModernUIV2")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
AppliedIS/wams-manager
Source/Ais.Internal.Dcm/Ais.Internal.Dcm.ModernUIV2/Properties/AssemblyInfo.cs
C#
apache-2.0
2,263
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Wpf.Mvvm.TestHarness")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Wpf.Mvvm.TestHarness")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
oriches/Simple.Wpf.FSharp.Repl
Wpf.Mvvm.TestHarness/Properties/AssemblyInfo.cs
C#
apache-2.0
2,236
package com.pengrad.telegrambot.request; import com.pengrad.telegrambot.response.BaseResponse; /** * Mirco Ianese * 07 December 2021 */ public class UnbanChatSenderChat extends BaseRequest<UnbanChatSenderChat, BaseResponse> { public UnbanChatSenderChat(Object chatId, long sender_chat_id) { super(BaseResponse.class); add("chat_id", chatId).add("sender_chat_id", sender_chat_id); } }
pengrad/java-telegram-bot-api
library/src/main/java/com/pengrad/telegrambot/request/UnbanChatSenderChat.java
Java
apache-2.0
415
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace DevZH.UI { [StructLayout(LayoutKind.Sequential)] public struct InitOptions { public UIntPtr Size; } }
noliar/DevZH.UI
src/DevZH.UI/InitOptions.cs
C#
apache-2.0
275
/** * @author: Alberto Cerqueira * @email: alberto.cerqueira1990@gmail.com */ jQuery.controller = function() { var controllerClass = function() { this.init = (function(){ $("#gravar").click(function(){ _self.gravar(); return false; }); }); this.gravar = (function() { $("#manterEntidade").ajaxSubmit({ url : systemURL, dataType : "json", success : (function(jsonReturn){ var consequence = jsonReturn.consequence; if (consequence == "ERRO") { alert(jsonReturn.message); } else if (consequence == "SUCESSO") { alert(jsonReturn.message + ": " + jsonReturn.dado.toString()); } else if(consequence == "MUITOS_ERROS"){ var mensagem = ['']; jQuery.each(jsonReturn.dado, function(i, dado) { mensagem.push(dado.localizedMessage + "\n"); }); alert(mensagem.join('')); } //location.reload(); }), error : (function(XMLHttpRequest, textStatus, errorThrown){ alert(errorConexao); }) }); }); var _self = this; }; return new controllerClass(); };
g6tech/spring-corp-test
project/viewria/WebContent/app/controller/controller.js
JavaScript
apache-2.0
1,076
/* * Copyright (c) 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 li.allan.easycache.config; import li.allan.easycache.CacheKeyGenerator; import li.allan.easycache.LocalCacheConfig; /** * @author lialun */ public class ConfigProperties { private LocalCacheConfig localCacheConfig; private CacheKeyGenerator cacheKeyGenerator; public LocalCacheConfig getLocalCacheConfig() { return localCacheConfig; } public void setLocalCacheConfig(LocalCacheConfig localCacheConfig) { this.localCacheConfig = localCacheConfig; } public CacheKeyGenerator getCacheKeyGenerator() { return cacheKeyGenerator; } public void setCacheKeyGenerator(CacheKeyGenerator cacheKeyGenerator) { this.cacheKeyGenerator = cacheKeyGenerator; } }
lialun/EasyCache
easycache/src/main/java/li/allan/easycache/config/ConfigProperties.java
Java
apache-2.0
1,360
# # 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 solum.api.controllers import common_types from solum.api.controllers.v1.datamodel import types as api_types #from solum.openstack.common import log as logging #LOG = logging.getLogger(__name__) class Extensions(api_types.Base): """extensions resource""" extension_links = [common_types.Link] """This attribute contains Links to extension resources that contain information about the extensions supported by this Platform.""" def __init__(self, **kwds): # LOG.debug("extensions constructor: %s" % kwds) super(Extensions, self).__init__(**kwds)
gilbertpilz/solum
solum/api/controllers/camp/v1_1/datamodel/extensions.py
Python
apache-2.0
1,139
<div class='row row-pad'> <div class='col-sm-2 col-md-2 col-lg-2 text-center'> <h5>Quick Menu</h5> </div> <div class='col-sm-8 col-md-8 col-lg-8 text-center'> <h5>Videos</h5> </div> <div class='col-sm-2 col-md-2 col-lg-2 text-center'> <h5>Following</h5> </div> </div> <div class='row row-pad'> <div class='col-sm-2 col-md-2 col-lg-2'> <?= $videoNav ?> </div> <div class='col-sm-8 col-md-8 col-lg-8'> <div class='row well row-pad'> <?php if (count($videos) > 0): ?> <div class='row scroll-h'> <div class='scroll-h-inner row-pad'> <?php foreach ($videos as $video): ?> <span class='vid-thumb-container'> <a href="/videos/single/<?= $video->id ?>"> <h4><?= $video->title; ?></h4> <img class='vid-thumb' src=<?= $video->thumbnail ?>> </a> </span> <?php endforeach; ?> </div> </div> <?php else: ?> <div class='well well-sm'> It looks like this user has no videos yet! </div> <?php endif; ?> </div> </div> <div class='col-sm-2 col-md-2 col-lg-2'> <?= $friendsNav ?> </div> </div>
karlmoser/Video-Annotation
web/public/application/views/parts/main.php
PHP
apache-2.0
1,103
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.appsync.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/appsync-2017-07-25/GetFunction" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetFunctionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The <code>Function</code> object. * </p> */ private FunctionConfiguration functionConfiguration; /** * <p> * The <code>Function</code> object. * </p> * * @param functionConfiguration * The <code>Function</code> object. */ public void setFunctionConfiguration(FunctionConfiguration functionConfiguration) { this.functionConfiguration = functionConfiguration; } /** * <p> * The <code>Function</code> object. * </p> * * @return The <code>Function</code> object. */ public FunctionConfiguration getFunctionConfiguration() { return this.functionConfiguration; } /** * <p> * The <code>Function</code> object. * </p> * * @param functionConfiguration * The <code>Function</code> object. * @return Returns a reference to this object so that method calls can be chained together. */ public GetFunctionResult withFunctionConfiguration(FunctionConfiguration functionConfiguration) { setFunctionConfiguration(functionConfiguration); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getFunctionConfiguration() != null) sb.append("FunctionConfiguration: ").append(getFunctionConfiguration()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetFunctionResult == false) return false; GetFunctionResult other = (GetFunctionResult) obj; if (other.getFunctionConfiguration() == null ^ this.getFunctionConfiguration() == null) return false; if (other.getFunctionConfiguration() != null && other.getFunctionConfiguration().equals(this.getFunctionConfiguration()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getFunctionConfiguration() == null) ? 0 : getFunctionConfiguration().hashCode()); return hashCode; } @Override public GetFunctionResult clone() { try { return (GetFunctionResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-appsync/src/main/java/com/amazonaws/services/appsync/model/GetFunctionResult.java
Java
apache-2.0
4,022
/* * Copyright 2008-2010 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 groovy.lang; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Field annotation to simplify lazy initialization. * <p> * Example usage without any special modifiers just defers initialization until the first call but is not thread-safe: * <pre> * {@code @Lazy} T x * </pre> * becomes * <pre> * private T $x * * T getX() { * if ($x != null) * return $x * else { * $x = new T() * return $x * } * } * </pre> * * If the field is declared volatile then initialization will be synchronized using * the <a href="http://en.wikipedia.org/wiki/Double-checked_locking">double-checked locking</a> pattern as shown here: * * <pre> * {@code @Lazy} volatile T x * </pre> * becomes * <pre> * private volatile T $x * * T getX() { * T $x_local = $x * if ($x_local != null) * return $x_local * else { * synchronized(this) { * if ($x == null) { * $x = new T() * } * return $x * } * } * } * </pre> * * By default a field will be initialized by calling its default constructor. * * If the field has an initial value expression then this expression will be used instead of calling the default constructor. * In particular, it is possible to use closure <code>{ ... } ()</code> syntax as follows: * * <pre> * {@code @Lazy} T x = { [1, 2, 3] } () * </pre> * becomes * <pre> * private T $x * * T getX() { * T $x_local = $x * if ($x_local != null) * return $x_local * else { * synchronized(this) { * if ($x == null) { * $x = { [1, 2, 3] } () * } * return $x * } * } * } * </pre> * <p> * <code>@Lazy(soft=true)</code> will use a soft reference instead of the field and use the above rules each time re-initialization is required. * <p> * If the <code>soft</code> flag for the annotation is not set but the field is static, then * the <a href="http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom">initialization on demand holder idiom</a> is * used as follows: * <pre> * {@code @Lazy} static FieldType field * {@code @Lazy} static Date date1 * {@code @Lazy} static Date date2 = { new Date().updated(year: 2000) }() * {@code @Lazy} static Date date3 = new GregorianCalendar(2009, Calendar.JANUARY, 1).time * </pre> * becomes these methods and inners classes within the class containing the above definitions: * <pre> * private static class FieldTypeHolder_field { * private static final FieldType INSTANCE = new FieldType() * } * * private static class DateHolder_date1 { * private static final Date INSTANCE = new Date() * } * * private static class DateHolder_date2 { * private static final Date INSTANCE = { new Date().updated(year: 2000) }() * } * * private static class DateHolder_date3 { * private static final Date INSTANCE = new GregorianCalendar(2009, Calendar.JANUARY, 1).time * } * * static FieldType getField() { * return FieldTypeHolder_field.INSTANCE * } * * static Date getDate1() { * return DateHolder_date1.INSTANCE * } * * static Date getDate2() { * return DateHolder_date2.INSTANCE * } * * static Date getDate3() { * return DateHolder_date3.INSTANCE * } * </pre> * * @author Alex Tkachman * @author Paul King */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.FIELD}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.LazyASTTransformation") public @interface Lazy { /** * @return if field should be soft referenced instead of hard referenced */ boolean soft () default false; }
Selventa/model-builder
tools/groovy/src/src/main/groovy/lang/Lazy.java
Java
apache-2.0
4,644
/* * Copyright 2013-present Facebook, 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 com.facebook.buck.event.listener; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; import com.facebook.buck.artifact_cache.ArtifactCacheConnectEvent; import com.facebook.buck.artifact_cache.CacheResult; import com.facebook.buck.artifact_cache.HttpArtifactCacheEvent; import com.facebook.buck.event.CommandEvent; import com.facebook.buck.artifact_cache.HttpArtifactCacheEventFetchData; import com.facebook.buck.event.ArtifactCompressionEvent; import com.facebook.buck.event.BuckEventBus; import com.facebook.buck.event.BuckEventBusFactory; import com.facebook.buck.event.ChromeTraceEvent; import com.facebook.buck.event.CompilerPluginDurationEvent; import com.facebook.buck.event.PerfEventId; import com.facebook.buck.event.SimplePerfEvent; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.jvm.java.AnnotationProcessingEvent; import com.facebook.buck.jvm.java.tracing.JavacPhaseEvent; import com.facebook.buck.log.InvocationInfo; import com.facebook.buck.model.BuildId; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.rules.BuildEvent; import com.facebook.buck.rules.BuildRuleEvent; import com.facebook.buck.rules.BuildRuleKeys; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.BuildRuleStatus; import com.facebook.buck.rules.BuildRuleSuccessType; import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer; import com.facebook.buck.rules.FakeBuildRule; import com.facebook.buck.rules.RuleKey; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.step.StepEvent; import com.facebook.buck.timing.Clock; import com.facebook.buck.timing.FakeClock; import com.facebook.buck.timing.IncrementingFakeClock; import com.facebook.buck.util.HumanReadableException; import com.facebook.buck.util.ObjectMappers; import com.facebook.buck.util.perf.PerfStatsTracking; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.gson.Gson; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPInputStream; public class ChromeTraceBuildListenerTest { private static final long TIMESTAMP_NANOS = 1409702151000000000L; private static final String EXPECTED_DIR = "buck-out/log/2014-09-02_23h55m51s_no_sub_command_BUILD_ID/"; @Rule public TemporaryFolder tmpDir = new TemporaryFolder(); private InvocationInfo invocationInfo; @Before public void setUp() throws IOException { invocationInfo = InvocationInfo.builder() .setTimestampMillis(TimeUnit.NANOSECONDS.toMillis(TIMESTAMP_NANOS)) .setBuckLogDir(tmpDir.getRoot().toPath().resolve("buck-out/log")) .setBuildId(new BuildId("BUILD_ID")) .setSubCommand("no_sub_command") .setIsDaemon(false) .setSuperConsoleEnabled(false) .build(); } @Test public void testDeleteFiles() throws IOException { ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath()); String tracePath = invocationInfo.getLogDirectoryPath().resolve("build.trace").toString(); File traceFile = new File(tracePath); projectFilesystem.createParentDirs(tracePath); traceFile.createNewFile(); traceFile.setLastModified(0); for (int i = 0; i < 10; ++i) { File oldResult = new File( String.format("%s/build.100%d.trace", invocationInfo.getLogDirectoryPath(), i)); oldResult.createNewFile(); oldResult.setLastModified(TimeUnit.SECONDS.toMillis(i)); } ChromeTraceBuildListener listener = new ChromeTraceBuildListener( projectFilesystem, invocationInfo, new FakeClock(TIMESTAMP_NANOS), ObjectMappers.newDefaultInstance(), Locale.US, TimeZone.getTimeZone("America/Los_Angeles"), /* tracesToKeep */ 3, false); listener.outputTrace(invocationInfo.getBuildId()); ImmutableList<String> files = FluentIterable. from(Arrays.asList(projectFilesystem.listFiles(invocationInfo.getLogDirectoryPath()))). filter(input -> input.toString().endsWith(".trace")). transform(File::getName). toList(); assertEquals(4, files.size()); assertEquals( ImmutableSortedSet.of( "build.trace", "build.1009.trace", "build.1008.trace", "build.2014-09-02.16-55-51.BUILD_ID.trace"), ImmutableSortedSet.copyOf(files)); } @Test public void testBuildJson() throws IOException { ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath()); ObjectMapper mapper = ObjectMappers.newDefaultInstance(); BuildId buildId = new BuildId("ChromeTraceBuildListenerTestBuildId"); ChromeTraceBuildListener listener = new ChromeTraceBuildListener( projectFilesystem, invocationInfo, new FakeClock(TIMESTAMP_NANOS), mapper, Locale.US, TimeZone.getTimeZone("America/Los_Angeles"), /* tracesToKeep */ 42, false); BuildTarget target = BuildTargetFactory.newInstance("//fake:rule"); FakeBuildRule rule = new FakeBuildRule( target, new SourcePathResolver( new BuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()) ), ImmutableSortedSet.of()); RuleKey ruleKey = new RuleKey("abc123"); String stepShortName = "fakeStep"; String stepDescription = "I'm a Fake Step!"; UUID stepUuid = UUID.randomUUID(); ImmutableSet<BuildTarget> buildTargets = ImmutableSet.of(target); Iterable<String> buildArgs = Iterables.transform(buildTargets, Object::toString); Clock fakeClock = new IncrementingFakeClock(TimeUnit.MILLISECONDS.toNanos(1)); BuckEventBus eventBus = BuckEventBusFactory.newInstance(fakeClock, buildId); eventBus.register(listener); CommandEvent.Started commandEventStarted = CommandEvent.started( "party", ImmutableList.of("arg1", "arg2"), /* isDaemon */ true); eventBus.post(commandEventStarted); eventBus.post(new PerfStatsTracking.MemoryPerfStatsEvent( /* freeMemoryBytes */ 1024 * 1024L, /* totalMemoryBytes */ 3 * 1024 * 1024L, /* timeSpentInGcMs */ -1, /* currentMemoryBytesUsageByPool */ ImmutableMap.of("flower", 42L * 1024 * 1024))); ArtifactCacheConnectEvent.Started artifactCacheConnectEventStarted = ArtifactCacheConnectEvent.started(); eventBus.post(artifactCacheConnectEventStarted); eventBus.post(ArtifactCacheConnectEvent.finished(artifactCacheConnectEventStarted)); BuildEvent.Started buildEventStarted = BuildEvent.started(buildArgs); eventBus.post(buildEventStarted); HttpArtifactCacheEvent.Started artifactCacheEventStarted = HttpArtifactCacheEvent.newFetchStartedEvent(ruleKey); eventBus.post(artifactCacheEventStarted); eventBus.post( HttpArtifactCacheEvent.newFinishedEventBuilder(artifactCacheEventStarted) .setFetchDataBuilder( HttpArtifactCacheEventFetchData.builder() .setFetchResult(CacheResult.hit("http"))) .build()); ArtifactCompressionEvent.Started artifactCompressionStartedEvent = ArtifactCompressionEvent.started( ArtifactCompressionEvent.Operation.COMPRESS, ImmutableSet.of(ruleKey)); eventBus.post(artifactCompressionStartedEvent); eventBus.post(ArtifactCompressionEvent.finished(artifactCompressionStartedEvent)); eventBus.post(BuildRuleEvent.started(rule)); eventBus.post(StepEvent.started(stepShortName, stepDescription, stepUuid)); JavacPhaseEvent.Started runProcessorsStartedEvent = JavacPhaseEvent.started( target, JavacPhaseEvent.Phase.RUN_ANNOTATION_PROCESSORS, ImmutableMap.of()); eventBus.post(runProcessorsStartedEvent); String annotationProcessorName = "com.facebook.FakeProcessor"; AnnotationProcessingEvent.Operation operation = AnnotationProcessingEvent.Operation.PROCESS; int annotationRound = 1; boolean isLastRound = false; AnnotationProcessingEvent.Started annotationProcessingEventStarted = AnnotationProcessingEvent.started( target, annotationProcessorName, operation, annotationRound, isLastRound); eventBus.post(annotationProcessingEventStarted); HttpArtifactCacheEvent.Scheduled httpScheduled = HttpArtifactCacheEvent.newStoreScheduledEvent( Optional.of("TARGET_ONE"), ImmutableSet.of(ruleKey)); HttpArtifactCacheEvent.Started httpStarted = HttpArtifactCacheEvent.newStoreStartedEvent(httpScheduled); eventBus.post(httpStarted); HttpArtifactCacheEvent.Finished httpFinished = HttpArtifactCacheEvent.newFinishedEventBuilder(httpStarted).build(); eventBus.post(httpFinished); final CompilerPluginDurationEvent.Started processingPartOneStarted = CompilerPluginDurationEvent.started( target, annotationProcessorName, "processingPartOne", ImmutableMap.of()); eventBus.post(processingPartOneStarted); eventBus.post( CompilerPluginDurationEvent.finished( processingPartOneStarted, ImmutableMap.of())); eventBus.post(AnnotationProcessingEvent.finished(annotationProcessingEventStarted)); eventBus.post( JavacPhaseEvent.finished(runProcessorsStartedEvent, ImmutableMap.of())); eventBus.post(StepEvent.finished( StepEvent.started(stepShortName, stepDescription, stepUuid), 0)); eventBus.post( BuildRuleEvent.finished( rule, BuildRuleKeys.of(ruleKey), BuildRuleStatus.SUCCESS, CacheResult.miss(), Optional.of(BuildRuleSuccessType.BUILT_LOCALLY), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty())); try (final SimplePerfEvent.Scope scope1 = SimplePerfEvent.scope( eventBus, PerfEventId.of("planning"), ImmutableMap.<String, Object>of("nefarious", "true"))) { try (final SimplePerfEvent.Scope scope2 = SimplePerfEvent.scope( eventBus, PerfEventId.of("scheming"))) { scope2.appendFinishedInfo("success", "false"); } } eventBus.post(BuildEvent.finished(buildEventStarted, 0)); eventBus.post(CommandEvent.finished(commandEventStarted, /* exitCode */ 0)); listener.outputTrace(new BuildId("BUILD_ID")); File resultFile = new File(tmpDir.getRoot(), "buck-out/log/build.trace"); List<ChromeTraceEvent> originalResultList = mapper.readValue( resultFile, new TypeReference<List<ChromeTraceEvent>>() {}); List<ChromeTraceEvent> resultListCopy = new ArrayList<>(); resultListCopy.addAll(originalResultList); ImmutableMap<String, String> emptyArgs = ImmutableMap.of(); assertNextResult( resultListCopy, "process_name", ChromeTraceEvent.Phase.METADATA, ImmutableMap.of("name", "buck")); assertNextResult( resultListCopy, "party", ChromeTraceEvent.Phase.BEGIN, ImmutableMap.of("command_args", "arg1 arg2")); assertNextResult( resultListCopy, "memory", ChromeTraceEvent.Phase.COUNTER, ImmutableMap.of( "used_memory_mb", "2", "free_memory_mb", "1", "total_memory_mb", "3", "time_spent_in_gc_sec", "0", "pool_flower_mb", "42")); assertNextResult( resultListCopy, "artifact_connect", ChromeTraceEvent.Phase.BEGIN, emptyArgs); assertNextResult( resultListCopy, "artifact_connect", ChromeTraceEvent.Phase.END, emptyArgs); assertNextResult( resultListCopy, "build", ChromeTraceEvent.Phase.BEGIN, emptyArgs); assertNextResult( resultListCopy, "http_artifact_fetch", ChromeTraceEvent.Phase.BEGIN, ImmutableMap.of("rule_key", "abc123")); assertNextResult( resultListCopy, "http_artifact_fetch", ChromeTraceEvent.Phase.END, ImmutableMap.of( "rule_key", "abc123", "success", "true", "cache_result", "HTTP_HIT")); assertNextResult( resultListCopy, "artifact_compress", ChromeTraceEvent.Phase.BEGIN, ImmutableMap.of("rule_key", "abc123")); assertNextResult( resultListCopy, "artifact_compress", ChromeTraceEvent.Phase.END, ImmutableMap.of("rule_key", "abc123")); // BuildRuleEvent.Started assertNextResult( resultListCopy, "//fake:rule", ChromeTraceEvent.Phase.BEGIN, ImmutableMap.of()); assertNextResult( resultListCopy, "fakeStep", ChromeTraceEvent.Phase.BEGIN, emptyArgs); assertNextResult( resultListCopy, "run annotation processors", ChromeTraceEvent.Phase.BEGIN, emptyArgs); assertNextResult( resultListCopy, "com.facebook.FakeProcessor.process", ChromeTraceEvent.Phase.BEGIN, emptyArgs); assertNextResult( resultListCopy, "http_artifact_store", ChromeTraceEvent.Phase.BEGIN, ImmutableMap.of( "rule_key", "abc123")); assertNextResult( resultListCopy, "http_artifact_store", ChromeTraceEvent.Phase.END, ImmutableMap.of( "success", "true", "rule_key", "abc123")); assertNextResult( resultListCopy, "processingPartOne", ChromeTraceEvent.Phase.BEGIN, emptyArgs); assertNextResult( resultListCopy, "processingPartOne", ChromeTraceEvent.Phase.END, emptyArgs); assertNextResult( resultListCopy, "com.facebook.FakeProcessor.process", ChromeTraceEvent.Phase.END, emptyArgs); assertNextResult( resultListCopy, "run annotation processors", ChromeTraceEvent.Phase.END, emptyArgs); assertNextResult( resultListCopy, "fakeStep", ChromeTraceEvent.Phase.END, ImmutableMap.of( "description", "I'm a Fake Step!", "exit_code", "0")); assertNextResult( resultListCopy, "//fake:rule", ChromeTraceEvent.Phase.END, ImmutableMap.of( "cache_result", "miss", "success_type", "BUILT_LOCALLY")); assertNextResult( resultListCopy, "planning", ChromeTraceEvent.Phase.BEGIN, ImmutableMap.of("nefarious", "true")); assertNextResult( resultListCopy, "scheming", ChromeTraceEvent.Phase.BEGIN, emptyArgs); assertNextResult( resultListCopy, "scheming", ChromeTraceEvent.Phase.END, ImmutableMap.of("success", "false")); assertNextResult( resultListCopy, "planning", ChromeTraceEvent.Phase.END, emptyArgs); assertNextResult( resultListCopy, "build", ChromeTraceEvent.Phase.END, emptyArgs); assertNextResult( resultListCopy, "party", ChromeTraceEvent.Phase.END, ImmutableMap.of( "command_args", "arg1 arg2", "daemon", "true")); assertEquals(0, resultListCopy.size()); } private static void assertNextResult( List<ChromeTraceEvent> resultList, String expectedName, ChromeTraceEvent.Phase expectedPhase, ImmutableMap<String, String> expectedArgs) { assertTrue(resultList.size() > 0); assertEquals(expectedName, resultList.get(0).getName()); assertEquals(expectedPhase, resultList.get(0).getPhase()); assertEquals(expectedArgs, resultList.get(0).getArgs()); resultList.remove(0); } @Test public void testOutputFailed() throws IOException { ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath()); assumeTrue("Can make the root directory read-only", tmpDir.getRoot().setReadOnly()); try { ChromeTraceBuildListener listener = new ChromeTraceBuildListener( projectFilesystem, invocationInfo, new FakeClock(TIMESTAMP_NANOS), ObjectMappers.newDefaultInstance(), Locale.US, TimeZone.getTimeZone("America/Los_Angeles"), /* tracesToKeep */ 3, false); listener.outputTrace(invocationInfo.getBuildId()); fail("Expected an exception."); } catch (HumanReadableException e) { assertEquals( "Unable to write trace file: java.nio.file.AccessDeniedException: " + projectFilesystem.resolve(projectFilesystem.getBuckPaths().getBuckOut()), e.getMessage()); } finally { tmpDir.getRoot().setWritable(true); } } @Test public void outputFileUsesCurrentTime() throws IOException { ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath()); ChromeTraceBuildListener listener = new ChromeTraceBuildListener( projectFilesystem, invocationInfo, new FakeClock(TIMESTAMP_NANOS), ObjectMappers.newDefaultInstance(), Locale.US, TimeZone.getTimeZone("America/Los_Angeles"), /* tracesToKeep */ 1, false); listener.outputTrace(invocationInfo.getBuildId()); assertTrue( projectFilesystem.exists( Paths.get(EXPECTED_DIR + "build.2014-09-02.16-55-51.BUILD_ID.trace"))); } @Test public void canCompressTraces() throws IOException { ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath()); ChromeTraceBuildListener listener = new ChromeTraceBuildListener( projectFilesystem, invocationInfo, new FakeClock(TIMESTAMP_NANOS), ObjectMappers.newDefaultInstance(), Locale.US, TimeZone.getTimeZone("America/Los_Angeles"), /* tracesToKeep */ 1, true); listener.outputTrace(invocationInfo.getBuildId()); Path tracePath = Paths.get(EXPECTED_DIR + "build.2014-09-02.16-55-51.BUILD_ID.trace.gz"); assertTrue(projectFilesystem.exists(tracePath)); BufferedReader reader = new BufferedReader( new InputStreamReader( new GZIPInputStream(projectFilesystem.newFileInputStream(tracePath)))); List<?> elements = new Gson().fromJson(reader, List.class); assertThat(elements, notNullValue()); } }
justinmuller/buck
test/com/facebook/buck/event/listener/ChromeTraceBuildListenerTest.java
Java
apache-2.0
20,351
<?php /** * Budget delivery methods. * @package Google_Api_Ads_AdWords_v201605 * @subpackage v201605 */ class BudgetBudgetDeliveryMethod { const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201605"; const XSI_TYPE = "Budget.BudgetDeliveryMethod"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } }
SonicGD/google-adwords-api-light
Google/Api/Ads/AdWords/v201605/classes/BudgetBudgetDeliveryMethod.php
PHP
apache-2.0
716
/* * Copyright (C) 2016 CaMnter yuanyu.camnter@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.camnter.savevolley.network.adapter.core; import com.camnter.savevolley.network.core.http.SaveHttpEntity; /** * Description:SaveHttpEntityAdapter * Created by:CaMnter * Time:2016-05-27 14:10 */ public interface SaveHttpEntityAdapter<T> { SaveHttpEntity adaptiveEntity(T t); }
CaMnter/SaveVolley
savevolley-network-adapter/src/main/java/com/camnter/savevolley/network/adapter/core/SaveHttpEntityAdapter.java
Java
apache-2.0
925
#include <iostream> #include <fstream> #include "disassembly/flowgraph.hpp" #include "disassembly/functionfeaturegenerator.hpp" #include "searchbackend/functionsimhashfeaturedump.hpp" // Writes a DOT file for a given graphlet. void WriteFeatureDictionaryEntry(uint64_t hashA, uint64_t hashB, const Flowgraph& graphlet) { char buf[256]; sprintf(buf, "/var/tmp/%16.16lx%16.16lx.dot", hashA, hashB); graphlet.WriteDot(std::string(buf)); } // Writes a JSON file for a given MnemTuple. void WriteFeatureDictionaryEntry(uint64_t hashA, uint64_t hashB, const MnemTuple& tuple) { char buf[256]; sprintf(buf, "/var/tmp/%16.16lx%16.16lx.json", hashA, hashB); std::ofstream jsonfile; jsonfile.open(std::string(buf)); jsonfile << "[ " << std::get<0>(tuple) << ", " << std::get<1>(tuple) << ", " << std::get<2>(tuple) << " ]" << std::endl; } // Writes an immediate that was encountered. void WriteFeatureDictionaryEntry(uint64_t hashA, uint64_t hashB, uint64_t immediate) { std::ofstream immediates; immediates.open("/var/tmp/immediates.txt", std::ofstream::out | std::ofstream::app); immediates << std::hex << hashA << " " << hashB << " " << immediate << std::endl; }
googleprojectzero/functionsimsearch
searchbackend/functionsimhashfeaturedump.cpp
C++
apache-2.0
1,200
/******************************************************************************* * Copyright 2007-2013 See AUTHORS file. * * 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 xworker.dataObject.http; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.xmeta.ActionContext; import org.xmeta.Thing; import xworker.dataObject.DataObject; public class DataObjectHttpUtils { /** * 通过给定的DataObject从httpRequest中分析参数。 */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static Object parseHttpRequestData(ActionContext actionContext){ DataObject theData = (DataObject) actionContext.get("theData"); Thing self = (Thing) actionContext.get("self"); if(theData == null){ theData = new DataObject(self); } HttpServletRequest request = (HttpServletRequest) actionContext.get("request"); Map paramMap = request.getParameterMap(); for(Thing attribute : self.getChilds("attribute")){ String name = attribute.getString("name"); if(paramMap.containsKey(name)){ theData.put(name, request.getParameter(name)); }else if("truefalse".equals(attribute.getString("inputtype"))){ //checkbox特殊处理 theData.put(name, "false"); } } return theData; } }
x-meta/xworker
xworker_dataobject/src/main/java/xworker/dataObject/http/DataObjectHttpUtils.java
Java
apache-2.0
2,037
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /* * Created by IntelliJ IDEA. * User: yole * Date: 17.11.2006 * Time: 17:36:42 */ package com.intellij.openapi.vcs.changes.patch; import com.intellij.icons.AllIcons; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.vcs.VcsBundle; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class PatchFileType implements FileType { public static final PatchFileType INSTANCE = new PatchFileType(); public static final String NAME = "PATCH"; @NotNull @NonNls public String getName() { return NAME; } @NotNull public String getDescription() { return VcsBundle.message("patch.file.type.description"); } @NotNull @NonNls public String getDefaultExtension() { return "patch"; } @Nullable public Icon getIcon() { return AllIcons.Nodes.Pointcut; } public boolean isBinary() { return false; } public boolean isReadOnly() { return false; } @Nullable @NonNls public String getCharset(@NotNull VirtualFile file, final byte[] content) { return null; } }
ernestp/consulo
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/PatchFileType.java
Java
apache-2.0
1,803