code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public static void saveAuthentication(String url, boolean isCluster, final String authenticationToken, final boolean authenticationTokenIsPrivate, final String applicationKey, final int timeToLive, final String privateKey, final HashMap<String, LinkedList<ChannelPermissions>> permissions, final OnRestWebserviceResponse onCompleted) throws IOException, InvalidBalancerServerException, OrtcAuthenticationNotAuthorizedException { String connectionUrl = url; if (isCluster) { Balancer.getServerFromBalancerAsync(url, applicationKey, new OnRestWebserviceResponse() { @Override public void run(Exception error, String response) { if(error != null){ onCompleted.run(error, null); }else{ saveAuthenticationAsync(response, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, onCompleted); } } }); }else{ saveAuthenticationAsync(connectionUrl, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, onCompleted); } } }
public class class_name { public static void saveAuthentication(String url, boolean isCluster, final String authenticationToken, final boolean authenticationTokenIsPrivate, final String applicationKey, final int timeToLive, final String privateKey, final HashMap<String, LinkedList<ChannelPermissions>> permissions, final OnRestWebserviceResponse onCompleted) throws IOException, InvalidBalancerServerException, OrtcAuthenticationNotAuthorizedException { String connectionUrl = url; if (isCluster) { Balancer.getServerFromBalancerAsync(url, applicationKey, new OnRestWebserviceResponse() { @Override public void run(Exception error, String response) { if(error != null){ onCompleted.run(error, null); // depends on control dependency: [if], data = [(error] }else{ saveAuthenticationAsync(response, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, onCompleted); // depends on control dependency: [if], data = [none] } } }); }else{ saveAuthenticationAsync(connectionUrl, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, onCompleted); } } }
public class class_name { @Override public void removePermissions(IPermission[] permissions) throws AuthorizationException { if (permissions.length > 0) { getPermissionStore().delete(permissions); if (this.cachePermissions) { removeFromPermissionsCache(permissions); } } } }
public class class_name { @Override public void removePermissions(IPermission[] permissions) throws AuthorizationException { if (permissions.length > 0) { getPermissionStore().delete(permissions); if (this.cachePermissions) { removeFromPermissionsCache(permissions); // depends on control dependency: [if], data = [none] } } } }
public class class_name { @Override public String getMetaZoneDisplayName(String mzID, NameType type) { if (mzID == null || mzID.length() == 0) { return null; } return loadMetaZoneNames(mzID).getName(type); } }
public class class_name { @Override public String getMetaZoneDisplayName(String mzID, NameType type) { if (mzID == null || mzID.length() == 0) { return null; // depends on control dependency: [if], data = [none] } return loadMetaZoneNames(mzID).getName(type); } }
public class class_name { public static void magnitude(ZMatrixD1 input , DMatrixD1 output ) { if( input.numCols != output.numCols || input.numRows != output.numRows ) { throw new IllegalArgumentException("The matrices are not all the same dimension."); } final int length = input.getDataLength(); for( int i = 0; i < length; i += 2 ) { double real = input.data[i]; double imaginary = input.data[i+1]; output.data[i/2] = Math.sqrt(real*real + imaginary*imaginary); } } }
public class class_name { public static void magnitude(ZMatrixD1 input , DMatrixD1 output ) { if( input.numCols != output.numCols || input.numRows != output.numRows ) { throw new IllegalArgumentException("The matrices are not all the same dimension."); } final int length = input.getDataLength(); for( int i = 0; i < length; i += 2 ) { double real = input.data[i]; double imaginary = input.data[i+1]; output.data[i/2] = Math.sqrt(real*real + imaginary*imaginary); // depends on control dependency: [for], data = [i] } } }
public class class_name { @Override public void handleMessage(Message message) throws Fault { String method = (String) message.get(Message.HTTP_REQUEST_METHOD); String query = (String) message.get(Message.QUERY_STRING); if (!"GET".equals(method) || StringUtils.isEmpty(query)) { return; } String baseUri = (String) message.get(Message.REQUEST_URL); String ctx = (String) message.get(Message.PATH_INFO); //cannot have two wsdl's being written for the same endpoint at the same //time as the addresses may get mixed up synchronized (message.getExchange().getEndpoint()) { Map<String, String> map = UrlUtils.parseQueryString(query); if (isRecognizedQuery(map, baseUri, ctx, message.getExchange().getEndpoint().getEndpointInfo())) { try { Conduit c = message.getExchange().getDestination().getBackChannel(message, null, null); Message mout = new MessageImpl(); mout.setExchange(message.getExchange()); message.getExchange().setOutMessage(mout); //Customize the response to 404 mout.put(Message.RESPONSE_CODE, HttpURLConnection.HTTP_NOT_FOUND); mout.put(Message.CONTENT_TYPE, "text/xml"); c.prepare(mout); OutputStream os = mout.getContent(OutputStream.class); Document doc = getDocument(message, baseUri, map, ctx, message.getExchange().getEndpoint().getEndpointInfo()); String enc = null; try { enc = doc.getXmlEncoding(); } catch (Exception ex) { //ignore - not dom level 3 } if (enc == null) { enc = "utf-8"; } XMLStreamWriter writer = null; try { writer = StaxUtils.createXMLStreamWriter(os, enc); StaxUtils.writeNode(doc, writer, true); message.getInterceptorChain().abort(); writer.flush(); os.flush(); } catch (IOException ex) { if (TraceComponent.isAnyTracingEnabled() && tc.isInfoEnabled()) { Tr.info(tc, "error.write.wsdl.stream", ex); } //LOG.log(Level.FINE, "Failure writing full wsdl to the stream", ex); //we can ignore this. Likely, whatever has requested the WSDL //has closed the connection before reading the entire wsdl. //WSDL4J has a tendency to not read the closing tags and such //and thus can sometimes hit this. In anycase, it's //pretty much ignorable and nothing we can do about it (cannot //send a fault or anything anyway } finally { if (writer != null) { try { writer.close(); } catch (Exception e) { } } try { os.close(); } catch (Exception e) { } } } catch (IOException e) { throw new Fault(e); } catch (XMLStreamException e) { throw new Fault(e); } finally { message.getExchange().setOutMessage(null); } } } } }
public class class_name { @Override public void handleMessage(Message message) throws Fault { String method = (String) message.get(Message.HTTP_REQUEST_METHOD); String query = (String) message.get(Message.QUERY_STRING); if (!"GET".equals(method) || StringUtils.isEmpty(query)) { return; } String baseUri = (String) message.get(Message.REQUEST_URL); String ctx = (String) message.get(Message.PATH_INFO); //cannot have two wsdl's being written for the same endpoint at the same //time as the addresses may get mixed up synchronized (message.getExchange().getEndpoint()) { Map<String, String> map = UrlUtils.parseQueryString(query); if (isRecognizedQuery(map, baseUri, ctx, message.getExchange().getEndpoint().getEndpointInfo())) { try { Conduit c = message.getExchange().getDestination().getBackChannel(message, null, null); Message mout = new MessageImpl(); mout.setExchange(message.getExchange()); message.getExchange().setOutMessage(mout); //Customize the response to 404 mout.put(Message.RESPONSE_CODE, HttpURLConnection.HTTP_NOT_FOUND); mout.put(Message.CONTENT_TYPE, "text/xml"); c.prepare(mout); OutputStream os = mout.getContent(OutputStream.class); Document doc = getDocument(message, baseUri, map, ctx, message.getExchange().getEndpoint().getEndpointInfo()); String enc = null; try { enc = doc.getXmlEncoding(); } catch (Exception ex) { //ignore - not dom level 3 } if (enc == null) { enc = "utf-8"; } XMLStreamWriter writer = null; try { writer = StaxUtils.createXMLStreamWriter(os, enc); StaxUtils.writeNode(doc, writer, true); message.getInterceptorChain().abort(); writer.flush(); os.flush(); } catch (IOException ex) { if (TraceComponent.isAnyTracingEnabled() && tc.isInfoEnabled()) { Tr.info(tc, "error.write.wsdl.stream", ex); // depends on control dependency: [if], data = [none] } //LOG.log(Level.FINE, "Failure writing full wsdl to the stream", ex); //we can ignore this. Likely, whatever has requested the WSDL //has closed the connection before reading the entire wsdl. //WSDL4J has a tendency to not read the closing tags and such //and thus can sometimes hit this. In anycase, it's //pretty much ignorable and nothing we can do about it (cannot //send a fault or anything anyway } finally { if (writer != null) { try { writer.close(); // depends on control dependency: [try], data = [none] } catch (Exception e) { } // depends on control dependency: [catch], data = [none] } try { os.close(); // depends on control dependency: [try], data = [none] } catch (Exception e) { } // depends on control dependency: [catch], data = [none] } } catch (IOException e) { throw new Fault(e); } catch (XMLStreamException e) { throw new Fault(e); } finally { message.getExchange().setOutMessage(null); } } } } }
public class class_name { private void loadBinlogImage() { ResultSetPacket rs = null; try { rs = query("show variables like 'binlog_row_image'"); } catch (IOException e) { throw new CanalParseException(e); } List<String> columnValues = rs.getFieldValues(); if (columnValues == null || columnValues.size() != 2) { // 可能历时版本没有image特性 binlogImage = BinlogImage.FULL; } else { binlogImage = BinlogImage.valuesOf(columnValues.get(1)); } if (binlogFormat == null) { throw new IllegalStateException("unexpected binlog image query result:" + rs.getFieldValues()); } } }
public class class_name { private void loadBinlogImage() { ResultSetPacket rs = null; try { rs = query("show variables like 'binlog_row_image'"); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new CanalParseException(e); } // depends on control dependency: [catch], data = [none] List<String> columnValues = rs.getFieldValues(); if (columnValues == null || columnValues.size() != 2) { // 可能历时版本没有image特性 binlogImage = BinlogImage.FULL; // depends on control dependency: [if], data = [none] } else { binlogImage = BinlogImage.valuesOf(columnValues.get(1)); // depends on control dependency: [if], data = [(columnValues] } if (binlogFormat == null) { throw new IllegalStateException("unexpected binlog image query result:" + rs.getFieldValues()); } } }
public class class_name { public boolean seek(String strSeekSign) throws DBException { // NOTE: This extra logic deals with a very specific and obscure case: // If this GRID table is NOT currently being used for indexed access (ie., get(x)) // You can do a seek and I will cache the record. On a subsequent seek, I will return the cached // record. This is typically used for thin client accessing cached virtual fields in a table session. boolean bAutonomousSeek = false; if (m_iEndOfFileIndex == UNKNOWN_POSITION) if ((m_iPhysicalFilePosition == UNKNOWN_POSITION) || (m_iPhysicalFilePosition == ADD_NEW_POSITION)) if ((m_iLogicalFilePosition == UNKNOWN_POSITION) || (m_iLogicalFilePosition == ADD_NEW_POSITION)) bAutonomousSeek = true; if (bAutonomousSeek) { Object bookmark = this.getRecord().getHandle(DBConstants.BOOKMARK_HANDLE); int iPosition = this.findElement(bookmark, DBConstants.BOOKMARK_HANDLE); if (iPosition == 0) { DataRecord dataRecord = (DataRecord)this.elementAt(iPosition); return this.getNextTable().setDataRecord(dataRecord); // Success always. } } // Don't set m_iPhysicalFilePosition = UNKNOWN_POSITION, because tables use seek to do queries. boolean bSuccess = super.seek(strSeekSign); if (bAutonomousSeek) { if (bSuccess) this.addRecordReference(0); } return bSuccess; } }
public class class_name { public boolean seek(String strSeekSign) throws DBException { // NOTE: This extra logic deals with a very specific and obscure case: // If this GRID table is NOT currently being used for indexed access (ie., get(x)) // You can do a seek and I will cache the record. On a subsequent seek, I will return the cached // record. This is typically used for thin client accessing cached virtual fields in a table session. boolean bAutonomousSeek = false; if (m_iEndOfFileIndex == UNKNOWN_POSITION) if ((m_iPhysicalFilePosition == UNKNOWN_POSITION) || (m_iPhysicalFilePosition == ADD_NEW_POSITION)) if ((m_iLogicalFilePosition == UNKNOWN_POSITION) || (m_iLogicalFilePosition == ADD_NEW_POSITION)) bAutonomousSeek = true; if (bAutonomousSeek) { Object bookmark = this.getRecord().getHandle(DBConstants.BOOKMARK_HANDLE); int iPosition = this.findElement(bookmark, DBConstants.BOOKMARK_HANDLE); if (iPosition == 0) { DataRecord dataRecord = (DataRecord)this.elementAt(iPosition); return this.getNextTable().setDataRecord(dataRecord); // Success always. // depends on control dependency: [if], data = [none] } } // Don't set m_iPhysicalFilePosition = UNKNOWN_POSITION, because tables use seek to do queries. boolean bSuccess = super.seek(strSeekSign); if (bAutonomousSeek) { if (bSuccess) this.addRecordReference(0); } return bSuccess; } }
public class class_name { public TenantDefinition getTenantDefinition(String tenantName) { // Allow access to default tenant if DBService is not yet initialized. if (tenantName.equals(m_defaultTenantName)) { return getDefaultTenantDef(); } checkServiceState(); return getTenantDef(tenantName); } }
public class class_name { public TenantDefinition getTenantDefinition(String tenantName) { // Allow access to default tenant if DBService is not yet initialized. if (tenantName.equals(m_defaultTenantName)) { return getDefaultTenantDef(); // depends on control dependency: [if], data = [none] } checkServiceState(); return getTenantDef(tenantName); } }
public class class_name { private void sendInitPacket(@NonNull final BluetoothGatt gatt, final boolean allowResume) throws RemoteDfuException, DeviceDisconnectedException, DfuException, UploadAbortedException, UnknownResponseException { final CRC32 crc32 = new CRC32(); // Used to calculate CRC32 of the Init packet ObjectChecksum checksum; // First, select the Command Object. As a response the maximum command size and information whether there is already // a command saved from a previous connection is returned. logi("Setting object to Command (Op Code = 6, Type = 1)"); final ObjectInfo info = selectObject(OBJECT_COMMAND); logi(String.format(Locale.US, "Command object info received (Max size = %d, Offset = %d, CRC = %08X)", info.maxSize, info.offset, info.CRC32)); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, String.format(Locale.US, "Command object info received (Max size = %d, Offset = %d, CRC = %08X)", info.maxSize, info.offset, info.CRC32)); //noinspection StatementWithEmptyBody if (mInitPacketSizeInBytes > info.maxSize) { // Ignore this here. Later, after sending the 'Create object' command, DFU target will send an error if init packet is too large } // Can we resume? If the offset obtained from the device is greater then zero we can compare it with the local init packet CRC // and resume sending the init packet, or even skip sending it if the whole file was sent before. boolean skipSendingInitPacket = false; boolean resumeSendingInitPacket = false; if (allowResume && info.offset > 0 && info.offset <= mInitPacketSizeInBytes) { try { // Read the same number of bytes from the current init packet to calculate local CRC32 final byte[] buffer = new byte[info.offset]; mInitPacketStream.read(buffer); // Calculate the CRC32 crc32.update(buffer); final int crc = (int) (crc32.getValue() & 0xFFFFFFFFL); if (info.CRC32 == crc) { logi("Init packet CRC is the same"); if (info.offset == mInitPacketSizeInBytes) { // The whole init packet was sent and it is equal to one we try to send now. // There is no need to send it again. We may try to resume sending data. logi("-> Whole Init packet was sent before"); skipSendingInitPacket = true; mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Received CRC match Init packet"); } else { logi("-> " + info.offset + " bytes of Init packet were sent before"); resumeSendingInitPacket = true; mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Resuming sending Init packet..."); } } else { // A different Init packet was sent before, or the error occurred while sending. // We have to send the whole Init packet again. mInitPacketStream.reset(); crc32.reset(); info.offset = 0; } } catch (final IOException e) { loge("Error while reading " + info.offset + " bytes from the init packet stream", e); try { // Go back to the beginning of the stream, we will send the whole init packet mInitPacketStream.reset(); crc32.reset(); info.offset = 0; } catch (final IOException e1) { loge("Error while resetting the init packet stream", e1); mService.terminateConnection(gatt, DfuBaseService.ERROR_FILE_IO_EXCEPTION); return; } } } if (!skipSendingInitPacket) { // The Init packet is sent different way in this implementation than the firmware, and receiving PRNs is not implemented. // This value might have been stored on the device, so we have to explicitly disable PRNs. setPacketReceiptNotifications(0); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Packet Receipt Notif disabled (Op Code = 2, Value = 0)"); for (int attempt = 1; attempt <= MAX_ATTEMPTS;) { if (!resumeSendingInitPacket) { // Create the Init object logi("Creating Init packet object (Op Code = 1, Type = 1, Size = " + mInitPacketSizeInBytes + ")"); writeCreateRequest(OBJECT_COMMAND, mInitPacketSizeInBytes); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Command object created"); } // Write Init data to the Packet Characteristic try { logi("Sending " + (mInitPacketSizeInBytes - info.offset) + " bytes of init packet..."); writeInitData(mPacketCharacteristic, crc32); } catch (final DeviceDisconnectedException e) { loge("Disconnected while sending init packet"); throw e; } final int crc = (int) (crc32.getValue() & 0xFFFFFFFFL); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, String.format(Locale.US, "Command object sent (CRC = %08X)", crc)); // Calculate Checksum logi("Sending Calculate Checksum command (Op Code = 3)"); checksum = readChecksum(); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, String.format(Locale.US, "Checksum received (Offset = %d, CRC = %08X)", checksum.offset, checksum.CRC32)); logi(String.format(Locale.US, "Checksum received (Offset = %d, CRC = %08X)", checksum.offset, checksum.CRC32)); if (crc == checksum.CRC32) { // Everything is OK, we can proceed break; } else { if (attempt < MAX_ATTEMPTS) { attempt++; logi("CRC does not match! Retrying...(" + attempt + "/" + MAX_ATTEMPTS + ")"); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING, "CRC does not match! Retrying...(" + attempt + "/" + MAX_ATTEMPTS + ")"); try { // Go back to the beginning, we will send the whole Init packet again resumeSendingInitPacket = false; info.offset = 0; info.CRC32 = 0; mInitPacketStream.reset(); crc32.reset(); } catch (final IOException e) { loge("Error while resetting the init packet stream", e); mService.terminateConnection(gatt, DfuBaseService.ERROR_FILE_IO_EXCEPTION); return; } } else { loge("CRC does not match!"); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_ERROR, "CRC does not match!"); mService.terminateConnection(gatt, DfuBaseService.ERROR_CRC_ERROR); return; } } } } // Execute Init packet. It's better to execute it twice than not execute at all... logi("Executing init packet (Op Code = 4)"); writeExecute(); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Command object executed"); } }
public class class_name { private void sendInitPacket(@NonNull final BluetoothGatt gatt, final boolean allowResume) throws RemoteDfuException, DeviceDisconnectedException, DfuException, UploadAbortedException, UnknownResponseException { final CRC32 crc32 = new CRC32(); // Used to calculate CRC32 of the Init packet ObjectChecksum checksum; // First, select the Command Object. As a response the maximum command size and information whether there is already // a command saved from a previous connection is returned. logi("Setting object to Command (Op Code = 6, Type = 1)"); final ObjectInfo info = selectObject(OBJECT_COMMAND); logi(String.format(Locale.US, "Command object info received (Max size = %d, Offset = %d, CRC = %08X)", info.maxSize, info.offset, info.CRC32)); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, String.format(Locale.US, "Command object info received (Max size = %d, Offset = %d, CRC = %08X)", info.maxSize, info.offset, info.CRC32)); //noinspection StatementWithEmptyBody if (mInitPacketSizeInBytes > info.maxSize) { // Ignore this here. Later, after sending the 'Create object' command, DFU target will send an error if init packet is too large } // Can we resume? If the offset obtained from the device is greater then zero we can compare it with the local init packet CRC // and resume sending the init packet, or even skip sending it if the whole file was sent before. boolean skipSendingInitPacket = false; boolean resumeSendingInitPacket = false; if (allowResume && info.offset > 0 && info.offset <= mInitPacketSizeInBytes) { try { // Read the same number of bytes from the current init packet to calculate local CRC32 final byte[] buffer = new byte[info.offset]; mInitPacketStream.read(buffer); // Calculate the CRC32 crc32.update(buffer); final int crc = (int) (crc32.getValue() & 0xFFFFFFFFL); if (info.CRC32 == crc) { logi("Init packet CRC is the same"); if (info.offset == mInitPacketSizeInBytes) { // The whole init packet was sent and it is equal to one we try to send now. // There is no need to send it again. We may try to resume sending data. logi("-> Whole Init packet was sent before"); // depends on control dependency: [if], data = [none] skipSendingInitPacket = true; // depends on control dependency: [if], data = [none] mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Received CRC match Init packet"); // depends on control dependency: [if], data = [none] } else { logi("-> " + info.offset + " bytes of Init packet were sent before"); // depends on control dependency: [if], data = [none] resumeSendingInitPacket = true; // depends on control dependency: [if], data = [none] mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Resuming sending Init packet..."); // depends on control dependency: [if], data = [none] } } else { // A different Init packet was sent before, or the error occurred while sending. // We have to send the whole Init packet again. mInitPacketStream.reset(); crc32.reset(); info.offset = 0; } } catch (final IOException e) { loge("Error while reading " + info.offset + " bytes from the init packet stream", e); try { // Go back to the beginning of the stream, we will send the whole init packet mInitPacketStream.reset(); crc32.reset(); info.offset = 0; } catch (final IOException e1) { loge("Error while resetting the init packet stream", e1); mService.terminateConnection(gatt, DfuBaseService.ERROR_FILE_IO_EXCEPTION); return; } } } if (!skipSendingInitPacket) { // The Init packet is sent different way in this implementation than the firmware, and receiving PRNs is not implemented. // This value might have been stored on the device, so we have to explicitly disable PRNs. setPacketReceiptNotifications(0); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Packet Receipt Notif disabled (Op Code = 2, Value = 0)"); for (int attempt = 1; attempt <= MAX_ATTEMPTS;) { if (!resumeSendingInitPacket) { // Create the Init object logi("Creating Init packet object (Op Code = 1, Type = 1, Size = " + mInitPacketSizeInBytes + ")"); writeCreateRequest(OBJECT_COMMAND, mInitPacketSizeInBytes); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Command object created"); } // Write Init data to the Packet Characteristic try { logi("Sending " + (mInitPacketSizeInBytes - info.offset) + " bytes of init packet..."); writeInitData(mPacketCharacteristic, crc32); } catch (final DeviceDisconnectedException e) { loge("Disconnected while sending init packet"); throw e; } final int crc = (int) (crc32.getValue() & 0xFFFFFFFFL); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, String.format(Locale.US, "Command object sent (CRC = %08X)", crc)); // Calculate Checksum logi("Sending Calculate Checksum command (Op Code = 3)"); checksum = readChecksum(); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, String.format(Locale.US, "Checksum received (Offset = %d, CRC = %08X)", checksum.offset, checksum.CRC32)); logi(String.format(Locale.US, "Checksum received (Offset = %d, CRC = %08X)", checksum.offset, checksum.CRC32)); if (crc == checksum.CRC32) { // Everything is OK, we can proceed break; } else { if (attempt < MAX_ATTEMPTS) { attempt++; logi("CRC does not match! Retrying...(" + attempt + "/" + MAX_ATTEMPTS + ")"); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING, "CRC does not match! Retrying...(" + attempt + "/" + MAX_ATTEMPTS + ")"); try { // Go back to the beginning, we will send the whole Init packet again resumeSendingInitPacket = false; info.offset = 0; info.CRC32 = 0; mInitPacketStream.reset(); crc32.reset(); } catch (final IOException e) { loge("Error while resetting the init packet stream", e); mService.terminateConnection(gatt, DfuBaseService.ERROR_FILE_IO_EXCEPTION); return; } } else { loge("CRC does not match!"); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_ERROR, "CRC does not match!"); mService.terminateConnection(gatt, DfuBaseService.ERROR_CRC_ERROR); return; } } } } // Execute Init packet. It's better to execute it twice than not execute at all... logi("Executing init packet (Op Code = 4)"); writeExecute(); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Command object executed"); } }
public class class_name { @VisibleForTesting public static long calculateNewNetworkBufferMemory(Configuration config, long maxJvmHeapMemory) { // The maximum heap memory has been adjusted as in TaskManagerServices#calculateHeapSizeMB // and we need to invert these calculations. final long jvmHeapNoNet; final MemoryType memoryType = ConfigurationParserUtils.getMemoryType(config); if (memoryType == MemoryType.HEAP) { jvmHeapNoNet = maxJvmHeapMemory; } else if (memoryType == MemoryType.OFF_HEAP) { long configuredMemory = ConfigurationParserUtils.getManagedMemorySize(config) << 20; // megabytes to bytes if (configuredMemory > 0) { // The maximum heap memory has been adjusted according to configuredMemory, i.e. // maxJvmHeap = jvmHeapNoNet - configuredMemory jvmHeapNoNet = maxJvmHeapMemory + configuredMemory; } else { // The maximum heap memory has been adjusted according to the fraction, i.e. // maxJvmHeap = jvmHeapNoNet - jvmHeapNoNet * managedFraction = jvmHeapNoNet * (1 - managedFraction) jvmHeapNoNet = (long) (maxJvmHeapMemory / (1.0 - ConfigurationParserUtils.getManagedMemoryFraction(config))); } } else { throw new RuntimeException("No supported memory type detected."); } // finally extract the network buffer memory size again from: // jvmHeapNoNet = jvmHeap - networkBufBytes // = jvmHeap - Math.min(networkBufMax, Math.max(networkBufMin, jvmHeap * netFraction) // jvmHeap = jvmHeapNoNet / (1.0 - networkBufFraction) float networkBufFraction = config.getFloat(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION); long networkBufSize = (long) (jvmHeapNoNet / (1.0 - networkBufFraction) * networkBufFraction); return calculateNewNetworkBufferMemory(config, networkBufSize, maxJvmHeapMemory); } }
public class class_name { @VisibleForTesting public static long calculateNewNetworkBufferMemory(Configuration config, long maxJvmHeapMemory) { // The maximum heap memory has been adjusted as in TaskManagerServices#calculateHeapSizeMB // and we need to invert these calculations. final long jvmHeapNoNet; final MemoryType memoryType = ConfigurationParserUtils.getMemoryType(config); if (memoryType == MemoryType.HEAP) { jvmHeapNoNet = maxJvmHeapMemory; // depends on control dependency: [if], data = [none] } else if (memoryType == MemoryType.OFF_HEAP) { long configuredMemory = ConfigurationParserUtils.getManagedMemorySize(config) << 20; // megabytes to bytes if (configuredMemory > 0) { // The maximum heap memory has been adjusted according to configuredMemory, i.e. // maxJvmHeap = jvmHeapNoNet - configuredMemory jvmHeapNoNet = maxJvmHeapMemory + configuredMemory; // depends on control dependency: [if], data = [none] } else { // The maximum heap memory has been adjusted according to the fraction, i.e. // maxJvmHeap = jvmHeapNoNet - jvmHeapNoNet * managedFraction = jvmHeapNoNet * (1 - managedFraction) jvmHeapNoNet = (long) (maxJvmHeapMemory / (1.0 - ConfigurationParserUtils.getManagedMemoryFraction(config))); // depends on control dependency: [if], data = [none] } } else { throw new RuntimeException("No supported memory type detected."); } // finally extract the network buffer memory size again from: // jvmHeapNoNet = jvmHeap - networkBufBytes // = jvmHeap - Math.min(networkBufMax, Math.max(networkBufMin, jvmHeap * netFraction) // jvmHeap = jvmHeapNoNet / (1.0 - networkBufFraction) float networkBufFraction = config.getFloat(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION); long networkBufSize = (long) (jvmHeapNoNet / (1.0 - networkBufFraction) * networkBufFraction); return calculateNewNetworkBufferMemory(config, networkBufSize, maxJvmHeapMemory); } }
public class class_name { protected TypedParams<SortingParams> parseSortingParameters(final QueryParamsParserContext context) { String sortingKey = RestrictedQueryParamsMembers.sort.name(); Map<String, Set<String>> sorting = filterQueryParamsByKey(context, sortingKey); Map<String, Map<String, RestrictedSortingValues>> temporarySortingMap = new LinkedHashMap<>(); for (Map.Entry<String, Set<String>> entry : sorting.entrySet()) { List<String> propertyList = buildPropertyListFromEntry(entry, sortingKey); String resourceType = propertyList.get(0); String propertyPath = StringUtils.join(".", propertyList.subList(1, propertyList.size())); if (temporarySortingMap.containsKey(resourceType)) { Map<String, RestrictedSortingValues> resourceParams = temporarySortingMap.get(resourceType); resourceParams.put(propertyPath, RestrictedSortingValues.valueOf(entry.getValue() .iterator() .next())); } else { Map<String, RestrictedSortingValues> resourceParams = new HashMap<>(); temporarySortingMap.put(resourceType, resourceParams); resourceParams.put(propertyPath, RestrictedSortingValues.valueOf(entry.getValue() .iterator() .next())); } } Map<String, SortingParams> decodedSortingMap = new LinkedHashMap<>(); for (Map.Entry<String, Map<String, RestrictedSortingValues>> resourceTypesMap : temporarySortingMap.entrySet()) { Map<String, RestrictedSortingValues> sortingMap = Collections.unmodifiableMap(resourceTypesMap.getValue()); decodedSortingMap.put(resourceTypesMap.getKey(), new SortingParams(sortingMap)); } return new TypedParams<>(Collections.unmodifiableMap(decodedSortingMap)); } }
public class class_name { protected TypedParams<SortingParams> parseSortingParameters(final QueryParamsParserContext context) { String sortingKey = RestrictedQueryParamsMembers.sort.name(); Map<String, Set<String>> sorting = filterQueryParamsByKey(context, sortingKey); Map<String, Map<String, RestrictedSortingValues>> temporarySortingMap = new LinkedHashMap<>(); for (Map.Entry<String, Set<String>> entry : sorting.entrySet()) { List<String> propertyList = buildPropertyListFromEntry(entry, sortingKey); String resourceType = propertyList.get(0); String propertyPath = StringUtils.join(".", propertyList.subList(1, propertyList.size())); if (temporarySortingMap.containsKey(resourceType)) { Map<String, RestrictedSortingValues> resourceParams = temporarySortingMap.get(resourceType); resourceParams.put(propertyPath, RestrictedSortingValues.valueOf(entry.getValue() .iterator() .next())); // depends on control dependency: [if], data = [none] } else { Map<String, RestrictedSortingValues> resourceParams = new HashMap<>(); temporarySortingMap.put(resourceType, resourceParams); // depends on control dependency: [if], data = [none] resourceParams.put(propertyPath, RestrictedSortingValues.valueOf(entry.getValue() .iterator() .next())); // depends on control dependency: [if], data = [none] } } Map<String, SortingParams> decodedSortingMap = new LinkedHashMap<>(); for (Map.Entry<String, Map<String, RestrictedSortingValues>> resourceTypesMap : temporarySortingMap.entrySet()) { Map<String, RestrictedSortingValues> sortingMap = Collections.unmodifiableMap(resourceTypesMap.getValue()); decodedSortingMap.put(resourceTypesMap.getKey(), new SortingParams(sortingMap)); // depends on control dependency: [for], data = [resourceTypesMap] } return new TypedParams<>(Collections.unmodifiableMap(decodedSortingMap)); } }
public class class_name { @Override public BoundingBox deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) { final BoundingBox bbox; if (json.isJsonArray()) { final JsonArray bboxJsonArray = json.getAsJsonArray(); bbox = new BoundingBox(); bbox.setSouth(bboxJsonArray.get(0).getAsDouble()); bbox.setNorth(bboxJsonArray.get(1).getAsDouble()); bbox.setWest(bboxJsonArray.get(2).getAsDouble()); bbox.setEast(bboxJsonArray.get(3).getAsDouble()); } else { throw new JsonParseException("Unexpected data: " + json.toString()); } return bbox; } }
public class class_name { @Override public BoundingBox deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) { final BoundingBox bbox; if (json.isJsonArray()) { final JsonArray bboxJsonArray = json.getAsJsonArray(); bbox = new BoundingBox(); // depends on control dependency: [if], data = [none] bbox.setSouth(bboxJsonArray.get(0).getAsDouble()); // depends on control dependency: [if], data = [none] bbox.setNorth(bboxJsonArray.get(1).getAsDouble()); // depends on control dependency: [if], data = [none] bbox.setWest(bboxJsonArray.get(2).getAsDouble()); // depends on control dependency: [if], data = [none] bbox.setEast(bboxJsonArray.get(3).getAsDouble()); // depends on control dependency: [if], data = [none] } else { throw new JsonParseException("Unexpected data: " + json.toString()); } return bbox; } }
public class class_name { public String[] getFamilyNames() { HashSet<String> familyNameSet = new HashSet<String>(); if (familyNames == null) { for (String columnName : columns(null, this.valueFields)) { int pos = columnName.indexOf(":"); familyNameSet.add(hbaseColumn(pos > 0 ? columnName.substring(0, pos) : columnName)); } } else { for (String familyName : familyNames) { familyNameSet.add(familyName); } } return familyNameSet.toArray(new String[0]); } }
public class class_name { public String[] getFamilyNames() { HashSet<String> familyNameSet = new HashSet<String>(); if (familyNames == null) { for (String columnName : columns(null, this.valueFields)) { int pos = columnName.indexOf(":"); familyNameSet.add(hbaseColumn(pos > 0 ? columnName.substring(0, pos) : columnName)); // depends on control dependency: [for], data = [columnName] } } else { for (String familyName : familyNames) { familyNameSet.add(familyName); // depends on control dependency: [for], data = [familyName] } } return familyNameSet.toArray(new String[0]); } }
public class class_name { private TernaryVector getTermIndexVector(String term) { TernaryVector iv = termToIndexVector.get(term); if (iv == null) { // lock in case multiple threads attempt to add it at once synchronized(this) { // recheck in case another thread added it while we were waiting // for the lock iv = termToIndexVector.get(term); if (iv == null) { // since this is a new term, also map it to its index for // later look-up when the integer documents are processed termToIndex.put(term, termIndexCounter++); // next, map it to its reflective vector which will be // filled in process space termToReflectiveSemantics.put(term, createVector()); // last, create an index vector for the term iv = indexVectorGenerator.generate(); termToIndexVector.put(term, iv); } } } return iv; } }
public class class_name { private TernaryVector getTermIndexVector(String term) { TernaryVector iv = termToIndexVector.get(term); if (iv == null) { // lock in case multiple threads attempt to add it at once synchronized(this) { // depends on control dependency: [if], data = [none] // recheck in case another thread added it while we were waiting // for the lock iv = termToIndexVector.get(term); if (iv == null) { // since this is a new term, also map it to its index for // later look-up when the integer documents are processed termToIndex.put(term, termIndexCounter++); // depends on control dependency: [if], data = [none] // next, map it to its reflective vector which will be // filled in process space termToReflectiveSemantics.put(term, createVector()); // depends on control dependency: [if], data = [none] // last, create an index vector for the term iv = indexVectorGenerator.generate(); // depends on control dependency: [if], data = [none] termToIndexVector.put(term, iv); // depends on control dependency: [if], data = [none] } } } return iv; } }
public class class_name { protected void init(Class<T> cls, Key ... keys) { readDataSource = Execution.getDataSourceName(cls.getName(), true); writeDataSource = Execution.getDataSourceName(cls.getName(), false); if( readDataSource == null ) { readDataSource = writeDataSource; } if( writeDataSource == null ) { writeDataSource = readDataSource; } Properties props = new Properties(); try { InputStream is = DaseinSequencer.class.getResourceAsStream(DaseinSequencer.PROPERTIES); if( is != null ) { props.load(is); } } catch( Exception e ) { logger.error("Problem reading " + DaseinSequencer.PROPERTIES + ": " + e.getMessage(), e); } database = props.getProperty("dasein.persist.handlersocket.database"); handlerSocketHost = props.getProperty("dasein.persist.handlersocket.host"); port = Integer.valueOf(props.getProperty("dasein.persist.handlersocket.port")); poolSize = Integer.valueOf(props.getProperty("dasein.persist.handlersocket.poolSize")); // get the columns List<String> targetColumns = new ArrayList<String>(); Class<?> clazz = cls; while( clazz != null && !clazz.equals(Object.class) ) { Field[] fields = clazz.getDeclaredFields(); for( Field f : fields ) { int m = f.getModifiers(); if( Modifier.isTransient(m) || Modifier.isStatic(m) ) { continue; } if (f.getType().getName().equals(Collection.class.getName())) { continue; // this is handled by dependency manager } if( !f.getType().getName().equals(Translator.class.getName()) ) { targetColumns.add(f.getName()); types.put(f.getName(), f.getType()); } } clazz = clazz.getSuperclass(); } columns = new String[targetColumns.size()]; databaseColumns = new String[targetColumns.size()]; for (int i = 0; i < targetColumns.size(); i++) { columns[i] = targetColumns.get(i); databaseColumns[i] = getSqlName(targetColumns.get(i)); } } }
public class class_name { protected void init(Class<T> cls, Key ... keys) { readDataSource = Execution.getDataSourceName(cls.getName(), true); writeDataSource = Execution.getDataSourceName(cls.getName(), false); if( readDataSource == null ) { readDataSource = writeDataSource; // depends on control dependency: [if], data = [none] } if( writeDataSource == null ) { writeDataSource = readDataSource; // depends on control dependency: [if], data = [none] } Properties props = new Properties(); try { InputStream is = DaseinSequencer.class.getResourceAsStream(DaseinSequencer.PROPERTIES); if( is != null ) { props.load(is); // depends on control dependency: [if], data = [none] } } catch( Exception e ) { logger.error("Problem reading " + DaseinSequencer.PROPERTIES + ": " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] database = props.getProperty("dasein.persist.handlersocket.database"); handlerSocketHost = props.getProperty("dasein.persist.handlersocket.host"); port = Integer.valueOf(props.getProperty("dasein.persist.handlersocket.port")); poolSize = Integer.valueOf(props.getProperty("dasein.persist.handlersocket.poolSize")); // get the columns List<String> targetColumns = new ArrayList<String>(); Class<?> clazz = cls; while( clazz != null && !clazz.equals(Object.class) ) { Field[] fields = clazz.getDeclaredFields(); for( Field f : fields ) { int m = f.getModifiers(); if( Modifier.isTransient(m) || Modifier.isStatic(m) ) { continue; } if (f.getType().getName().equals(Collection.class.getName())) { continue; // this is handled by dependency manager } if( !f.getType().getName().equals(Translator.class.getName()) ) { targetColumns.add(f.getName()); types.put(f.getName(), f.getType()); } } clazz = clazz.getSuperclass(); } columns = new String[targetColumns.size()]; databaseColumns = new String[targetColumns.size()]; for (int i = 0; i < targetColumns.size(); i++) { columns[i] = targetColumns.get(i); databaseColumns[i] = getSqlName(targetColumns.get(i)); } } }
public class class_name { public static void showOnlyChannels(Object... channels){ for(LogRecordHandler handler : handlers){ if(handler instanceof VisibilityHandler){ VisibilityHandler visHandler = (VisibilityHandler) handler; visHandler.hideAll(); for (Object channel : channels) { visHandler.alsoShow(channel); } } } } }
public class class_name { public static void showOnlyChannels(Object... channels){ for(LogRecordHandler handler : handlers){ if(handler instanceof VisibilityHandler){ VisibilityHandler visHandler = (VisibilityHandler) handler; visHandler.hideAll(); // depends on control dependency: [if], data = [none] for (Object channel : channels) { visHandler.alsoShow(channel); // depends on control dependency: [for], data = [channel] } } } } }
public class class_name { public List<HistoryEvent> createUserOperationLogEvents(UserOperationLogContext context) { List<HistoryEvent> historyEvents = new ArrayList<HistoryEvent>(); String operationId = Context.getCommandContext().getOperationId(); context.setOperationId(operationId); for (UserOperationLogContextEntry entry : context.getEntries()) { for (PropertyChange propertyChange : entry.getPropertyChanges()) { UserOperationLogEntryEventEntity evt = new UserOperationLogEntryEventEntity(); initUserOperationLogEvent(evt, context, entry, propertyChange); historyEvents.add(evt); } } return historyEvents; } }
public class class_name { public List<HistoryEvent> createUserOperationLogEvents(UserOperationLogContext context) { List<HistoryEvent> historyEvents = new ArrayList<HistoryEvent>(); String operationId = Context.getCommandContext().getOperationId(); context.setOperationId(operationId); for (UserOperationLogContextEntry entry : context.getEntries()) { for (PropertyChange propertyChange : entry.getPropertyChanges()) { UserOperationLogEntryEventEntity evt = new UserOperationLogEntryEventEntity(); initUserOperationLogEvent(evt, context, entry, propertyChange); // depends on control dependency: [for], data = [propertyChange] historyEvents.add(evt); // depends on control dependency: [for], data = [none] } } return historyEvents; } }
public class class_name { @Override public double[] getVotesForInstance(Instance instance) { if (this.reset == true) { return new double[2]; } double[] probOfClassGivenDoc = new double[m_numClasses]; double totalSize = totalSize(instance); for (int i = 0; i < m_numClasses; i++) { probOfClassGivenDoc[i] = Math.log(m_probOfClass[i]) - totalSize * Math.log(m_classTotals[i]); } for (int i = 0; i < instance.numValues(); i++) { int index = instance.index(i); if (index == instance.classIndex() || instance.isMissing(i)) { continue; } double wordCount = instance.valueSparse(i); for (int c = 0; c < m_numClasses; c++) { double value = m_wordTotalForClass[c].getValue(index); probOfClassGivenDoc[c] += wordCount * Math.log(value == 0 ? this.laplaceCorrectionOption.getValue() : value ); } } return Utils.logs2probs(probOfClassGivenDoc); } }
public class class_name { @Override public double[] getVotesForInstance(Instance instance) { if (this.reset == true) { return new double[2]; // depends on control dependency: [if], data = [none] } double[] probOfClassGivenDoc = new double[m_numClasses]; double totalSize = totalSize(instance); for (int i = 0; i < m_numClasses; i++) { probOfClassGivenDoc[i] = Math.log(m_probOfClass[i]) - totalSize * Math.log(m_classTotals[i]); // depends on control dependency: [for], data = [i] } for (int i = 0; i < instance.numValues(); i++) { int index = instance.index(i); if (index == instance.classIndex() || instance.isMissing(i)) { continue; } double wordCount = instance.valueSparse(i); for (int c = 0; c < m_numClasses; c++) { double value = m_wordTotalForClass[c].getValue(index); probOfClassGivenDoc[c] += wordCount * Math.log(value == 0 ? this.laplaceCorrectionOption.getValue() : value ); // depends on control dependency: [for], data = [c] } } return Utils.logs2probs(probOfClassGivenDoc); } }
public class class_name { public static void addTagMetaData(ConfigWebImpl cw, lucee.commons.io.log.Log log) { if (true) return; PageContextImpl pc = null; try { pc = ThreadUtil.createPageContext(cw, DevNullOutputStream.DEV_NULL_OUTPUT_STREAM, "localhost", "/", "", new Cookie[0], new Pair[0], null, new Pair[0], new StructImpl(), false, -1); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); return; } PageContext orgPC = ThreadLocalPageContext.get(); try { ThreadLocalPageContext.register(pc); // MUST MOST of them are the same, so this is a huge overhead _addTagMetaData(pc, cw, CFMLEngine.DIALECT_CFML); _addTagMetaData(pc, cw, CFMLEngine.DIALECT_LUCEE); } catch (Exception e) { XMLConfigWebFactory.log(cw, log, e); } finally { pc.getConfig().getFactory().releaseLuceePageContext(pc, true); ThreadLocalPageContext.register(orgPC); } } }
public class class_name { public static void addTagMetaData(ConfigWebImpl cw, lucee.commons.io.log.Log log) { if (true) return; PageContextImpl pc = null; try { pc = ThreadUtil.createPageContext(cw, DevNullOutputStream.DEV_NULL_OUTPUT_STREAM, "localhost", "/", "", new Cookie[0], new Pair[0], null, new Pair[0], new StructImpl(), false, -1); // depends on control dependency: [try], data = [none] } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); return; } // depends on control dependency: [catch], data = [none] PageContext orgPC = ThreadLocalPageContext.get(); try { ThreadLocalPageContext.register(pc); // depends on control dependency: [try], data = [none] // MUST MOST of them are the same, so this is a huge overhead _addTagMetaData(pc, cw, CFMLEngine.DIALECT_CFML); // depends on control dependency: [try], data = [none] _addTagMetaData(pc, cw, CFMLEngine.DIALECT_LUCEE); // depends on control dependency: [try], data = [none] } catch (Exception e) { XMLConfigWebFactory.log(cw, log, e); } // depends on control dependency: [catch], data = [none] finally { pc.getConfig().getFactory().releaseLuceePageContext(pc, true); ThreadLocalPageContext.register(orgPC); } } }
public class class_name { @Override public AbstractDLock createLock(String name) { String lockName = buildLockName(name); try { AbstractDLock lock = lockInstances.get(lockName, new Callable<AbstractDLock>() { @Override public AbstractDLock call() throws Exception { // yup, use "name" here (not "lockName) is correct and // intended! Properties lockProps = getLockProperties(name); return createAndInitLockInstance(lockName, lockProps); } }); return lock; } catch (ExecutionException e) { throw new RuntimeException(e); } } }
public class class_name { @Override public AbstractDLock createLock(String name) { String lockName = buildLockName(name); try { AbstractDLock lock = lockInstances.get(lockName, new Callable<AbstractDLock>() { @Override public AbstractDLock call() throws Exception { // yup, use "name" here (not "lockName) is correct and // intended! Properties lockProps = getLockProperties(name); return createAndInitLockInstance(lockName, lockProps); } }); return lock; // depends on control dependency: [try], data = [none] } catch (ExecutionException e) { throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public Object invokeFunction(EvaluationContext ctx, String name, List<Object> args) { // find function with given name Method func = getFunction(name); if (func == null) { throw new EvaluationError("Undefined function: " + name); } List<Object> parameters = new ArrayList<>(); List<Object> remainingArgs = new ArrayList<>(args); for (Parameter param : Parameter.fromMethod(func)) { BooleanDefault defaultBool = param.getAnnotation(BooleanDefault.class); IntegerDefault defaultInt = param.getAnnotation(IntegerDefault.class); StringDefault defaultStr = param.getAnnotation(StringDefault.class); if (param.getType().equals(EvaluationContext.class)) { parameters.add(ctx); } else if (param.getType().isArray()) { // we've reach a varargs param parameters.add(remainingArgs.toArray(new Object[remainingArgs.size()])); remainingArgs.clear(); break; } else if (remainingArgs.size() > 0) { Object arg = remainingArgs.remove(0); parameters.add(arg); } else if (defaultBool != null) { parameters.add(defaultBool.value()); } else if (defaultInt != null) { parameters.add(defaultInt.value()); } else if (defaultStr != null) { parameters.add(defaultStr.value()); } else { throw new EvaluationError("Too few arguments provided for function " + name); } } if (!remainingArgs.isEmpty()) { throw new EvaluationError("Too many arguments provided for function " + name); } try { return func.invoke(null, parameters.toArray(new Object[parameters.size()])); } catch (Exception e) { List<String> prettyArgs = new ArrayList<>(); for (Object arg : args) { String pretty; if (arg instanceof String) { pretty = "\"" + arg + "\""; } else { try { pretty = Conversions.toString(arg, ctx); } catch (EvaluationError ex) { pretty = arg.toString(); } } prettyArgs.add(pretty); } throw new EvaluationError("Error calling function " + name + " with arguments " + StringUtils.join(prettyArgs, ", "), e); } } }
public class class_name { public Object invokeFunction(EvaluationContext ctx, String name, List<Object> args) { // find function with given name Method func = getFunction(name); if (func == null) { throw new EvaluationError("Undefined function: " + name); } List<Object> parameters = new ArrayList<>(); List<Object> remainingArgs = new ArrayList<>(args); for (Parameter param : Parameter.fromMethod(func)) { BooleanDefault defaultBool = param.getAnnotation(BooleanDefault.class); IntegerDefault defaultInt = param.getAnnotation(IntegerDefault.class); StringDefault defaultStr = param.getAnnotation(StringDefault.class); if (param.getType().equals(EvaluationContext.class)) { parameters.add(ctx); // depends on control dependency: [if], data = [none] } else if (param.getType().isArray()) { // we've reach a varargs param parameters.add(remainingArgs.toArray(new Object[remainingArgs.size()])); // depends on control dependency: [if], data = [none] remainingArgs.clear(); // depends on control dependency: [if], data = [none] break; } else if (remainingArgs.size() > 0) { Object arg = remainingArgs.remove(0); parameters.add(arg); // depends on control dependency: [if], data = [none] } else if (defaultBool != null) { parameters.add(defaultBool.value()); // depends on control dependency: [if], data = [(defaultBool] } else if (defaultInt != null) { parameters.add(defaultInt.value()); // depends on control dependency: [if], data = [(defaultInt] } else if (defaultStr != null) { parameters.add(defaultStr.value()); // depends on control dependency: [if], data = [(defaultStr] } else { throw new EvaluationError("Too few arguments provided for function " + name); } } if (!remainingArgs.isEmpty()) { throw new EvaluationError("Too many arguments provided for function " + name); } try { return func.invoke(null, parameters.toArray(new Object[parameters.size()])); // depends on control dependency: [try], data = [none] } catch (Exception e) { List<String> prettyArgs = new ArrayList<>(); for (Object arg : args) { String pretty; if (arg instanceof String) { pretty = "\"" + arg + "\""; // depends on control dependency: [if], data = [none] } else { try { pretty = Conversions.toString(arg, ctx); // depends on control dependency: [try], data = [none] } catch (EvaluationError ex) { pretty = arg.toString(); } // depends on control dependency: [catch], data = [none] } prettyArgs.add(pretty); // depends on control dependency: [for], data = [none] } throw new EvaluationError("Error calling function " + name + " with arguments " + StringUtils.join(prettyArgs, ", "), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static ChannelBindException fail(AbstractBootstrap<?, ?> bootstrap, @Nullable Throwable cause) { Objects.requireNonNull(bootstrap, "bootstrap"); if (cause instanceof java.net.BindException || // With epoll/kqueue transport it is // io.netty.channel.unix.Errors$NativeIoException: bind(..) failed: Address already in use (cause instanceof IOException && cause.getMessage() != null && cause.getMessage().contains("Address already in use"))) { cause = null; } if (!(bootstrap.config().localAddress() instanceof InetSocketAddress)) { return new ChannelBindException(bootstrap.config().localAddress().toString(), -1, cause); } InetSocketAddress address = (InetSocketAddress)bootstrap.config().localAddress(); return new ChannelBindException(address.getHostString(), address.getPort(), cause); } }
public class class_name { public static ChannelBindException fail(AbstractBootstrap<?, ?> bootstrap, @Nullable Throwable cause) { Objects.requireNonNull(bootstrap, "bootstrap"); if (cause instanceof java.net.BindException || // With epoll/kqueue transport it is // io.netty.channel.unix.Errors$NativeIoException: bind(..) failed: Address already in use (cause instanceof IOException && cause.getMessage() != null && cause.getMessage().contains("Address already in use"))) { cause = null; // depends on control dependency: [if], data = [none] } if (!(bootstrap.config().localAddress() instanceof InetSocketAddress)) { return new ChannelBindException(bootstrap.config().localAddress().toString(), -1, cause); // depends on control dependency: [if], data = [none] } InetSocketAddress address = (InetSocketAddress)bootstrap.config().localAddress(); return new ChannelBindException(address.getHostString(), address.getPort(), cause); } }
public class class_name { public void marshall(GCMChannelResponse gCMChannelResponse, ProtocolMarshaller protocolMarshaller) { if (gCMChannelResponse == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(gCMChannelResponse.getApplicationId(), APPLICATIONID_BINDING); protocolMarshaller.marshall(gCMChannelResponse.getCreationDate(), CREATIONDATE_BINDING); protocolMarshaller.marshall(gCMChannelResponse.getCredential(), CREDENTIAL_BINDING); protocolMarshaller.marshall(gCMChannelResponse.getEnabled(), ENABLED_BINDING); protocolMarshaller.marshall(gCMChannelResponse.getHasCredential(), HASCREDENTIAL_BINDING); protocolMarshaller.marshall(gCMChannelResponse.getId(), ID_BINDING); protocolMarshaller.marshall(gCMChannelResponse.getIsArchived(), ISARCHIVED_BINDING); protocolMarshaller.marshall(gCMChannelResponse.getLastModifiedBy(), LASTMODIFIEDBY_BINDING); protocolMarshaller.marshall(gCMChannelResponse.getLastModifiedDate(), LASTMODIFIEDDATE_BINDING); protocolMarshaller.marshall(gCMChannelResponse.getPlatform(), PLATFORM_BINDING); protocolMarshaller.marshall(gCMChannelResponse.getVersion(), VERSION_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(GCMChannelResponse gCMChannelResponse, ProtocolMarshaller protocolMarshaller) { if (gCMChannelResponse == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(gCMChannelResponse.getApplicationId(), APPLICATIONID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(gCMChannelResponse.getCreationDate(), CREATIONDATE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(gCMChannelResponse.getCredential(), CREDENTIAL_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(gCMChannelResponse.getEnabled(), ENABLED_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(gCMChannelResponse.getHasCredential(), HASCREDENTIAL_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(gCMChannelResponse.getId(), ID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(gCMChannelResponse.getIsArchived(), ISARCHIVED_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(gCMChannelResponse.getLastModifiedBy(), LASTMODIFIEDBY_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(gCMChannelResponse.getLastModifiedDate(), LASTMODIFIEDDATE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(gCMChannelResponse.getPlatform(), PLATFORM_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(gCMChannelResponse.getVersion(), VERSION_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public boolean isChildNodePrimaryTypeAllowed(final InternalQName childName, final InternalQName childNodeType, final InternalQName parentNodeType, final InternalQName[] parentMixinNames) throws RepositoryException { final Set<InternalQName> testSuperTypesNames = this.nodeTypeRepository.getSupertypes(childNodeType); NodeDefinitionData[] allChildNodeDefinitions = getAllChildNodeDefinitions(parentNodeType); for (final NodeDefinitionData cnd : allChildNodeDefinitions) { for (final InternalQName reqNodeType : cnd.getRequiredPrimaryTypes()) { InternalQName reqName = cnd.getName(); if (isChildAllowed(childName, childNodeType, cnd, reqName, reqNodeType)) { return true; } for (final InternalQName superName : testSuperTypesNames) { if (isChildAllowed(childName, superName, cnd, reqName, reqNodeType)) { return true; } } } } allChildNodeDefinitions = getAllChildNodeDefinitions(parentMixinNames); for (final NodeDefinitionData cnd : allChildNodeDefinitions) { for (final InternalQName reqNodeType : cnd.getRequiredPrimaryTypes()) { InternalQName reqName = cnd.getName(); if (isChildAllowed(childName, childNodeType, cnd, reqName, reqNodeType)) { return true; } for (final InternalQName superName : testSuperTypesNames) { if (isChildAllowed(childName, superName, cnd, reqName, reqNodeType)) { return true; } } } } return false; } }
public class class_name { public boolean isChildNodePrimaryTypeAllowed(final InternalQName childName, final InternalQName childNodeType, final InternalQName parentNodeType, final InternalQName[] parentMixinNames) throws RepositoryException { final Set<InternalQName> testSuperTypesNames = this.nodeTypeRepository.getSupertypes(childNodeType); NodeDefinitionData[] allChildNodeDefinitions = getAllChildNodeDefinitions(parentNodeType); for (final NodeDefinitionData cnd : allChildNodeDefinitions) { for (final InternalQName reqNodeType : cnd.getRequiredPrimaryTypes()) { InternalQName reqName = cnd.getName(); if (isChildAllowed(childName, childNodeType, cnd, reqName, reqNodeType)) { return true; // depends on control dependency: [if], data = [none] } for (final InternalQName superName : testSuperTypesNames) { if (isChildAllowed(childName, superName, cnd, reqName, reqNodeType)) { return true; // depends on control dependency: [if], data = [none] } } } } allChildNodeDefinitions = getAllChildNodeDefinitions(parentMixinNames); for (final NodeDefinitionData cnd : allChildNodeDefinitions) { for (final InternalQName reqNodeType : cnd.getRequiredPrimaryTypes()) { InternalQName reqName = cnd.getName(); if (isChildAllowed(childName, childNodeType, cnd, reqName, reqNodeType)) { return true; // depends on control dependency: [if], data = [none] } for (final InternalQName superName : testSuperTypesNames) { if (isChildAllowed(childName, superName, cnd, reqName, reqNodeType)) { return true; // depends on control dependency: [if], data = [none] } } } } return false; } }
public class class_name { @Override public boolean subscribe(IProvider provider, Map<String, Object> paramMap) { boolean success = super.subscribe(provider, paramMap); if (log.isDebugEnabled()) { log.debug("Provider subscribe{} {} params: {}", new Object[] { (success ? "d" : " failed"), provider, paramMap }); } if (success) { fireProviderConnectionEvent(provider, PipeConnectionEvent.EventType.PROVIDER_CONNECT_PUSH, paramMap); } return success; } }
public class class_name { @Override public boolean subscribe(IProvider provider, Map<String, Object> paramMap) { boolean success = super.subscribe(provider, paramMap); if (log.isDebugEnabled()) { log.debug("Provider subscribe{} {} params: {}", new Object[] { (success ? "d" : " failed"), provider, paramMap }); // depends on control dependency: [if], data = [none] } if (success) { fireProviderConnectionEvent(provider, PipeConnectionEvent.EventType.PROVIDER_CONNECT_PUSH, paramMap); // depends on control dependency: [if], data = [none] } return success; } }
public class class_name { protected K standardLastKey() { Entry<K, V> entry = lastEntry(); if (entry == null) { throw new NoSuchElementException(); } else { return entry.getKey(); } } }
public class class_name { protected K standardLastKey() { Entry<K, V> entry = lastEntry(); if (entry == null) { throw new NoSuchElementException(); } else { return entry.getKey(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public char skipTo(char to) { int index = in.indexOf(to, pos); if (index != -1) { pos = index; return to; } else { return '\0'; } } }
public class class_name { public char skipTo(char to) { int index = in.indexOf(to, pos); if (index != -1) { pos = index; // depends on control dependency: [if], data = [none] return to; // depends on control dependency: [if], data = [none] } else { return '\0'; // depends on control dependency: [if], data = [none] } } }
public class class_name { private static File extractLibraryFile(String libFolderForCurrentOS, String libraryFileName, String targetFolder) { String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName; // Attach UUID to the native library file to ensure multiple class loaders can read the libsnappy-java multiple times. String uuid = UUID.randomUUID().toString(); String extractedLibFileName = String.format("snappy-%s-%s-%s", getVersion(), uuid, libraryFileName); File extractedLibFile = new File(targetFolder, extractedLibFileName); try { // Extract a native library file into the target directory InputStream reader = null; FileOutputStream writer = null; try { reader = SnappyLoader.class.getResourceAsStream(nativeLibraryFilePath); try { writer = new FileOutputStream(extractedLibFile); byte[] buffer = new byte[8192]; int bytesRead = 0; while ((bytesRead = reader.read(buffer)) != -1) { writer.write(buffer, 0, bytesRead); } } finally { if (writer != null) { writer.close(); } } } finally { if (reader != null) { reader.close(); } // Delete the extracted lib file on JVM exit. extractedLibFile.deleteOnExit(); } // Set executable (x) flag to enable Java to load the native library boolean success = extractedLibFile.setReadable(true) && extractedLibFile.setWritable(true, true) && extractedLibFile.setExecutable(true); if (!success) { // Setting file flag may fail, but in this case another error will be thrown in later phase } // Check whether the contents are properly copied from the resource folder { InputStream nativeIn = null; InputStream extractedLibIn = null; try { nativeIn = SnappyLoader.class.getResourceAsStream(nativeLibraryFilePath); extractedLibIn = new FileInputStream(extractedLibFile); if (!contentsEquals(nativeIn, extractedLibIn)) { throw new SnappyError(SnappyErrorCode.FAILED_TO_LOAD_NATIVE_LIBRARY, String.format("Failed to write a native library file at %s", extractedLibFile)); } } finally { if (nativeIn != null) { nativeIn.close(); } if (extractedLibIn != null) { extractedLibIn.close(); } } } return new File(targetFolder, extractedLibFileName); } catch (IOException e) { e.printStackTrace(System.err); return null; } } }
public class class_name { private static File extractLibraryFile(String libFolderForCurrentOS, String libraryFileName, String targetFolder) { String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName; // Attach UUID to the native library file to ensure multiple class loaders can read the libsnappy-java multiple times. String uuid = UUID.randomUUID().toString(); String extractedLibFileName = String.format("snappy-%s-%s-%s", getVersion(), uuid, libraryFileName); File extractedLibFile = new File(targetFolder, extractedLibFileName); try { // Extract a native library file into the target directory InputStream reader = null; FileOutputStream writer = null; try { reader = SnappyLoader.class.getResourceAsStream(nativeLibraryFilePath); // depends on control dependency: [try], data = [none] try { writer = new FileOutputStream(extractedLibFile); // depends on control dependency: [try], data = [none] byte[] buffer = new byte[8192]; int bytesRead = 0; while ((bytesRead = reader.read(buffer)) != -1) { writer.write(buffer, 0, bytesRead); // depends on control dependency: [while], data = [none] } } finally { if (writer != null) { writer.close(); // depends on control dependency: [if], data = [none] } } } finally { if (reader != null) { reader.close(); // depends on control dependency: [if], data = [none] } // Delete the extracted lib file on JVM exit. extractedLibFile.deleteOnExit(); } // Set executable (x) flag to enable Java to load the native library boolean success = extractedLibFile.setReadable(true) && extractedLibFile.setWritable(true, true) && extractedLibFile.setExecutable(true); if (!success) { // Setting file flag may fail, but in this case another error will be thrown in later phase } // Check whether the contents are properly copied from the resource folder { InputStream nativeIn = null; InputStream extractedLibIn = null; try { nativeIn = SnappyLoader.class.getResourceAsStream(nativeLibraryFilePath); // depends on control dependency: [try], data = [none] extractedLibIn = new FileInputStream(extractedLibFile); // depends on control dependency: [try], data = [none] if (!contentsEquals(nativeIn, extractedLibIn)) { throw new SnappyError(SnappyErrorCode.FAILED_TO_LOAD_NATIVE_LIBRARY, String.format("Failed to write a native library file at %s", extractedLibFile)); } } finally { if (nativeIn != null) { nativeIn.close(); // depends on control dependency: [if], data = [none] } if (extractedLibIn != null) { extractedLibIn.close(); // depends on control dependency: [if], data = [none] } } } return new File(targetFolder, extractedLibFileName); // depends on control dependency: [try], data = [none] } catch (IOException e) { e.printStackTrace(System.err); return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { final void bipush(CompletableFuture<?> b, BiCompletion<?, ?, ?> c) { if (c != null) { while (result == null) { if (tryPushStack(c)) { if (b.result == null) b.unipush(new CoCompletion(c)); else if (result != null) c.tryFire(SYNC); return; } } b.unipush(c); } } }
public class class_name { final void bipush(CompletableFuture<?> b, BiCompletion<?, ?, ?> c) { if (c != null) { while (result == null) { if (tryPushStack(c)) { if (b.result == null) b.unipush(new CoCompletion(c)); else if (result != null) c.tryFire(SYNC); return; // depends on control dependency: [if], data = [none] } } b.unipush(c); // depends on control dependency: [if], data = [(c] } } }
public class class_name { public void list(String line, DispatchCallback callback) { int index = 0; DatabaseConnections databaseConnections = sqlLine.getDatabaseConnections(); sqlLine.info( sqlLine.loc("active-connections", databaseConnections.size())); for (DatabaseConnection databaseConnection : databaseConnections) { boolean closed; try { closed = databaseConnection.connection.isClosed(); } catch (Exception e) { closed = true; } sqlLine.output( sqlLine.getColorBuffer() .pad(" #" + index++ + "", 5) .pad(closed ? sqlLine.loc("closed") : sqlLine.loc("open"), 9) .pad(databaseConnection.getNickname(), 20) .append(" " + databaseConnection.getUrl())); } callback.setToSuccess(); } }
public class class_name { public void list(String line, DispatchCallback callback) { int index = 0; DatabaseConnections databaseConnections = sqlLine.getDatabaseConnections(); sqlLine.info( sqlLine.loc("active-connections", databaseConnections.size())); for (DatabaseConnection databaseConnection : databaseConnections) { boolean closed; try { closed = databaseConnection.connection.isClosed(); // depends on control dependency: [try], data = [none] } catch (Exception e) { closed = true; } // depends on control dependency: [catch], data = [none] sqlLine.output( sqlLine.getColorBuffer() .pad(" #" + index++ + "", 5) .pad(closed ? sqlLine.loc("closed") : sqlLine.loc("open"), 9) .pad(databaseConnection.getNickname(), 20) .append(" " + databaseConnection.getUrl())); // depends on control dependency: [for], data = [none] } callback.setToSuccess(); } }
public class class_name { private static int[] calculateGridParam(int imagesSize) { int[] gridParam = new int[2]; if (imagesSize < 3) { gridParam[0] = 1; gridParam[1] = imagesSize; } else if (imagesSize <= 4) { gridParam[0] = 2; gridParam[1] = 2; } else { gridParam[0] = imagesSize / 3 + (imagesSize % 3 == 0 ? 0 : 1); gridParam[1] = 3; } return gridParam; } }
public class class_name { private static int[] calculateGridParam(int imagesSize) { int[] gridParam = new int[2]; if (imagesSize < 3) { gridParam[0] = 1; // depends on control dependency: [if], data = [none] gridParam[1] = imagesSize; // depends on control dependency: [if], data = [none] } else if (imagesSize <= 4) { gridParam[0] = 2; // depends on control dependency: [if], data = [none] gridParam[1] = 2; // depends on control dependency: [if], data = [none] } else { gridParam[0] = imagesSize / 3 + (imagesSize % 3 == 0 ? 0 : 1); // depends on control dependency: [if], data = [(imagesSize] gridParam[1] = 3; // depends on control dependency: [if], data = [none] } return gridParam; } }
public class class_name { public void addMemberDescription(FieldDoc field, Content contentTree) { if (field.inlineTags().length > 0) { writer.addInlineComment(field, contentTree); } Tag[] tags = field.tags("serial"); if (tags.length > 0) { writer.addInlineComment(field, tags[0], contentTree); } } }
public class class_name { public void addMemberDescription(FieldDoc field, Content contentTree) { if (field.inlineTags().length > 0) { writer.addInlineComment(field, contentTree); // depends on control dependency: [if], data = [none] } Tag[] tags = field.tags("serial"); if (tags.length > 0) { writer.addInlineComment(field, tags[0], contentTree); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void genArgs(List<JCExpression> trees, List<Type> pts) { for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) { genExpr(l.head, pts.head).load(); pts = pts.tail; } // require lists be of same length Assert.check(pts.isEmpty()); } }
public class class_name { public void genArgs(List<JCExpression> trees, List<Type> pts) { for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) { genExpr(l.head, pts.head).load(); // depends on control dependency: [for], data = [l] pts = pts.tail; // depends on control dependency: [for], data = [none] } // require lists be of same length Assert.check(pts.isEmpty()); } }
public class class_name { public boolean decrement() { synchronized (lock) { if (isDisposed) { return false; } referenceCount--; if (referenceCount <= disposeOnReferenceCount) { isDisposed = true; } return isDisposed; } } }
public class class_name { public boolean decrement() { synchronized (lock) { if (isDisposed) { return false; // depends on control dependency: [if], data = [none] } referenceCount--; if (referenceCount <= disposeOnReferenceCount) { isDisposed = true; // depends on control dependency: [if], data = [none] } return isDisposed; } } }
public class class_name { public ProcessDefinitionEntity getPersistedInstanceOfProcessDefinition(ProcessDefinitionEntity processDefinition) { String deploymentId = processDefinition.getDeploymentId(); if (StringUtils.isEmpty(processDefinition.getDeploymentId())) { throw new IllegalStateException("Provided process definition must have a deployment id."); } ProcessDefinitionEntityManager processDefinitionManager = Context.getCommandContext().getProcessEngineConfiguration().getProcessDefinitionEntityManager(); ProcessDefinitionEntity persistedProcessDefinition = null; if (processDefinition.getTenantId() == null || ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinition.getTenantId())) { persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKey(deploymentId, processDefinition.getKey()); } else { persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKeyAndTenantId(deploymentId, processDefinition.getKey(), processDefinition.getTenantId()); } return persistedProcessDefinition; } }
public class class_name { public ProcessDefinitionEntity getPersistedInstanceOfProcessDefinition(ProcessDefinitionEntity processDefinition) { String deploymentId = processDefinition.getDeploymentId(); if (StringUtils.isEmpty(processDefinition.getDeploymentId())) { throw new IllegalStateException("Provided process definition must have a deployment id."); } ProcessDefinitionEntityManager processDefinitionManager = Context.getCommandContext().getProcessEngineConfiguration().getProcessDefinitionEntityManager(); ProcessDefinitionEntity persistedProcessDefinition = null; if (processDefinition.getTenantId() == null || ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinition.getTenantId())) { persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKey(deploymentId, processDefinition.getKey()); // depends on control dependency: [if], data = [none] } else { persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKeyAndTenantId(deploymentId, processDefinition.getKey(), processDefinition.getTenantId()); // depends on control dependency: [if], data = [none] } return persistedProcessDefinition; } }
public class class_name { public AbstractHTMLElement addClass(String clazz) { String currentClass = this.getProperty("class"); if (currentClass != null) { currentClass += " " + clazz; } else { currentClass = clazz; } this.setProperty("class", currentClass); return this; } }
public class class_name { public AbstractHTMLElement addClass(String clazz) { String currentClass = this.getProperty("class"); if (currentClass != null) { currentClass += " " + clazz; // depends on control dependency: [if], data = [none] } else { currentClass = clazz; // depends on control dependency: [if], data = [none] } this.setProperty("class", currentClass); return this; } }
public class class_name { private int getFieldValueAsInt(final DatatypeConstants.Field field) { Number n = getField(field); if (n != null) { return n.intValue(); } return 0; } }
public class class_name { private int getFieldValueAsInt(final DatatypeConstants.Field field) { Number n = getField(field); if (n != null) { return n.intValue(); // depends on control dependency: [if], data = [none] } return 0; } }
public class class_name { public static BigDecimal e(MathContext mathContext) { checkMathContext(mathContext); BigDecimal result = null; synchronized (eCacheLock) { if (eCache != null && mathContext.getPrecision() <= eCache.precision()) { result = eCache; } else { eCache = exp(ONE, mathContext); return eCache; } } return round(result, mathContext); } }
public class class_name { public static BigDecimal e(MathContext mathContext) { checkMathContext(mathContext); BigDecimal result = null; synchronized (eCacheLock) { if (eCache != null && mathContext.getPrecision() <= eCache.precision()) { result = eCache; // depends on control dependency: [if], data = [none] } else { eCache = exp(ONE, mathContext); // depends on control dependency: [if], data = [none] return eCache; // depends on control dependency: [if], data = [none] } } return round(result, mathContext); } }
public class class_name { public static void adapt(HttpStatusIOException httpStatusException) { String msg = "HTTP Status: " + httpStatusException.getHttpStatusCode(); // if we have a HTTP body try to parse more error details from body if (isNotEmpty(httpStatusException.getHttpBody())) { ObjectMapper mapper = new ObjectMapper(); CmcResult result; try { result = mapper.readValue(httpStatusException.getHttpBody(), CmcResult.class); } catch (Exception e) { // but ignore errors on parsing and throw generic ExchangeException instead throw new ExchangeException(msg, httpStatusException); } // but if it contains a parsable result, then try to parse errors from result: if (result.getStatus() != null && isNotEmpty(result.getStatus().getErrorMessage()) && !result.isSuccess()) { String error = result.getStatus().getErrorMessage(); if (result.getStatus().getErrorCode() == 401) { throw new ExchangeSecurityException(error); } if (result.getStatus().getErrorCode() == 402) { throw new FundsExceededException(error); } if (result.getStatus().getErrorCode() == 429) { throw new FrequencyLimitExceededException(error); } msg = error + " - ErrorCode: " + result.getStatus().getErrorCode(); throw new ExchangeException(msg); } } // else: just throw ExchangeException with causing Exception throw new ExchangeException(msg, httpStatusException); } }
public class class_name { public static void adapt(HttpStatusIOException httpStatusException) { String msg = "HTTP Status: " + httpStatusException.getHttpStatusCode(); // if we have a HTTP body try to parse more error details from body if (isNotEmpty(httpStatusException.getHttpBody())) { ObjectMapper mapper = new ObjectMapper(); CmcResult result; try { result = mapper.readValue(httpStatusException.getHttpBody(), CmcResult.class); // depends on control dependency: [try], data = [none] } catch (Exception e) { // but ignore errors on parsing and throw generic ExchangeException instead throw new ExchangeException(msg, httpStatusException); } // depends on control dependency: [catch], data = [none] // but if it contains a parsable result, then try to parse errors from result: if (result.getStatus() != null && isNotEmpty(result.getStatus().getErrorMessage()) && !result.isSuccess()) { String error = result.getStatus().getErrorMessage(); if (result.getStatus().getErrorCode() == 401) { throw new ExchangeSecurityException(error); } if (result.getStatus().getErrorCode() == 402) { throw new FundsExceededException(error); } if (result.getStatus().getErrorCode() == 429) { throw new FrequencyLimitExceededException(error); } msg = error + " - ErrorCode: " + result.getStatus().getErrorCode(); // depends on control dependency: [if], data = [none] throw new ExchangeException(msg); } } // else: just throw ExchangeException with causing Exception throw new ExchangeException(msg, httpStatusException); } }
public class class_name { public boolean setText (String text) { // the Java text stuff freaks out in a variety of ways if it is asked to deal with the // empty string, so we fake blank labels by just using a space if (StringUtil.isBlank(text)) { text = " "; } // if there is no change then avoid doing anything if (text.equals((_rawText == null) ? _text : _rawText)) { return false; } // _text should contain the text without any tags _text = filterColors(text); // _rawText will be null if there are no tags _rawText = text.equals(_text) ? null : text; // if what we were passed contains escaped color tags, unescape them _text = unescapeColors(_text, true); if (_rawText != null) { _rawText = unescapeColors(_rawText, false); } invalidate("setText"); return true; } }
public class class_name { public boolean setText (String text) { // the Java text stuff freaks out in a variety of ways if it is asked to deal with the // empty string, so we fake blank labels by just using a space if (StringUtil.isBlank(text)) { text = " "; // depends on control dependency: [if], data = [none] } // if there is no change then avoid doing anything if (text.equals((_rawText == null) ? _text : _rawText)) { return false; // depends on control dependency: [if], data = [none] } // _text should contain the text without any tags _text = filterColors(text); // _rawText will be null if there are no tags _rawText = text.equals(_text) ? null : text; // if what we were passed contains escaped color tags, unescape them _text = unescapeColors(_text, true); if (_rawText != null) { _rawText = unescapeColors(_rawText, false); // depends on control dependency: [if], data = [(_rawText] } invalidate("setText"); return true; } }
public class class_name { public void processEvent(EventObject event) { // Don't need to do anything except resend if challenged // (we only get here for a stateless NOTIFY) if (event instanceof ResponseEvent) { receivedResponses.add(new SipResponse((ResponseEvent) event)); resendWithAuthorization((ResponseEvent) event); } } }
public class class_name { public void processEvent(EventObject event) { // Don't need to do anything except resend if challenged // (we only get here for a stateless NOTIFY) if (event instanceof ResponseEvent) { receivedResponses.add(new SipResponse((ResponseEvent) event)); // depends on control dependency: [if], data = [none] resendWithAuthorization((ResponseEvent) event); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void downHeap(int idx) { Reference<E> e = entries.array[idx]; int iter = idx; while (hasChildren(iter)) { int cidx = leftChild(iter); Reference<E> c = entries.array[cidx]; if (hasRightChild(iter)) { int rcidx = rightChild(iter); Reference<E> rc = entries.array[rcidx]; if (compare(rc, c) < 0) { cidx = rcidx; c = rc; } } if (compare(e, c) <= 0) { break; } entries.array[cidx] = e; entries.array[iter] = c; c.index = iter; iter = cidx; } e.index = iter; } }
public class class_name { private void downHeap(int idx) { Reference<E> e = entries.array[idx]; int iter = idx; while (hasChildren(iter)) { int cidx = leftChild(iter); Reference<E> c = entries.array[cidx]; if (hasRightChild(iter)) { int rcidx = rightChild(iter); Reference<E> rc = entries.array[rcidx]; if (compare(rc, c) < 0) { cidx = rcidx; // depends on control dependency: [if], data = [none] c = rc; // depends on control dependency: [if], data = [none] } } if (compare(e, c) <= 0) { break; } entries.array[cidx] = e; // depends on control dependency: [while], data = [none] entries.array[iter] = c; // depends on control dependency: [while], data = [none] c.index = iter; // depends on control dependency: [while], data = [none] iter = cidx; // depends on control dependency: [while], data = [none] } e.index = iter; } }
public class class_name { public Scope getDefiningScope(String name) { for (Scope s = this; s != null; s = s.parentScope) { Map<String,Symbol> symbolTable = s.getSymbolTable(); if (symbolTable != null && symbolTable.containsKey(name)) { return s; } } return null; } }
public class class_name { public Scope getDefiningScope(String name) { for (Scope s = this; s != null; s = s.parentScope) { Map<String,Symbol> symbolTable = s.getSymbolTable(); if (symbolTable != null && symbolTable.containsKey(name)) { return s; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { public static Map<String, String> convertPropertyConnectionsToSimpleForm(Map<String, Set<String>> connections) { Map<String, String> result = new HashMap<String, String>(); if (connections == null) { return result; } for (Map.Entry<String, Set<String>> entry : connections.entrySet()) { result.put(entry.getKey(), Joiner.on(',').join(entry.getValue())); } return result; } }
public class class_name { public static Map<String, String> convertPropertyConnectionsToSimpleForm(Map<String, Set<String>> connections) { Map<String, String> result = new HashMap<String, String>(); if (connections == null) { return result; // depends on control dependency: [if], data = [none] } for (Map.Entry<String, Set<String>> entry : connections.entrySet()) { result.put(entry.getKey(), Joiner.on(',').join(entry.getValue())); // depends on control dependency: [for], data = [entry] } return result; } }
public class class_name { @Override public FilterSupportStatus isFilterSupported( FilterAdapterContext context, SingleColumnValueExcludeFilter filter) { FilterSupportStatus delegateStatus = delegateAdapter.isFilterSupported(context, filter); if (!delegateStatus.isSupported()) { return delegateStatus; } // This filter can only be adapted when there's a single family. if (context.getScan().numFamilies() != 1) { return UNSUPPORTED_STATUS; } return FilterSupportStatus.SUPPORTED; } }
public class class_name { @Override public FilterSupportStatus isFilterSupported( FilterAdapterContext context, SingleColumnValueExcludeFilter filter) { FilterSupportStatus delegateStatus = delegateAdapter.isFilterSupported(context, filter); if (!delegateStatus.isSupported()) { return delegateStatus; // depends on control dependency: [if], data = [none] } // This filter can only be adapted when there's a single family. if (context.getScan().numFamilies() != 1) { return UNSUPPORTED_STATUS; // depends on control dependency: [if], data = [none] } return FilterSupportStatus.SUPPORTED; } }
public class class_name { static public Throwable findRootCause(Throwable throwable) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "findRootCause: " + throwable); } Throwable root = throwable; Throwable next = root; while (next != null) { root = next; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "finding cause of: " + root.getClass().getName()); } if (root instanceof java.rmi.RemoteException) { next = ((java.rmi.RemoteException) root).detail; } else if (root instanceof WsNestedException) // d162976 { next = ((WsNestedException) root).getCause(); // d162976 } else if (root instanceof TransactionRolledbackLocalException) //d180095 begin { next = ((TransactionRolledbackLocalException) root).getCause(); } else if (root instanceof AccessLocalException) { next = ((AccessLocalException) root).getCause(); } else if (root instanceof NoSuchObjectLocalException) { next = ((NoSuchObjectLocalException) root).getCause(); } else if (root instanceof TransactionRequiredLocalException) { next = ((TransactionRequiredLocalException) root).getCause(); } // else if (root instanceof InvalidActivityLocalException) // { // root = ((InvalidActivityLocalException) root).getCause(); // } // else if (root instanceof ActivityRequiredLocalException) // { // root = ((ActivityRequiredLocalException) root).getCause(); // } // else if (root instanceof ActivityCompletedLocalException) // { // next = ((ActivityCompletedLocalException) root).getCause(); //d180095 end // } else if (root instanceof NamingException) { next = ((NamingException) root).getRootCause(); } else if (root instanceof InvocationTargetException) { next = ((InvocationTargetException) root).getTargetException(); } else if (root instanceof org.omg.CORBA.portable.UnknownException) { next = ((org.omg.CORBA.portable.UnknownException) root).originalEx; } else if (root instanceof InjectionException) // d436080 { next = root.getCause(); } else { next = null; } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.exit(tc, "findRootCause returning: " + root); return root; } }
public class class_name { static public Throwable findRootCause(Throwable throwable) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "findRootCause: " + throwable); // depends on control dependency: [if], data = [none] } Throwable root = throwable; Throwable next = root; while (next != null) { root = next; // depends on control dependency: [while], data = [none] if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "finding cause of: " + root.getClass().getName()); // depends on control dependency: [if], data = [none] } if (root instanceof java.rmi.RemoteException) { next = ((java.rmi.RemoteException) root).detail; // depends on control dependency: [if], data = [none] } else if (root instanceof WsNestedException) // d162976 { next = ((WsNestedException) root).getCause(); // d162976 // depends on control dependency: [if], data = [none] } else if (root instanceof TransactionRolledbackLocalException) //d180095 begin { next = ((TransactionRolledbackLocalException) root).getCause(); // depends on control dependency: [if], data = [none] } else if (root instanceof AccessLocalException) { next = ((AccessLocalException) root).getCause(); // depends on control dependency: [if], data = [none] } else if (root instanceof NoSuchObjectLocalException) { next = ((NoSuchObjectLocalException) root).getCause(); // depends on control dependency: [if], data = [none] } else if (root instanceof TransactionRequiredLocalException) { next = ((TransactionRequiredLocalException) root).getCause(); // depends on control dependency: [if], data = [none] } // else if (root instanceof InvalidActivityLocalException) // { // root = ((InvalidActivityLocalException) root).getCause(); // } // else if (root instanceof ActivityRequiredLocalException) // { // root = ((ActivityRequiredLocalException) root).getCause(); // } // else if (root instanceof ActivityCompletedLocalException) // { // next = ((ActivityCompletedLocalException) root).getCause(); //d180095 end // } else if (root instanceof NamingException) { next = ((NamingException) root).getRootCause(); // depends on control dependency: [if], data = [none] } else if (root instanceof InvocationTargetException) { next = ((InvocationTargetException) root).getTargetException(); // depends on control dependency: [if], data = [none] } else if (root instanceof org.omg.CORBA.portable.UnknownException) { next = ((org.omg.CORBA.portable.UnknownException) root).originalEx; // depends on control dependency: [if], data = [none] } else if (root instanceof InjectionException) // d436080 { next = root.getCause(); // depends on control dependency: [if], data = [none] } else { next = null; // depends on control dependency: [if], data = [none] } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.exit(tc, "findRootCause returning: " + root); return root; } }
public class class_name { public void assignNestedValues(XAttributable element, Map<List<String>, Type> amounts) { /* * Add the proper value for every key list. */ for (List<String> keys : amounts.keySet()) { assignNestedValuesPrivate(element, keys, amounts.get(keys)); } } }
public class class_name { public void assignNestedValues(XAttributable element, Map<List<String>, Type> amounts) { /* * Add the proper value for every key list. */ for (List<String> keys : amounts.keySet()) { assignNestedValuesPrivate(element, keys, amounts.get(keys)); // depends on control dependency: [for], data = [keys] } } }
public class class_name { @Override public void addAuthorization(FoxHttpAuthorizationScope foxHttpAuthorizationScope, FoxHttpAuthorization foxHttpAuthorization) { if (foxHttpAuthorizations.containsKey(foxHttpAuthorizationScope.toString())) { foxHttpAuthorizations.get(foxHttpAuthorizationScope.toString()).add(foxHttpAuthorization); } else { foxHttpAuthorizations.put(foxHttpAuthorizationScope.toString(), new ArrayList<>(Collections.singletonList(foxHttpAuthorization))); } } }
public class class_name { @Override public void addAuthorization(FoxHttpAuthorizationScope foxHttpAuthorizationScope, FoxHttpAuthorization foxHttpAuthorization) { if (foxHttpAuthorizations.containsKey(foxHttpAuthorizationScope.toString())) { foxHttpAuthorizations.get(foxHttpAuthorizationScope.toString()).add(foxHttpAuthorization); // depends on control dependency: [if], data = [none] } else { foxHttpAuthorizations.put(foxHttpAuthorizationScope.toString(), new ArrayList<>(Collections.singletonList(foxHttpAuthorization))); // depends on control dependency: [if], data = [none] } } }
public class class_name { public boolean hasPrimitivePeer() { if (mObjectClass == Integer.class || mObjectClass == Boolean.class || mObjectClass == Byte.class || mObjectClass == Character.class || mObjectClass == Short.class || mObjectClass == Long.class || mObjectClass == Float.class || mObjectClass == Double.class || mObjectClass == Void.class) { return true; } return false; } }
public class class_name { public boolean hasPrimitivePeer() { if (mObjectClass == Integer.class || mObjectClass == Boolean.class || mObjectClass == Byte.class || mObjectClass == Character.class || mObjectClass == Short.class || mObjectClass == Long.class || mObjectClass == Float.class || mObjectClass == Double.class || mObjectClass == Void.class) { return true; // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { public JaxRsResponseException convertException(final AbstractJaxRsProvider theServer, final Throwable theException) { if (theServer.withStackTrace()) { exceptionHandler.setReturnStackTracesForExceptionTypes(Throwable.class); } final JaxRsRequest requestDetails = theServer.getRequest(null, null).build(); final BaseServerResponseException convertedException = preprocessException(theException, requestDetails); return new JaxRsResponseException(convertedException); } }
public class class_name { public JaxRsResponseException convertException(final AbstractJaxRsProvider theServer, final Throwable theException) { if (theServer.withStackTrace()) { exceptionHandler.setReturnStackTracesForExceptionTypes(Throwable.class); // depends on control dependency: [if], data = [none] } final JaxRsRequest requestDetails = theServer.getRequest(null, null).build(); final BaseServerResponseException convertedException = preprocessException(theException, requestDetails); return new JaxRsResponseException(convertedException); } }
public class class_name { public CreateImageResponse createImage(CreateImageRequest request) { checkNotNull(request, "request should not be null."); if (Strings.isNullOrEmpty(request.getClientToken())) { request.setClientToken(this.generateClientToken()); } checkStringNotEmpty(request.getImageName(), "request imageName should not be empty."); if (Strings.isNullOrEmpty(request.getInstanceId()) && Strings.isNullOrEmpty(request.getSnapshotId())) { throw new IllegalArgumentException("request instanceId or snapshotId should not be empty ."); } InternalRequest internalRequest = this.createRequest(request, HttpMethodName.POST, IMAGE_PREFIX); internalRequest.addParameter("clientToken", request.getClientToken()); fillPayload(internalRequest, request); return invokeHttpClient(internalRequest, CreateImageResponse.class); } }
public class class_name { public CreateImageResponse createImage(CreateImageRequest request) { checkNotNull(request, "request should not be null."); if (Strings.isNullOrEmpty(request.getClientToken())) { request.setClientToken(this.generateClientToken()); // depends on control dependency: [if], data = [none] } checkStringNotEmpty(request.getImageName(), "request imageName should not be empty."); if (Strings.isNullOrEmpty(request.getInstanceId()) && Strings.isNullOrEmpty(request.getSnapshotId())) { throw new IllegalArgumentException("request instanceId or snapshotId should not be empty ."); } InternalRequest internalRequest = this.createRequest(request, HttpMethodName.POST, IMAGE_PREFIX); internalRequest.addParameter("clientToken", request.getClientToken()); fillPayload(internalRequest, request); return invokeHttpClient(internalRequest, CreateImageResponse.class); } }
public class class_name { public Object resolveParameter(String parameterName, Object defaultValue) { try { return groovyShell.evaluate("m." + parameterName); } catch (RuntimeException rt) { // TODO: Debug warning here... return defaultValue; } } }
public class class_name { public Object resolveParameter(String parameterName, Object defaultValue) { try { return groovyShell.evaluate("m." + parameterName); // depends on control dependency: [try], data = [none] } catch (RuntimeException rt) { // TODO: Debug warning here... return defaultValue; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static Optional<MuteEvent> createMuteEvent(Identification source) { if (source == null) return Optional.empty(); try { MuteEvent muteRequest = new MuteEvent(source); return Optional.of(muteRequest); } catch (IllegalArgumentException e) { return Optional.empty(); } } }
public class class_name { public static Optional<MuteEvent> createMuteEvent(Identification source) { if (source == null) return Optional.empty(); try { MuteEvent muteRequest = new MuteEvent(source); return Optional.of(muteRequest); // depends on control dependency: [try], data = [none] } catch (IllegalArgumentException e) { return Optional.empty(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Pure public static int max(int... values) { if (values == null || values.length == 0) { return 0; } int max = values[0]; for (final int v : values) { if (v > max) { max = v; } } return max; } }
public class class_name { @Pure public static int max(int... values) { if (values == null || values.length == 0) { return 0; // depends on control dependency: [if], data = [none] } int max = values[0]; for (final int v : values) { if (v > max) { max = v; // depends on control dependency: [if], data = [none] } } return max; } }
public class class_name { public static boolean and(IComplexNDArray n, Condition cond) { boolean ret = true; IComplexNDArray linear = n.linearView(); for (int i = 0; i < linear.length(); i++) { ret = ret && cond.apply(linear.getComplex(i)); } return ret; } }
public class class_name { public static boolean and(IComplexNDArray n, Condition cond) { boolean ret = true; IComplexNDArray linear = n.linearView(); for (int i = 0; i < linear.length(); i++) { ret = ret && cond.apply(linear.getComplex(i)); // depends on control dependency: [for], data = [i] } return ret; } }
public class class_name { private void onInheritedProperty(TableInfo tableInfo, EntityType entityType) { String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn(); if (discrColumn != null) { ColumnInfo columnInfo = new ColumnInfo(); columnInfo.setColumnName(discrColumn); columnInfo.setType(String.class); columnInfo.setIndexable(true); IndexInfo idxInfo = new IndexInfo(discrColumn); tableInfo.addColumnInfo(columnInfo); tableInfo.addToIndexedColumnList(idxInfo); } } }
public class class_name { private void onInheritedProperty(TableInfo tableInfo, EntityType entityType) { String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn(); if (discrColumn != null) { ColumnInfo columnInfo = new ColumnInfo(); columnInfo.setColumnName(discrColumn); // depends on control dependency: [if], data = [(discrColumn] columnInfo.setType(String.class); // depends on control dependency: [if], data = [none] columnInfo.setIndexable(true); // depends on control dependency: [if], data = [none] IndexInfo idxInfo = new IndexInfo(discrColumn); tableInfo.addColumnInfo(columnInfo); // depends on control dependency: [if], data = [none] tableInfo.addToIndexedColumnList(idxInfo); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void checkTenantTasks(Tenant tenant) { m_logger.debug("Checking tenant '{}' for needy tasks", tenant); try { for (ApplicationDefinition appDef : SchemaService.instance().getAllApplications(tenant)) { for (Task task : getAppTasks(appDef)) { checkTaskForExecution(appDef, task); } } } catch (Throwable e) { m_logger.warn("Could not check tasks for tenant '{}': {}", tenant.getName(), e); } } }
public class class_name { private void checkTenantTasks(Tenant tenant) { m_logger.debug("Checking tenant '{}' for needy tasks", tenant); try { for (ApplicationDefinition appDef : SchemaService.instance().getAllApplications(tenant)) { for (Task task : getAppTasks(appDef)) { checkTaskForExecution(appDef, task); // depends on control dependency: [for], data = [task] } } } catch (Throwable e) { m_logger.warn("Could not check tasks for tenant '{}': {}", tenant.getName(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void markTaskCompletion() { if (this.countDownLatch.isPresent()) { this.countDownLatch.get().countDown(); } this.taskState.setProp(ConfigurationKeys.TASK_RETRIES_KEY, this.retryCount.get()); } }
public class class_name { public void markTaskCompletion() { if (this.countDownLatch.isPresent()) { this.countDownLatch.get().countDown(); // depends on control dependency: [if], data = [none] } this.taskState.setProp(ConfigurationKeys.TASK_RETRIES_KEY, this.retryCount.get()); } }
public class class_name { public Actions clickAndHold(WebElement target) { if (isBuildingActions()) { action.addAction(new ClickAndHoldAction(jsonMouse, (Locatable) target)); } return moveInTicks(target, 0, 0) .tick(defaultMouse.createPointerDown(LEFT.asArg())); } }
public class class_name { public Actions clickAndHold(WebElement target) { if (isBuildingActions()) { action.addAction(new ClickAndHoldAction(jsonMouse, (Locatable) target)); // depends on control dependency: [if], data = [none] } return moveInTicks(target, 0, 0) .tick(defaultMouse.createPointerDown(LEFT.asArg())); } }
public class class_name { public static void unregisterService(String serviceName, String clientId) { try { if (registry != null) { synchronized (lock) { ServiceInstance<NodeStatus> instance = registry.serviceDiscovery.queryForInstance(serviceName, clientId); if (instance != null) { registry.serviceDiscovery.unregisterService(instance); } else { LOG.warn("你要注销的服务不存在或已经被注销了,服务id:" + clientId); } } } else { LOG.error("服务注册机已经停止,说明本机所有服务已经全部注销,所以没必要再单独注销服务了。", new Throwable()); } } catch (Throwable e) { LOG.error(e); } } }
public class class_name { public static void unregisterService(String serviceName, String clientId) { try { if (registry != null) { synchronized (lock) { // depends on control dependency: [if], data = [none] ServiceInstance<NodeStatus> instance = registry.serviceDiscovery.queryForInstance(serviceName, clientId); if (instance != null) { registry.serviceDiscovery.unregisterService(instance); // depends on control dependency: [if], data = [(instance] } else { LOG.warn("你要注销的服务不存在或已经被注销了,服务id:" + clientId); // depends on control dependency: [if], data = [none] } } } else { LOG.error("服务注册机已经停止,说明本机所有服务已经全部注销,所以没必要再单独注销服务了。", new Throwable()); // depends on control dependency: [if], data = [none] } } catch (Throwable e) { LOG.error(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public synchronized Object get(final long timeout) throws InterruptedException { if (status == closed) { return null; } long currentTime = System.currentTimeMillis(); final long stopTime = currentTime + timeout; Object o = null; while (true) { if ((o = tryGet()) != null) { return o; } currentTime = System.currentTimeMillis(); if (stopTime <= currentTime) { throw new InterruptedException("Get operation timed out"); } try { this.wait(stopTime - currentTime); } catch (final InterruptedException e) { // ignore, but really should retry operation instead } } } }
public class class_name { public synchronized Object get(final long timeout) throws InterruptedException { if (status == closed) { return null; } long currentTime = System.currentTimeMillis(); final long stopTime = currentTime + timeout; Object o = null; while (true) { if ((o = tryGet()) != null) { return o; // depends on control dependency: [if], data = [none] } currentTime = System.currentTimeMillis(); if (stopTime <= currentTime) { throw new InterruptedException("Get operation timed out"); } try { this.wait(stopTime - currentTime); // depends on control dependency: [try], data = [none] } catch (final InterruptedException e) { // ignore, but really should retry operation instead } // depends on control dependency: [catch], data = [none] } } }
public class class_name { @Override public Map<String, String[]> getDeviceProperties(final String name, final String... propertyNames) throws DevFailed { Map<String, String[]> map; if (propertyNames.length == 0) { map = getProperties(PropertyType.Device, name); } else { map = getProperty(PropertyType.Device, name, propertyNames); } return map; } }
public class class_name { @Override public Map<String, String[]> getDeviceProperties(final String name, final String... propertyNames) throws DevFailed { Map<String, String[]> map; if (propertyNames.length == 0) { map = getProperties(PropertyType.Device, name); // depends on control dependency: [if], data = [none] } else { map = getProperty(PropertyType.Device, name, propertyNames); // depends on control dependency: [if], data = [none] } return map; } }
public class class_name { public void setContent(final WComponent content) { WindowModel model = getOrCreateComponentModel(); // If the previous content had been wrapped, then remove it from the wrapping WApplication. if (model.wrappedContent != null && model.wrappedContent != model.content) { model.wrappedContent.removeAll(); } model.content = content; // Wrap content in a WApplication if (content instanceof WApplication) { model.wrappedContent = (WApplication) content; } else { model.wrappedContent = new WApplication(); model.wrappedContent.add(content); } // There should only be one content. holder.removeAll(); holder.add(model.wrappedContent); } }
public class class_name { public void setContent(final WComponent content) { WindowModel model = getOrCreateComponentModel(); // If the previous content had been wrapped, then remove it from the wrapping WApplication. if (model.wrappedContent != null && model.wrappedContent != model.content) { model.wrappedContent.removeAll(); // depends on control dependency: [if], data = [none] } model.content = content; // Wrap content in a WApplication if (content instanceof WApplication) { model.wrappedContent = (WApplication) content; // depends on control dependency: [if], data = [none] } else { model.wrappedContent = new WApplication(); // depends on control dependency: [if], data = [none] model.wrappedContent.add(content); // depends on control dependency: [if], data = [none] } // There should only be one content. holder.removeAll(); holder.add(model.wrappedContent); } }
public class class_name { public void importUser() { // create a new user id String userName = m_orgUnit.getName() + m_userName; try { if (m_throwable != null) { m_user = null; getReport().println(m_throwable); CmsMessageContainer message = Messages.get().container( Messages.ERR_IMPORTEXPORT_ERROR_IMPORTING_USER_1, userName); if (LOG.isDebugEnabled()) { LOG.debug(message.key(), m_throwable); } m_throwable = null; return; } getReport().print(Messages.get().container(Messages.RPT_IMPORT_USER_0), I_CmsReport.FORMAT_NOTE); getReport().print( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_ARGUMENT_1, userName)); getReport().print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0)); try { getCms().readUser(userName); // user exists already getReport().println(Messages.get().container(Messages.RPT_NOT_CREATED_0), I_CmsReport.FORMAT_OK); m_user = null; return; } catch (@SuppressWarnings("unused") CmsDbEntryNotFoundException e) { // user does not exist } CmsParameterConfiguration config = OpenCms.getPasswordHandler().getConfiguration(); if ((config != null) && config.containsKey(I_CmsPasswordHandler.CONVERT_DIGEST_ENCODING)) { if (config.getBoolean(I_CmsPasswordHandler.CONVERT_DIGEST_ENCODING, false)) { m_userPassword = convertDigestEncoding(m_userPassword); } } m_user = getCms().importUser( new CmsUUID().toString(), userName, m_userPassword, m_userFirstname, m_userLastname, m_userEmail, m_userFlags, m_userDateCreated, m_userInfos); getReport().println( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0), I_CmsReport.FORMAT_OK); } catch (Throwable e) { m_user = null; getReport().println(e); CmsMessageContainer message = Messages.get().container( Messages.ERR_IMPORTEXPORT_ERROR_IMPORTING_USER_1, userName); if (LOG.isDebugEnabled()) { LOG.debug(message.key(), e); } } finally { m_userName = null; m_userPassword = null; m_userFirstname = null; m_userLastname = null; m_userEmail = null; m_userFlags = 0; m_userDateCreated = 0; m_userInfos = null; } } }
public class class_name { public void importUser() { // create a new user id String userName = m_orgUnit.getName() + m_userName; try { if (m_throwable != null) { m_user = null; // depends on control dependency: [if], data = [none] getReport().println(m_throwable); // depends on control dependency: [if], data = [(m_throwable] CmsMessageContainer message = Messages.get().container( Messages.ERR_IMPORTEXPORT_ERROR_IMPORTING_USER_1, userName); if (LOG.isDebugEnabled()) { LOG.debug(message.key(), m_throwable); // depends on control dependency: [if], data = [none] } m_throwable = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } getReport().print(Messages.get().container(Messages.RPT_IMPORT_USER_0), I_CmsReport.FORMAT_NOTE); // depends on control dependency: [try], data = [none] getReport().print( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_ARGUMENT_1, userName)); // depends on control dependency: [try], data = [none] getReport().print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0)); // depends on control dependency: [try], data = [none] try { getCms().readUser(userName); // depends on control dependency: [try], data = [none] // user exists already getReport().println(Messages.get().container(Messages.RPT_NOT_CREATED_0), I_CmsReport.FORMAT_OK); // depends on control dependency: [try], data = [none] m_user = null; // depends on control dependency: [try], data = [none] return; // depends on control dependency: [try], data = [none] } catch (@SuppressWarnings("unused") CmsDbEntryNotFoundException e) { // user does not exist } // depends on control dependency: [catch], data = [none] CmsParameterConfiguration config = OpenCms.getPasswordHandler().getConfiguration(); if ((config != null) && config.containsKey(I_CmsPasswordHandler.CONVERT_DIGEST_ENCODING)) { if (config.getBoolean(I_CmsPasswordHandler.CONVERT_DIGEST_ENCODING, false)) { m_userPassword = convertDigestEncoding(m_userPassword); // depends on control dependency: [if], data = [none] } } m_user = getCms().importUser( new CmsUUID().toString(), userName, m_userPassword, m_userFirstname, m_userLastname, m_userEmail, m_userFlags, m_userDateCreated, m_userInfos); // depends on control dependency: [try], data = [none] getReport().println( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0), I_CmsReport.FORMAT_OK); // depends on control dependency: [try], data = [none] } catch (Throwable e) { m_user = null; getReport().println(e); CmsMessageContainer message = Messages.get().container( Messages.ERR_IMPORTEXPORT_ERROR_IMPORTING_USER_1, userName); if (LOG.isDebugEnabled()) { LOG.debug(message.key(), e); // depends on control dependency: [if], data = [none] } } finally { // depends on control dependency: [catch], data = [none] m_userName = null; m_userPassword = null; m_userFirstname = null; m_userLastname = null; m_userEmail = null; m_userFlags = 0; m_userDateCreated = 0; m_userInfos = null; } } }
public class class_name { private void compareRow(Object computedRow, List<FitCell> expectedCells) { for (int i = 0; i < columnNames.length && expectedCells != null; i++) { try { ValueReceiver valueReceiver; if (isComment(i)) { valueReceiver = null; } else { valueReceiver = createReceiver(computedRow, columnNames[i]); } String columnParameter = FitUtils.saveGet(i, columnParameters); check(expectedCells.get(i), valueReceiver, columnParameter); } catch (NoSuchMethodException | NoSuchFieldException e) { expectedCells.indexOf(e); } } } }
public class class_name { private void compareRow(Object computedRow, List<FitCell> expectedCells) { for (int i = 0; i < columnNames.length && expectedCells != null; i++) { try { ValueReceiver valueReceiver; if (isComment(i)) { valueReceiver = null; // depends on control dependency: [if], data = [none] } else { valueReceiver = createReceiver(computedRow, columnNames[i]); // depends on control dependency: [if], data = [none] } String columnParameter = FitUtils.saveGet(i, columnParameters); check(expectedCells.get(i), valueReceiver, columnParameter); // depends on control dependency: [try], data = [none] } catch (NoSuchMethodException | NoSuchFieldException e) { expectedCells.indexOf(e); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { public static void configure(Job conf, SimpleConfiguration props) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); props.save(baos); conf.getConfiguration().set(PROPS_CONF_KEY, new String(baos.toByteArray(), StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } } }
public class class_name { public static void configure(Job conf, SimpleConfiguration props) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); props.save(baos); // depends on control dependency: [try], data = [none] conf.getConfiguration().set(PROPS_CONF_KEY, new String(baos.toByteArray(), StandardCharsets.UTF_8)); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public double[] dijkstra(int s, boolean weighted) { double[] wt = new double[n]; Arrays.fill(wt, Double.POSITIVE_INFINITY); PriorityQueue queue = new PriorityQueue(wt); for (int v = 0; v < n; v++) { queue.insert(v); } wt[s] = 0.0; queue.lower(s); while (!queue.empty()) { int v = queue.poll(); if (!Double.isInfinite(wt[v])) { for (int w = 0; w < n; w++) { if (graph[v][w] != 0.0) { double p = weighted ? wt[v] + graph[v][w] : wt[v] + 1; if (p < wt[w]) { wt[w] = p; queue.lower(w); } } } } } return wt; } }
public class class_name { public double[] dijkstra(int s, boolean weighted) { double[] wt = new double[n]; Arrays.fill(wt, Double.POSITIVE_INFINITY); PriorityQueue queue = new PriorityQueue(wt); for (int v = 0; v < n; v++) { queue.insert(v); // depends on control dependency: [for], data = [v] } wt[s] = 0.0; queue.lower(s); while (!queue.empty()) { int v = queue.poll(); if (!Double.isInfinite(wt[v])) { for (int w = 0; w < n; w++) { if (graph[v][w] != 0.0) { double p = weighted ? wt[v] + graph[v][w] : wt[v] + 1; if (p < wt[w]) { wt[w] = p; // depends on control dependency: [if], data = [none] queue.lower(w); // depends on control dependency: [if], data = [none] } } } } } return wt; } }
public class class_name { public boolean remove(KType key) { if (Intrinsics.isEmpty(key)) { boolean hadEmptyKey = hasEmptyKey; hasEmptyKey = false; return hadEmptyKey; } else { final KType [] keys = Intrinsics.<KType[]> cast(this.keys); final int mask = this.mask; int slot = hashKey(key) & mask; KType existing; while (!Intrinsics.isEmpty(existing = keys[slot])) { if (Intrinsics.equals(this, key, existing)) { shiftConflictingKeys(slot); return true; } slot = (slot + 1) & mask; } return false; } } }
public class class_name { public boolean remove(KType key) { if (Intrinsics.isEmpty(key)) { boolean hadEmptyKey = hasEmptyKey; hasEmptyKey = false; // depends on control dependency: [if], data = [none] return hadEmptyKey; // depends on control dependency: [if], data = [none] } else { final KType [] keys = Intrinsics.<KType[]> cast(this.keys); final int mask = this.mask; int slot = hashKey(key) & mask; KType existing; while (!Intrinsics.isEmpty(existing = keys[slot])) { if (Intrinsics.equals(this, key, existing)) { shiftConflictingKeys(slot); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } slot = (slot + 1) & mask; // depends on control dependency: [while], data = [none] } return false; // depends on control dependency: [if], data = [none] } } }
public class class_name { private List<SimulatorEvent> processTaskAttemptCompletionEvent( TaskAttemptCompletionEvent event) { if (LOG.isDebugEnabled()) { LOG.debug("Processing task attempt completion event" + event); } long now = event.getTimeStamp(); TaskStatus finalStatus = event.getStatus(); TaskAttemptID taskID = finalStatus.getTaskID(); boolean killedEarlier = orphanTaskCompletions.remove(taskID); if (!killedEarlier) { finishRunningTask(finalStatus, now); } return SimulatorEngine.EMPTY_EVENTS; } }
public class class_name { private List<SimulatorEvent> processTaskAttemptCompletionEvent( TaskAttemptCompletionEvent event) { if (LOG.isDebugEnabled()) { LOG.debug("Processing task attempt completion event" + event); // depends on control dependency: [if], data = [none] } long now = event.getTimeStamp(); TaskStatus finalStatus = event.getStatus(); TaskAttemptID taskID = finalStatus.getTaskID(); boolean killedEarlier = orphanTaskCompletions.remove(taskID); if (!killedEarlier) { finishRunningTask(finalStatus, now); // depends on control dependency: [if], data = [none] } return SimulatorEngine.EMPTY_EVENTS; } }
public class class_name { public EClass getIfcFillStyleSelect() { if (ifcFillStyleSelectEClass == null) { ifcFillStyleSelectEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(955); } return ifcFillStyleSelectEClass; } }
public class class_name { public EClass getIfcFillStyleSelect() { if (ifcFillStyleSelectEClass == null) { ifcFillStyleSelectEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(955); // depends on control dependency: [if], data = [none] } return ifcFillStyleSelectEClass; } }
public class class_name { Symbol addConstantMethodHandle( final int referenceKind, final String owner, final String name, final String descriptor, final boolean isInterface) { final int tag = Symbol.CONSTANT_METHOD_HANDLE_TAG; // Note that we don't need to include isInterface in the hash computation, because it is // redundant with owner (we can't have the same owner with different isInterface values). int hashCode = hash(tag, owner, name, descriptor, referenceKind); Entry entry = get(hashCode); while (entry != null) { if (entry.tag == tag && entry.hashCode == hashCode && entry.data == referenceKind && entry.owner.equals(owner) && entry.name.equals(name) && entry.value.equals(descriptor)) { return entry; } entry = entry.next; } if (referenceKind <= Opcodes.H_PUTSTATIC) { constantPool.put112(tag, referenceKind, addConstantFieldref(owner, name, descriptor).index); } else { constantPool.put112( tag, referenceKind, addConstantMethodref(owner, name, descriptor, isInterface).index); } return put( new Entry(constantPoolCount++, tag, owner, name, descriptor, referenceKind, hashCode)); } }
public class class_name { Symbol addConstantMethodHandle( final int referenceKind, final String owner, final String name, final String descriptor, final boolean isInterface) { final int tag = Symbol.CONSTANT_METHOD_HANDLE_TAG; // Note that we don't need to include isInterface in the hash computation, because it is // redundant with owner (we can't have the same owner with different isInterface values). int hashCode = hash(tag, owner, name, descriptor, referenceKind); Entry entry = get(hashCode); while (entry != null) { if (entry.tag == tag && entry.hashCode == hashCode && entry.data == referenceKind && entry.owner.equals(owner) && entry.name.equals(name) && entry.value.equals(descriptor)) { return entry; // depends on control dependency: [if], data = [none] } entry = entry.next; // depends on control dependency: [while], data = [none] } if (referenceKind <= Opcodes.H_PUTSTATIC) { constantPool.put112(tag, referenceKind, addConstantFieldref(owner, name, descriptor).index); // depends on control dependency: [if], data = [none] } else { constantPool.put112( tag, referenceKind, addConstantMethodref(owner, name, descriptor, isInterface).index); // depends on control dependency: [if], data = [none] } return put( new Entry(constantPoolCount++, tag, owner, name, descriptor, referenceKind, hashCode)); } }
public class class_name { public static Coordinate coordinateFromColRow( int col, int row, GridGeometry2D gridGeometry ) { try { GridCoordinates2D pos = new GridCoordinates2D(col, row); DirectPosition gridToWorld = gridGeometry.gridToWorld(pos); double[] coord = gridToWorld.getCoordinate(); return new Coordinate(coord[0], coord[1]); } catch (InvalidGridGeometryException e) { e.printStackTrace(); } catch (TransformException e) { e.printStackTrace(); } return null; } }
public class class_name { public static Coordinate coordinateFromColRow( int col, int row, GridGeometry2D gridGeometry ) { try { GridCoordinates2D pos = new GridCoordinates2D(col, row); DirectPosition gridToWorld = gridGeometry.gridToWorld(pos); double[] coord = gridToWorld.getCoordinate(); return new Coordinate(coord[0], coord[1]); // depends on control dependency: [try], data = [none] } catch (InvalidGridGeometryException e) { e.printStackTrace(); } catch (TransformException e) { // depends on control dependency: [catch], data = [none] e.printStackTrace(); } // depends on control dependency: [catch], data = [none] return null; } }
public class class_name { public static String formatRadiuses(double[] radiuses) { if (radiuses == null || radiuses.length == 0) { return null; } String[] radiusesFormatted = new String[radiuses.length]; for (int i = 0; i < radiuses.length; i++) { if (radiuses[i] == Double.POSITIVE_INFINITY) { radiusesFormatted[i] = "unlimited"; } else { radiusesFormatted[i] = String.format(Locale.US, "%s", TextUtils.formatCoordinate(radiuses[i])); } } return join(";", radiusesFormatted); } }
public class class_name { public static String formatRadiuses(double[] radiuses) { if (radiuses == null || radiuses.length == 0) { return null; // depends on control dependency: [if], data = [none] } String[] radiusesFormatted = new String[radiuses.length]; for (int i = 0; i < radiuses.length; i++) { if (radiuses[i] == Double.POSITIVE_INFINITY) { radiusesFormatted[i] = "unlimited"; // depends on control dependency: [if], data = [none] } else { radiusesFormatted[i] = String.format(Locale.US, "%s", TextUtils.formatCoordinate(radiuses[i])); // depends on control dependency: [if], data = [none] } } return join(";", radiusesFormatted); } }
public class class_name { public static int cublasSetVector (int n, cuDoubleComplex x[], int offsetx, int incx, Pointer y, int incy) { ByteBuffer byteBufferx = ByteBuffer.allocateDirect(x.length * 8 * 2); byteBufferx.order(ByteOrder.nativeOrder()); DoubleBuffer doubleBufferx = byteBufferx.asDoubleBuffer(); int indexx = offsetx; for (int i=0; i<n; i++, indexx+=incx) { doubleBufferx.put(indexx*2+0, x[indexx].x); doubleBufferx.put(indexx*2+1, x[indexx].y); } return checkResult(cublasSetVectorNative(n, 16, Pointer.to(doubleBufferx).withByteOffset(offsetx * 8 * 2), incx, y, incy)); } }
public class class_name { public static int cublasSetVector (int n, cuDoubleComplex x[], int offsetx, int incx, Pointer y, int incy) { ByteBuffer byteBufferx = ByteBuffer.allocateDirect(x.length * 8 * 2); byteBufferx.order(ByteOrder.nativeOrder()); DoubleBuffer doubleBufferx = byteBufferx.asDoubleBuffer(); int indexx = offsetx; for (int i=0; i<n; i++, indexx+=incx) { doubleBufferx.put(indexx*2+0, x[indexx].x); // depends on control dependency: [for], data = [none] doubleBufferx.put(indexx*2+1, x[indexx].y); // depends on control dependency: [for], data = [none] } return checkResult(cublasSetVectorNative(n, 16, Pointer.to(doubleBufferx).withByteOffset(offsetx * 8 * 2), incx, y, incy)); } }
public class class_name { @Override public void visitClassContext(ClassContext classContext) { try { JavaClass cls = classContext.getJavaClass(); for (CompareSpec entry : compareClasses) { if (cls.implementationOf(entry.getCompareClass())) { methodInfo = entry.getMethodInfo(); stack = new OpcodeStack(); super.visitClassContext(classContext); break; } } } catch (ClassNotFoundException cnfe) { bugReporter.reportMissingClass(cnfe); } finally { methodInfo = null; stack = null; } } }
public class class_name { @Override public void visitClassContext(ClassContext classContext) { try { JavaClass cls = classContext.getJavaClass(); for (CompareSpec entry : compareClasses) { if (cls.implementationOf(entry.getCompareClass())) { methodInfo = entry.getMethodInfo(); // depends on control dependency: [if], data = [none] stack = new OpcodeStack(); // depends on control dependency: [if], data = [none] super.visitClassContext(classContext); // depends on control dependency: [if], data = [none] break; } } } catch (ClassNotFoundException cnfe) { bugReporter.reportMissingClass(cnfe); } finally { // depends on control dependency: [catch], data = [none] methodInfo = null; stack = null; } } }
public class class_name { private void expireDevices() { long now = System.currentTimeMillis(); // Make a copy so we don't have to worry about concurrent modification. Map<InetAddress, DeviceAnnouncement> copy = new HashMap<InetAddress, DeviceAnnouncement>(devices); for (Map.Entry<InetAddress, DeviceAnnouncement> entry : copy.entrySet()) { if (now - entry.getValue().getTimestamp() > MAXIMUM_AGE) { devices.remove(entry.getKey()); deliverLostAnnouncement(entry.getValue()); } } if (devices.isEmpty()) { firstDeviceTime.set(0); // We have lost contact with the Pro DJ Link network, so start over with next device. } } }
public class class_name { private void expireDevices() { long now = System.currentTimeMillis(); // Make a copy so we don't have to worry about concurrent modification. Map<InetAddress, DeviceAnnouncement> copy = new HashMap<InetAddress, DeviceAnnouncement>(devices); for (Map.Entry<InetAddress, DeviceAnnouncement> entry : copy.entrySet()) { if (now - entry.getValue().getTimestamp() > MAXIMUM_AGE) { devices.remove(entry.getKey()); // depends on control dependency: [if], data = [none] deliverLostAnnouncement(entry.getValue()); // depends on control dependency: [if], data = [none] } } if (devices.isEmpty()) { firstDeviceTime.set(0); // We have lost contact with the Pro DJ Link network, so start over with next device. // depends on control dependency: [if], data = [none] } } }
public class class_name { protected String getRequestHost() { String forwarded = header("X-Forwarded-Host"); if (StringUtil.blank(forwarded)) { return host(); } String[] forwards = forwarded.split(","); return forwards[0].trim(); } }
public class class_name { protected String getRequestHost() { String forwarded = header("X-Forwarded-Host"); if (StringUtil.blank(forwarded)) { return host(); // depends on control dependency: [if], data = [none] } String[] forwards = forwarded.split(","); return forwards[0].trim(); } }
public class class_name { public static Map<String, Integer> createNGrams(String inputQuery, boolean removeStopWords) { List<String> wordsInString = Lists.newArrayList(Stemmer.replaceIllegalCharacter(inputQuery).split(" ")); if (removeStopWords) wordsInString.removeAll(STOPWORDSLIST); List<String> stemmedWordsInString = wordsInString.stream().map(Stemmer::stem).collect(Collectors.toList()); Map<String, Integer> tokens = new HashMap<>(); // Padding the string for (String singleWord : stemmedWordsInString) { if (!StringUtils.isEmpty(singleWord)) { // The s$ will be the produced from two words. StringBuilder singleString = new StringBuilder(singleWord.length() + 2); singleString.append('^').append(singleWord.toLowerCase()).append('$'); int length = singleString.length(); for (int i = 0; i < length - 1; i++) { String token = null; if (i + N_GRAMS < length) { token = singleString.substring(i, i + N_GRAMS); } else { token = singleString.substring(length - 2); } if (!tokens.containsKey(token)) { tokens.put(token, 1); } else { tokens.put(token, (tokens.get(token) + 1)); } } } } return tokens; } }
public class class_name { public static Map<String, Integer> createNGrams(String inputQuery, boolean removeStopWords) { List<String> wordsInString = Lists.newArrayList(Stemmer.replaceIllegalCharacter(inputQuery).split(" ")); if (removeStopWords) wordsInString.removeAll(STOPWORDSLIST); List<String> stemmedWordsInString = wordsInString.stream().map(Stemmer::stem).collect(Collectors.toList()); Map<String, Integer> tokens = new HashMap<>(); // Padding the string for (String singleWord : stemmedWordsInString) { if (!StringUtils.isEmpty(singleWord)) { // The s$ will be the produced from two words. StringBuilder singleString = new StringBuilder(singleWord.length() + 2); singleString.append('^').append(singleWord.toLowerCase()).append('$'); // depends on control dependency: [if], data = [none] int length = singleString.length(); for (int i = 0; i < length - 1; i++) { String token = null; if (i + N_GRAMS < length) { token = singleString.substring(i, i + N_GRAMS); // depends on control dependency: [if], data = [none] } else { token = singleString.substring(length - 2); // depends on control dependency: [if], data = [none] } if (!tokens.containsKey(token)) { tokens.put(token, 1); // depends on control dependency: [if], data = [none] } else { tokens.put(token, (tokens.get(token) + 1)); // depends on control dependency: [if], data = [none] } } } } return tokens; } }
public class class_name { @Override public EClass getIfcSurfaceCurveSweptAreaSolid() { if (ifcSurfaceCurveSweptAreaSolidEClass == null) { ifcSurfaceCurveSweptAreaSolidEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(673); } return ifcSurfaceCurveSweptAreaSolidEClass; } }
public class class_name { @Override public EClass getIfcSurfaceCurveSweptAreaSolid() { if (ifcSurfaceCurveSweptAreaSolidEClass == null) { ifcSurfaceCurveSweptAreaSolidEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(673); // depends on control dependency: [if], data = [none] } return ifcSurfaceCurveSweptAreaSolidEClass; } }
public class class_name { public Priority[] filePriorities() { int_vector v = th.get_file_priorities2(); int size = (int) v.size(); Priority[] arr = new Priority[size]; for (int i = 0; i < size; i++) { arr[i] = Priority.fromSwig(v.get(i)); } return arr; } }
public class class_name { public Priority[] filePriorities() { int_vector v = th.get_file_priorities2(); int size = (int) v.size(); Priority[] arr = new Priority[size]; for (int i = 0; i < size; i++) { arr[i] = Priority.fromSwig(v.get(i)); // depends on control dependency: [for], data = [i] } return arr; } }
public class class_name { private static Integer decodeInt(String token) { try { return Integer.decode(token); } catch (NumberFormatException e) { return null; } } }
public class class_name { private static Integer decodeInt(String token) { try { return Integer.decode(token); // depends on control dependency: [try], data = [none] } catch (NumberFormatException e) { return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public boolean deleteProperty(String name) { BugProperty prev = null; BugProperty prop = propertyListHead; while (prop != null) { if (prop.getName().equals(name)) { break; } prev = prop; prop = prop.getNext(); } if (prop != null) { if (prev != null) { // Deleted node in interior or at tail of list prev.setNext(prop.getNext()); } else { // Deleted node at head of list propertyListHead = prop.getNext(); } if (prop.getNext() == null) { // Deleted node at end of list propertyListTail = prev; } return true; } else { // No such property return false; } } }
public class class_name { public boolean deleteProperty(String name) { BugProperty prev = null; BugProperty prop = propertyListHead; while (prop != null) { if (prop.getName().equals(name)) { break; } prev = prop; // depends on control dependency: [while], data = [none] prop = prop.getNext(); // depends on control dependency: [while], data = [none] } if (prop != null) { if (prev != null) { // Deleted node in interior or at tail of list prev.setNext(prop.getNext()); // depends on control dependency: [if], data = [none] } else { // Deleted node at head of list propertyListHead = prop.getNext(); // depends on control dependency: [if], data = [none] } if (prop.getNext() == null) { // Deleted node at end of list propertyListTail = prev; // depends on control dependency: [if], data = [none] } return true; // depends on control dependency: [if], data = [none] } else { // No such property return false; // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public Description matchMethodInvocation(MethodInvocationTree t, VisitorState state) { String arg1; String arg2; if (instanceEqualsMatcher.matches(t, state)) { arg1 = state.getSourceForNode(((JCFieldAccess) t.getMethodSelect()).getExpression()); arg2 = state.getSourceForNode(t.getArguments().get(0)); } else if (staticEqualsMatcher.matches(t, state)) { arg1 = state.getSourceForNode(t.getArguments().get(0)); arg2 = state.getSourceForNode(t.getArguments().get(1)); } else { return NO_MATCH; } Fix fix = SuggestedFix.builder() .replace(t, "Arrays.equals(" + arg1 + ", " + arg2 + ")") .addImport("java.util.Arrays") .build(); return describeMatch(t, fix); } }
public class class_name { @Override public Description matchMethodInvocation(MethodInvocationTree t, VisitorState state) { String arg1; String arg2; if (instanceEqualsMatcher.matches(t, state)) { arg1 = state.getSourceForNode(((JCFieldAccess) t.getMethodSelect()).getExpression()); // depends on control dependency: [if], data = [none] arg2 = state.getSourceForNode(t.getArguments().get(0)); // depends on control dependency: [if], data = [none] } else if (staticEqualsMatcher.matches(t, state)) { arg1 = state.getSourceForNode(t.getArguments().get(0)); // depends on control dependency: [if], data = [none] arg2 = state.getSourceForNode(t.getArguments().get(1)); // depends on control dependency: [if], data = [none] } else { return NO_MATCH; // depends on control dependency: [if], data = [none] } Fix fix = SuggestedFix.builder() .replace(t, "Arrays.equals(" + arg1 + ", " + arg2 + ")") .addImport("java.util.Arrays") .build(); return describeMatch(t, fix); } }
public class class_name { public String url() { try { return driver.getCurrentUrl(); } catch (Exception e) { log.warn(e); return null; } } }
public class class_name { public String url() { try { return driver.getCurrentUrl(); // depends on control dependency: [try], data = [none] } catch (Exception e) { log.warn(e); return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static long getLong(String pStr) { if (isEmpty(pStr)) { return 0; } long value = 0; try { value = Long.parseLong(pStr); } catch (NumberFormatException nm) { } return value; } }
public class class_name { public static long getLong(String pStr) { if (isEmpty(pStr)) { return 0; // depends on control dependency: [if], data = [none] } long value = 0; try { value = Long.parseLong(pStr); // depends on control dependency: [try], data = [none] } catch (NumberFormatException nm) { } // depends on control dependency: [catch], data = [none] return value; } }
public class class_name { public static int intLogBase2v2(int value) { int temp; if ((temp = value >> 24) > 0) { return 24 + LOG_TABLE_256[temp]; } else if ((temp = value >> 16) > 0) { return 16 + LOG_TABLE_256[temp]; } else if ((temp = value >> 8) > 0) { return 8 + LOG_TABLE_256[temp]; } else { return LOG_TABLE_256[value]; } } }
public class class_name { public static int intLogBase2v2(int value) { int temp; if ((temp = value >> 24) > 0) { return 24 + LOG_TABLE_256[temp]; // depends on control dependency: [if], data = [none] } else if ((temp = value >> 16) > 0) { return 16 + LOG_TABLE_256[temp]; // depends on control dependency: [if], data = [none] } else if ((temp = value >> 8) > 0) { return 8 + LOG_TABLE_256[temp]; // depends on control dependency: [if], data = [none] } else { return LOG_TABLE_256[value]; // depends on control dependency: [if], data = [none] } } }
public class class_name { public void reloadPolicies(String scanPolicyName) { DefaultComboBoxModel<String> policies = new DefaultComboBoxModel<>(); for (String policy : extension.getPolicyManager().getAllPolicyNames()) { policies.addElement(policy); } getPolicySelector().setModel(policies); getPolicySelector().setSelectedItem(scanPolicyName); } }
public class class_name { public void reloadPolicies(String scanPolicyName) { DefaultComboBoxModel<String> policies = new DefaultComboBoxModel<>(); for (String policy : extension.getPolicyManager().getAllPolicyNames()) { policies.addElement(policy); // depends on control dependency: [for], data = [policy] } getPolicySelector().setModel(policies); getPolicySelector().setSelectedItem(scanPolicyName); } }
public class class_name { private Attribute<?> toAssociationDto(Object value, AssociationAttributeInfo associationAttributeInfo) throws GeomajasException { if (associationAttributeInfo.getType() == AssociationType.MANY_TO_ONE) { return new ManyToOneAttribute(createAssociationValue(value, associationAttributeInfo)); } else if (associationAttributeInfo.getType() == AssociationType.ONE_TO_MANY) { // Value should be an array of objects... List<AssociationValue> associationValues = new ArrayList<AssociationValue>(); if (value != null && value instanceof Object[]) { Object[] array = (Object[]) value; for (Object bean : array) { associationValues.add(createAssociationValue(bean, associationAttributeInfo)); } } return new OneToManyAttribute(associationValues); } return null; } }
public class class_name { private Attribute<?> toAssociationDto(Object value, AssociationAttributeInfo associationAttributeInfo) throws GeomajasException { if (associationAttributeInfo.getType() == AssociationType.MANY_TO_ONE) { return new ManyToOneAttribute(createAssociationValue(value, associationAttributeInfo)); } else if (associationAttributeInfo.getType() == AssociationType.ONE_TO_MANY) { // Value should be an array of objects... List<AssociationValue> associationValues = new ArrayList<AssociationValue>(); if (value != null && value instanceof Object[]) { Object[] array = (Object[]) value; for (Object bean : array) { associationValues.add(createAssociationValue(bean, associationAttributeInfo)); // depends on control dependency: [for], data = [bean] } } return new OneToManyAttribute(associationValues); } return null; } }
public class class_name { protected void finallyInvocation(InterceptorStatusToken token) { if (token != null && token.isContextHolderRefreshRequired()) { if (logger.isDebugEnabled()) { logger.debug("Reverting to original Authentication: " + token.getSecurityContext().getAuthentication()); } SecurityContextHolder.setContext(token.getSecurityContext()); } } }
public class class_name { protected void finallyInvocation(InterceptorStatusToken token) { if (token != null && token.isContextHolderRefreshRequired()) { if (logger.isDebugEnabled()) { logger.debug("Reverting to original Authentication: " + token.getSecurityContext().getAuthentication()); // depends on control dependency: [if], data = [none] } SecurityContextHolder.setContext(token.getSecurityContext()); // depends on control dependency: [if], data = [(token] } } }
public class class_name { private final Object slotExchange(Object item, boolean timed, long ns) { Node p = participant.get(); Thread t = Thread.currentThread(); if (t.isInterrupted()) // preserve interrupt status so caller can recheck return null; for (Node q;;) { if ((q = slot) != null) { if (U.compareAndSwapObject(this, SLOT, q, null)) { Object v = q.item; q.match = item; Thread w = q.parked; if (w != null) U.unpark(w); return v; } // create arena on contention, but continue until slot null if (NCPU > 1 && bound == 0 && U.compareAndSwapInt(this, BOUND, 0, SEQ)) arena = new Node[(FULL + 2) << ASHIFT]; } else if (arena != null) return null; // caller must reroute to arenaExchange else { p.item = item; if (U.compareAndSwapObject(this, SLOT, null, p)) break; p.item = null; } } // await release int h = p.hash; long end = timed ? System.nanoTime() + ns : 0L; int spins = (NCPU > 1) ? SPINS : 1; Object v; while ((v = p.match) == null) { if (spins > 0) { h ^= h << 1; h ^= h >>> 3; h ^= h << 10; if (h == 0) h = SPINS | (int)t.getId(); else if (h < 0 && (--spins & ((SPINS >>> 1) - 1)) == 0) Thread.yield(); } else if (slot != p) spins = SPINS; else if (!t.isInterrupted() && arena == null && (!timed || (ns = end - System.nanoTime()) > 0L)) { U.putObject(t, BLOCKER, this); p.parked = t; if (slot == p) U.park(false, ns); p.parked = null; U.putObject(t, BLOCKER, null); } else if (U.compareAndSwapObject(this, SLOT, p, null)) { v = timed && ns <= 0L && !t.isInterrupted() ? TIMED_OUT : null; break; } } U.putOrderedObject(p, MATCH, null); p.item = null; p.hash = h; return v; } }
public class class_name { private final Object slotExchange(Object item, boolean timed, long ns) { Node p = participant.get(); Thread t = Thread.currentThread(); if (t.isInterrupted()) // preserve interrupt status so caller can recheck return null; for (Node q;;) { if ((q = slot) != null) { if (U.compareAndSwapObject(this, SLOT, q, null)) { Object v = q.item; q.match = item; // depends on control dependency: [if], data = [none] Thread w = q.parked; if (w != null) U.unpark(w); return v; // depends on control dependency: [if], data = [none] } // create arena on contention, but continue until slot null if (NCPU > 1 && bound == 0 && U.compareAndSwapInt(this, BOUND, 0, SEQ)) arena = new Node[(FULL + 2) << ASHIFT]; } else if (arena != null) return null; // caller must reroute to arenaExchange else { p.item = item; // depends on control dependency: [if], data = [none] if (U.compareAndSwapObject(this, SLOT, null, p)) break; p.item = null; // depends on control dependency: [if], data = [none] } } // await release int h = p.hash; long end = timed ? System.nanoTime() + ns : 0L; int spins = (NCPU > 1) ? SPINS : 1; Object v; while ((v = p.match) == null) { if (spins > 0) { h ^= h << 1; h ^= h >>> 3; h ^= h << 10; // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none] if (h == 0) h = SPINS | (int)t.getId(); else if (h < 0 && (--spins & ((SPINS >>> 1) - 1)) == 0) Thread.yield(); } else if (slot != p) spins = SPINS; else if (!t.isInterrupted() && arena == null && (!timed || (ns = end - System.nanoTime()) > 0L)) { U.putObject(t, BLOCKER, this); // depends on control dependency: [if], data = [none] p.parked = t; // depends on control dependency: [if], data = [none] if (slot == p) U.park(false, ns); p.parked = null; // depends on control dependency: [if], data = [none] U.putObject(t, BLOCKER, null); // depends on control dependency: [if], data = [none] } else if (U.compareAndSwapObject(this, SLOT, p, null)) { v = timed && ns <= 0L && !t.isInterrupted() ? TIMED_OUT : null; // depends on control dependency: [if], data = [none] break; } } U.putOrderedObject(p, MATCH, null); p.item = null; p.hash = h; return v; } }
public class class_name { public void getAllExpressions(Collection<Expression2> accumulator) { accumulator.add(rootExpression); for (int i = 0; i < substitutions.size(); i++) { substitutions.get(i).getAllExpressions(accumulator); } for (int i = 0; i < lefts.size(); i++) { lefts.get(i).getAllExpressions(accumulator); rights.get(i).getAllExpressions(accumulator); } } }
public class class_name { public void getAllExpressions(Collection<Expression2> accumulator) { accumulator.add(rootExpression); for (int i = 0; i < substitutions.size(); i++) { substitutions.get(i).getAllExpressions(accumulator); // depends on control dependency: [for], data = [i] } for (int i = 0; i < lefts.size(); i++) { lefts.get(i).getAllExpressions(accumulator); // depends on control dependency: [for], data = [i] rights.get(i).getAllExpressions(accumulator); // depends on control dependency: [for], data = [i] } } }
public class class_name { @Override public PointersPair alloc(AllocationStatus targetMode, AllocationPoint point, AllocationShape shape, boolean initialize) { long reqMemory = AllocationUtils.getRequiredMemory(shape); CudaContext context = getCudaContext(); switch (targetMode) { case HOST: { if (MemoryTracker.getInstance().getActiveHostAmount() + reqMemory >= configuration.getMaximumZeroAllocation()) { while (MemoryTracker.getInstance().getActiveHostAmount() + reqMemory >= configuration.getMaximumZeroAllocation()) { val before = MemoryTracker.getInstance().getActiveHostAmount(); memoryProvider.purgeCache(); Nd4j.getMemoryManager().invokeGc(); val after = MemoryTracker.getInstance().getActiveHostAmount(); log.debug("[HOST] before: {}; after: {};", before, after); if (MemoryTracker.getInstance().getActiveHostAmount() + reqMemory >= configuration.getMaximumZeroAllocation()) { try { log.warn("No available [HOST] memory, sleeping for a while... Consider increasing -Xmx next time."); log.debug("Currently used: [" + zeroUseCounter.get() + "], allocated objects: [" + zeroAllocations.get(0) + "]"); memoryProvider.purgeCache(); Nd4j.getMemoryManager().invokeGc(); Thread.sleep(1000); } catch (Exception e) { throw new RuntimeException(e); } } } } PointersPair pair = memoryProvider.malloc(shape, point, targetMode); if (initialize) { org.bytedeco.javacpp.Pointer.memset(pair.getHostPointer(), 0, reqMemory); point.tickHostWrite(); } pickupHostAllocation(point); return pair; } case DEVICE: { int deviceId = getDeviceId(); PointersPair returnPair = new PointersPair(); PointersPair tmpPair = new PointersPair(); // if the initial memory location is device, there's a chance we don't have zero memory allocated if (point.getPointers() == null || point.getPointers().getHostPointer() == null) { tmpPair = alloc(AllocationStatus.HOST, point, point.getShape(), initialize); returnPair.setDevicePointer(tmpPair.getHostPointer()); returnPair.setHostPointer(tmpPair.getHostPointer()); point.setAllocationStatus(AllocationStatus.HOST); point.setPointers(tmpPair); } /* if (reqMemory < configuration.getMaximumSingleHostAllocation() && deviceMemoryTracker.getAllocatedSize(deviceId) + reqMemory < configuration .getMaximumDeviceAllocation()) { */ //val timeStart = System.nanoTime(); //long free = NativeOpsHolder.getInstance().getDeviceNativeOps().getDeviceFreeMemory(); //val timeEnd = System.nanoTime(); //log.info("Free time: {} ns; Free memory: {} bytes", (timeEnd - timeStart), free); if (deviceMemoryTracker.reserveAllocationIfPossible(Thread.currentThread().getId(), deviceId, reqMemory)) { point.setDeviceId(deviceId); val pair = memoryProvider.malloc(shape, point, targetMode); if (pair != null) { returnPair.setDevicePointer(pair.getDevicePointer()); point.setAllocationStatus(AllocationStatus.DEVICE); if (point.getPointers() == null) throw new RuntimeException("PointersPair can't be null"); point.getPointers().setDevicePointer(pair.getDevicePointer()); deviceAllocations.get(deviceId).put(point.getObjectId(), point.getObjectId()); val p = point.getBucketId(); if (p != null) { val m = zeroAllocations.get(point.getBucketId()); // m can be null, if that's point from workspace - just no bucketId for it if (m != null) m.remove(point.getObjectId()); } deviceMemoryTracker.addToAllocation(Thread.currentThread().getId(), deviceId, reqMemory); // point.tickDeviceWrite(); point.tickHostWrite(); if (!initialize) { point.tickDeviceWrite(); point.tickHostRead(); } else { nativeOps.memsetAsync(pair.getDevicePointer(), 0, reqMemory, 0, context.getSpecialStream()); context.getSpecialStream().synchronize(); point.tickDeviceWrite(); point.tickHostRead(); //AtomicAllocator.getInstance().getFlowController().registerAction(ctx, point); } } else { log.warn("Out of [DEVICE] memory, host memory will be used instead: deviceId: [{}], requested bytes: [{}]; Approximate free bytes: {}; Real free bytes: {}", deviceId, reqMemory, MemoryTracker.getInstance().getApproximateFreeMemory(deviceId), MemoryTracker.getInstance().getPreciseFreeMemory(deviceId)); log.info("Total allocated dev_0: {}", MemoryTracker.getInstance().getActiveMemory(0)); log.info("Cached dev_0: {}", MemoryTracker.getInstance().getCachedAmount(0)); log.info("Allocated dev_0: {}", MemoryTracker.getInstance().getAllocatedAmount(0)); log.info("Workspace dev_0: {}", MemoryTracker.getInstance().getWorkspaceAllocatedAmount(0)); //log.info("Total allocated dev_1: {}", MemoryTracker.getInstance().getActiveMemory(1)); // if device memory allocation failed (aka returned NULL), keep using host memory instead returnPair.setDevicePointer(tmpPair.getHostPointer()); point.setAllocationStatus(AllocationStatus.HOST); Nd4j.getMemoryManager().invokeGc(); try { Thread.sleep(100); } catch (Exception e) { } } } else { log.warn("Hard limit on [DEVICE] memory hit, please consider tuning memory parameters, deviceId [{}]", deviceId); Nd4j.getMemoryManager().invokeGc(); try { Thread.sleep(100); } catch (InterruptedException e) { // } } return returnPair; } default: throw new IllegalStateException("Can't allocate memory on target [" + targetMode + "]"); } } }
public class class_name { @Override public PointersPair alloc(AllocationStatus targetMode, AllocationPoint point, AllocationShape shape, boolean initialize) { long reqMemory = AllocationUtils.getRequiredMemory(shape); CudaContext context = getCudaContext(); switch (targetMode) { case HOST: { if (MemoryTracker.getInstance().getActiveHostAmount() + reqMemory >= configuration.getMaximumZeroAllocation()) { while (MemoryTracker.getInstance().getActiveHostAmount() + reqMemory >= configuration.getMaximumZeroAllocation()) { val before = MemoryTracker.getInstance().getActiveHostAmount(); memoryProvider.purgeCache(); // depends on control dependency: [while], data = [none] Nd4j.getMemoryManager().invokeGc(); // depends on control dependency: [while], data = [none] val after = MemoryTracker.getInstance().getActiveHostAmount(); log.debug("[HOST] before: {}; after: {};", before, after); // depends on control dependency: [while], data = [none] if (MemoryTracker.getInstance().getActiveHostAmount() + reqMemory >= configuration.getMaximumZeroAllocation()) { try { log.warn("No available [HOST] memory, sleeping for a while... Consider increasing -Xmx next time."); // depends on control dependency: [try], data = [none] log.debug("Currently used: [" + zeroUseCounter.get() + "], allocated objects: [" + zeroAllocations.get(0) + "]"); // depends on control dependency: [try], data = [none] memoryProvider.purgeCache(); // depends on control dependency: [try], data = [none] Nd4j.getMemoryManager().invokeGc(); // depends on control dependency: [try], data = [none] Thread.sleep(1000); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] } } } PointersPair pair = memoryProvider.malloc(shape, point, targetMode); if (initialize) { org.bytedeco.javacpp.Pointer.memset(pair.getHostPointer(), 0, reqMemory); // depends on control dependency: [if], data = [none] point.tickHostWrite(); // depends on control dependency: [if], data = [none] } pickupHostAllocation(point); return pair; } case DEVICE: { int deviceId = getDeviceId(); PointersPair returnPair = new PointersPair(); PointersPair tmpPair = new PointersPair(); // if the initial memory location is device, there's a chance we don't have zero memory allocated if (point.getPointers() == null || point.getPointers().getHostPointer() == null) { tmpPair = alloc(AllocationStatus.HOST, point, point.getShape(), initialize); // depends on control dependency: [if], data = [none] returnPair.setDevicePointer(tmpPair.getHostPointer()); // depends on control dependency: [if], data = [none] returnPair.setHostPointer(tmpPair.getHostPointer()); // depends on control dependency: [if], data = [none] point.setAllocationStatus(AllocationStatus.HOST); // depends on control dependency: [if], data = [none] point.setPointers(tmpPair); // depends on control dependency: [if], data = [none] } /* if (reqMemory < configuration.getMaximumSingleHostAllocation() && deviceMemoryTracker.getAllocatedSize(deviceId) + reqMemory < configuration .getMaximumDeviceAllocation()) { */ //val timeStart = System.nanoTime(); //long free = NativeOpsHolder.getInstance().getDeviceNativeOps().getDeviceFreeMemory(); //val timeEnd = System.nanoTime(); //log.info("Free time: {} ns; Free memory: {} bytes", (timeEnd - timeStart), free); if (deviceMemoryTracker.reserveAllocationIfPossible(Thread.currentThread().getId(), deviceId, reqMemory)) { point.setDeviceId(deviceId); // depends on control dependency: [if], data = [none] val pair = memoryProvider.malloc(shape, point, targetMode); if (pair != null) { returnPair.setDevicePointer(pair.getDevicePointer()); // depends on control dependency: [if], data = [(pair] point.setAllocationStatus(AllocationStatus.DEVICE); // depends on control dependency: [if], data = [none] if (point.getPointers() == null) throw new RuntimeException("PointersPair can't be null"); point.getPointers().setDevicePointer(pair.getDevicePointer()); // depends on control dependency: [if], data = [(pair] deviceAllocations.get(deviceId).put(point.getObjectId(), point.getObjectId()); // depends on control dependency: [if], data = [none] val p = point.getBucketId(); if (p != null) { val m = zeroAllocations.get(point.getBucketId()); // m can be null, if that's point from workspace - just no bucketId for it if (m != null) m.remove(point.getObjectId()); } deviceMemoryTracker.addToAllocation(Thread.currentThread().getId(), deviceId, reqMemory); // depends on control dependency: [if], data = [none] // point.tickDeviceWrite(); point.tickHostWrite(); // depends on control dependency: [if], data = [none] if (!initialize) { point.tickDeviceWrite(); // depends on control dependency: [if], data = [none] point.tickHostRead(); // depends on control dependency: [if], data = [none] } else { nativeOps.memsetAsync(pair.getDevicePointer(), 0, reqMemory, 0, context.getSpecialStream()); // depends on control dependency: [if], data = [none] context.getSpecialStream().synchronize(); // depends on control dependency: [if], data = [none] point.tickDeviceWrite(); // depends on control dependency: [if], data = [none] point.tickHostRead(); // depends on control dependency: [if], data = [none] //AtomicAllocator.getInstance().getFlowController().registerAction(ctx, point); } } else { log.warn("Out of [DEVICE] memory, host memory will be used instead: deviceId: [{}], requested bytes: [{}]; Approximate free bytes: {}; Real free bytes: {}", deviceId, reqMemory, MemoryTracker.getInstance().getApproximateFreeMemory(deviceId), MemoryTracker.getInstance().getPreciseFreeMemory(deviceId)); // depends on control dependency: [if], data = [none] log.info("Total allocated dev_0: {}", MemoryTracker.getInstance().getActiveMemory(0)); // depends on control dependency: [if], data = [none] log.info("Cached dev_0: {}", MemoryTracker.getInstance().getCachedAmount(0)); // depends on control dependency: [if], data = [none] log.info("Allocated dev_0: {}", MemoryTracker.getInstance().getAllocatedAmount(0)); // depends on control dependency: [if], data = [none] log.info("Workspace dev_0: {}", MemoryTracker.getInstance().getWorkspaceAllocatedAmount(0)); // depends on control dependency: [if], data = [none] //log.info("Total allocated dev_1: {}", MemoryTracker.getInstance().getActiveMemory(1)); // if device memory allocation failed (aka returned NULL), keep using host memory instead returnPair.setDevicePointer(tmpPair.getHostPointer()); // depends on control dependency: [if], data = [none] point.setAllocationStatus(AllocationStatus.HOST); // depends on control dependency: [if], data = [none] Nd4j.getMemoryManager().invokeGc(); // depends on control dependency: [if], data = [none] try { Thread.sleep(100); // depends on control dependency: [try], data = [none] } catch (Exception e) { } // depends on control dependency: [catch], data = [none] } } else { log.warn("Hard limit on [DEVICE] memory hit, please consider tuning memory parameters, deviceId [{}]", deviceId); Nd4j.getMemoryManager().invokeGc(); try { Thread.sleep(100); // depends on control dependency: [if], data = [none] } catch (InterruptedException e) { // } } return returnPair; } default: throw new IllegalStateException("Can't allocate memory on target [" + targetMode + "]"); } } }
public class class_name { boolean isVertex(double x, double y) { int cnt = points.numRows; double[] d = points.data; for (int ii=0;ii<cnt;ii++) { if (x == d[2*ii] && y== d[2*ii+1]) { return true; } } return false; } }
public class class_name { boolean isVertex(double x, double y) { int cnt = points.numRows; double[] d = points.data; for (int ii=0;ii<cnt;ii++) { if (x == d[2*ii] && y== d[2*ii+1]) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { @Override public List<String> setTargetHostsFromList(List<String> targetHosts) { List<String> targetHostsNew = new ArrayList<String>(); targetHostsNew.addAll(targetHosts); int dupSize = PcTargetHostsUtils.removeDuplicateNodeList(targetHostsNew); if (dupSize > 0) { logger.info("get target hosts with duplicated hosts of " + dupSize + " with new total size of " + targetHosts.size()); } return targetHostsNew; } }
public class class_name { @Override public List<String> setTargetHostsFromList(List<String> targetHosts) { List<String> targetHostsNew = new ArrayList<String>(); targetHostsNew.addAll(targetHosts); int dupSize = PcTargetHostsUtils.removeDuplicateNodeList(targetHostsNew); if (dupSize > 0) { logger.info("get target hosts with duplicated hosts of " + dupSize + " with new total size of " + targetHosts.size()); // depends on control dependency: [if], data = [none] } return targetHostsNew; } }
public class class_name { @Nonnull public BugInstance setProperty(String name, String value) { BugProperty prop = lookupProperty(name); if (prop != null) { prop.setValue(value); } else { prop = new BugProperty(name, value); addProperty(prop); } return this; } }
public class class_name { @Nonnull public BugInstance setProperty(String name, String value) { BugProperty prop = lookupProperty(name); if (prop != null) { prop.setValue(value); // depends on control dependency: [if], data = [none] } else { prop = new BugProperty(name, value); // depends on control dependency: [if], data = [none] addProperty(prop); // depends on control dependency: [if], data = [(prop] } return this; } }
public class class_name { @SuppressWarnings("unchecked") private static <T extends Comparable<T>> int compare(T o1, T o2) { if (o1 instanceof PMessage && o2 instanceof PMessage) { return compareMessages((PMessage) o1, (PMessage) o2); } return o1.compareTo(o2); } }
public class class_name { @SuppressWarnings("unchecked") private static <T extends Comparable<T>> int compare(T o1, T o2) { if (o1 instanceof PMessage && o2 instanceof PMessage) { return compareMessages((PMessage) o1, (PMessage) o2); // depends on control dependency: [if], data = [none] } return o1.compareTo(o2); } }
public class class_name { private void visitInvoke(InvokeInstruction obj) { assert obj != null; try { TaintMethodConfig methodConfig = getMethodConfig(obj); ObjectType realInstanceClass = (methodConfig == null) ? null : methodConfig.getOutputTaint().getRealInstanceClass(); Taint taint = getMethodTaint(methodConfig); assert taint != null; if (FindSecBugsGlobalConfig.getInstance().isDebugTaintState()) { taint.setDebugInfo(obj.getMethodName(cpg) + "()"); //TODO: Deprecated debug info } taint.addSource(new UnknownSource(UnknownSourceType.RETURN,taint.getState()).setSignatureMethod(obj.getClassName(cpg).replace(".","/")+"."+obj.getMethodName(cpg)+obj.getSignature(cpg))); if (taint.isUnknown()) { taint.addLocation(getTaintLocation(), false); } taintMutableArguments(methodConfig, obj); transferTaintToMutables(methodConfig, taint); // adds variable index to taint too Taint taintCopy = new Taint(taint); // return type is not always the instance type taintCopy.setRealInstanceClass(realInstanceClass); TaintFrame tf = getFrame(); int stackDepth = tf.getStackDepth(); int nbParam = getNumWordsConsumed(obj); List<Taint> parameters = new ArrayList<>(nbParam); for(int i=0;i<Math.min(stackDepth,nbParam);i++) { parameters.add(new Taint(tf.getStackValue(i))); } modelInstruction(obj, getNumWordsConsumed(obj), getNumWordsProduced(obj), taintCopy); for(TaintFrameAdditionalVisitor visitor : visitors) { try { visitor.visitInvoke(obj, methodGen, getFrame() , parameters, cpg); } catch (Throwable e) { LOG.log(Level.SEVERE,"Error while executing "+visitor.getClass().getName(),e); } } } catch (Exception e) { String className = ClassName.toSlashedClassName(obj.getReferenceType(cpg).toString()); String methodName = obj.getMethodName(cpg); String signature = obj.getSignature(cpg); throw new RuntimeException("Unable to call " + className + '.' + methodName + signature, e); } } }
public class class_name { private void visitInvoke(InvokeInstruction obj) { assert obj != null; try { TaintMethodConfig methodConfig = getMethodConfig(obj); ObjectType realInstanceClass = (methodConfig == null) ? null : methodConfig.getOutputTaint().getRealInstanceClass(); Taint taint = getMethodTaint(methodConfig); assert taint != null; if (FindSecBugsGlobalConfig.getInstance().isDebugTaintState()) { taint.setDebugInfo(obj.getMethodName(cpg) + "()"); //TODO: Deprecated debug info // depends on control dependency: [if], data = [none] } taint.addSource(new UnknownSource(UnknownSourceType.RETURN,taint.getState()).setSignatureMethod(obj.getClassName(cpg).replace(".","/")+"."+obj.getMethodName(cpg)+obj.getSignature(cpg))); // depends on control dependency: [try], data = [none] if (taint.isUnknown()) { taint.addLocation(getTaintLocation(), false); // depends on control dependency: [if], data = [none] } taintMutableArguments(methodConfig, obj); // depends on control dependency: [try], data = [none] transferTaintToMutables(methodConfig, taint); // adds variable index to taint too // depends on control dependency: [try], data = [none] Taint taintCopy = new Taint(taint); // return type is not always the instance type taintCopy.setRealInstanceClass(realInstanceClass); // depends on control dependency: [try], data = [none] TaintFrame tf = getFrame(); int stackDepth = tf.getStackDepth(); int nbParam = getNumWordsConsumed(obj); List<Taint> parameters = new ArrayList<>(nbParam); for(int i=0;i<Math.min(stackDepth,nbParam);i++) { parameters.add(new Taint(tf.getStackValue(i))); // depends on control dependency: [for], data = [i] } modelInstruction(obj, getNumWordsConsumed(obj), getNumWordsProduced(obj), taintCopy); // depends on control dependency: [try], data = [none] for(TaintFrameAdditionalVisitor visitor : visitors) { try { visitor.visitInvoke(obj, methodGen, getFrame() , parameters, cpg); // depends on control dependency: [try], data = [none] } catch (Throwable e) { LOG.log(Level.SEVERE,"Error while executing "+visitor.getClass().getName(),e); } // depends on control dependency: [catch], data = [none] } } catch (Exception e) { String className = ClassName.toSlashedClassName(obj.getReferenceType(cpg).toString()); String methodName = obj.getMethodName(cpg); String signature = obj.getSignature(cpg); throw new RuntimeException("Unable to call " + className + '.' + methodName + signature, e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private HyperBoundingBox mbr(final int[] entries, final int from, final int to) { SpatialEntry first = this.node.getEntry(entries[from]); ModifiableHyperBoundingBox mbr = new ModifiableHyperBoundingBox(first); for(int i = from + 1; i < to; i++) { mbr.extend(this.node.getEntry(entries[i])); } return mbr; } }
public class class_name { private HyperBoundingBox mbr(final int[] entries, final int from, final int to) { SpatialEntry first = this.node.getEntry(entries[from]); ModifiableHyperBoundingBox mbr = new ModifiableHyperBoundingBox(first); for(int i = from + 1; i < to; i++) { mbr.extend(this.node.getEntry(entries[i])); // depends on control dependency: [for], data = [i] } return mbr; } }
public class class_name { protected void saveWorkFlow() { /*log.fine("void saveWorkFlow(): called");*/ // Cycle through all the accessed screens in the work flow while (!accessedScreens.isEmpty()) { WorkFlowScreenPanel nextScreen = (WorkFlowScreenPanel) accessedScreens.pop(); // Check if the screen has unsaved state and call its save work method if so if (nextScreen.getState().getState().equals(WorkFlowScreenState.NOT_SAVED)) { nextScreen.saveWork(); } } // Call the save work method for the entire work flow controller to finalize the work flow saveWork(); } }
public class class_name { protected void saveWorkFlow() { /*log.fine("void saveWorkFlow(): called");*/ // Cycle through all the accessed screens in the work flow while (!accessedScreens.isEmpty()) { WorkFlowScreenPanel nextScreen = (WorkFlowScreenPanel) accessedScreens.pop(); // Check if the screen has unsaved state and call its save work method if so if (nextScreen.getState().getState().equals(WorkFlowScreenState.NOT_SAVED)) { nextScreen.saveWork(); // depends on control dependency: [if], data = [none] } } // Call the save work method for the entire work flow controller to finalize the work flow saveWork(); } }
public class class_name { public static Tuple3<List<Point2D_F64>,List<Point2D_F64>,List<Point2D_F64>> split3(List<AssociatedTriple> input ) { List<Point2D_F64> list1 = new ArrayList<>(); List<Point2D_F64> list2 = new ArrayList<>(); List<Point2D_F64> list3 = new ArrayList<>(); for (int i = 0; i < input.size(); i++) { list1.add( input.get(i).p1 ); list2.add( input.get(i).p2 ); list3.add( input.get(i).p3 ); } return new Tuple3<>(list1,list2,list3); } }
public class class_name { public static Tuple3<List<Point2D_F64>,List<Point2D_F64>,List<Point2D_F64>> split3(List<AssociatedTriple> input ) { List<Point2D_F64> list1 = new ArrayList<>(); List<Point2D_F64> list2 = new ArrayList<>(); List<Point2D_F64> list3 = new ArrayList<>(); for (int i = 0; i < input.size(); i++) { list1.add( input.get(i).p1 ); // depends on control dependency: [for], data = [i] list2.add( input.get(i).p2 ); // depends on control dependency: [for], data = [i] list3.add( input.get(i).p3 ); // depends on control dependency: [for], data = [i] } return new Tuple3<>(list1,list2,list3); } }